Exemplo n.º 1
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)
    {
        logMessage("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("TCP: Nothing to read");
#endif
            continue;
        }

        if (!recvBuffer->startsWith("POST") && !recvBuffer->startsWith("GET")) // Not HTTP, clear the buffer
        {
#if DEBUG_LOG
            logMessage(QString("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
                {
                    logMessage("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("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
                {
                    data.truncate(length);

                    // Process data, if the buffer is not empty, keep reading
                    tcpProcessData(data, socket);
                    // Delete the processed message from the buffer
                    *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("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())
                        {
                            logMessage("Can't open header : "+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("Sent log to "+socket->peerAddress().toString());
                        continue;
                    }
                    // Other GETs (not getlog)
                    data = removeHTTPHeader(data, "POST ");
                    data = removeHTTPHeader(data, "GET ");
                    logMessage("TCP: Replying to HTTP GET "+path);
                    QFile head(QString(NETDATAPATH)+"/dataHeader.bin");
                    QFile res("data/"+path);
                    head.open(QIODevice::ReadOnly);
                    if (!head.isOpen())
                    {
                        logMessage("TCP: Can't open header : "+head.errorString());
                        continue;
                    }
                    res.open(QIODevice::ReadOnly);
                    if (!res.isOpen())
                    {
                        logMessage("TCP: File not found");
                        head.close();
                        QFile head404(QString(NETDATAPATH)+"/notmodified.bin");
                        head404.open(QIODevice::ReadOnly);
                        if (!head404.isOpen())
                        {
                            logMessage("TCP: Can't open 304 Not Modified header : "+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("TCP: Sent "+QString().setNum(res.size()+head.size())+" bytes");
#endif
                }
            } while (i1 != -1);

            *recvBuffer = recvBuffer->mid(dataSize);
        }
    }
}
Exemplo n.º 2
0
void SharedDaemon::handleConnection()
{
    QTcpSocket *socket = nextPendingConnection();

    if ( !socket ) return;

    //the connecting socket should have sent password..
    //the client should be sending a password..
    socket->waitForReadyRead();

    if (!socket->bytesAvailable())
    {
        //std::cout << "no bytes available to read" << std::endl;
        socket->close();
        return;
    }
    std::cout << "user: "******" is attempting to connect" << std::endl;

    QAbstractSocket* finalSocket = NULL;
    ConnectionType typeOfConnection = TcpConnection;

    QByteArray result = socket->readAll();
    QString input(result);

    /// initial connection must pass password, but can optionally pass
    /// whether the client canRender and what the threshold value should be..
    JSONNode output;

    /// check if this is a WebSocketConnection
    QString response = "";
    if(input.startsWith("{") && ParseInput(input,output))
    {
        finalSocket = socket;
        typeOfConnection = TcpConnection;
    } /// check if this is a WebSocketConnection..
    else if(QWsSocket::initializeWebSocket(result,response))
    {
        /// this is a websocket connection, respond and get frame..
        socket->write(response.toLatin1());
        socket->flush();

        QEventLoop loop;

        matched_input = "";

        QWsSocket* wssocket = new QWsSocket(socket);

        connect(wssocket,SIGNAL(frameReceived(QString)),
                this,SLOT(getPasswordMessage(QString)));

        connect(wssocket,SIGNAL(frameReceived(QString)),
                &loop,SLOT(quit()));

        /// wait for password to be sent ..
        /// std::cout << "waiting for password from websocket" << std::endl;
        loop.exec();

        disconnect(wssocket,SIGNAL(frameReceived(QString)),
                this,SLOT(getPasswordMessage(QString)));

        disconnect(wssocket,SIGNAL(frameReceived(QString)),
                &loop,SLOT(quit()));

        //std::cout << matched_input.toStdString() << std::endl;

        if( !ParseInput(matched_input,output) )
        {
            //std::cout << "passwords do not match: "
            //          << matched_password.toStdString()
            //          << " " << password << std::endl;

            wssocket->close("passwords do not match or operation timed out");

            if(socket->state() != QAbstractSocket::UnconnectedState)
                socket->waitForDisconnected();

            wssocket->deleteLater();
            return;
        }

        finalSocket = wssocket;
        typeOfConnection = WSocketConnection;

    } /// not sure what connection this is, reject it..
    else
    {
        //send rejection notice..
        std::string errorString = "Unknown connection..";
        socket->write(errorString.c_str(),errorString.length());
        socket->disconnectFromHost();
        socket->waitForDisconnected();
        return;
    }

    //passwords match enable RemoteProcess and get port remote Process is listening to.
    //send host,port,security_key and whatever else so that remote machine can successfully reverse connect
    std::string program = "remoteApp";
    std::string clientName = "newclient1";

    ViewerClientConnection *newClient = new
            ViewerClientConnection(subject->GetViewerState(),
                                   this,
                                   clientName.c_str(),
                                   true);

    ViewerClientAttributes& clientAtts = newClient->GetViewerClientAttributes();
    JSONNode::JSONObject jo = output.GetJsonObject();

    clientAtts.SetExternalClient(true);

    if(jo.count("name") == 0 || jo["name"].GetString().size() == 0)
        clientAtts.SetTitle(socket->peerAddress().toString().toStdString());
    else
        clientAtts.SetTitle(jo["name"].GetString());

    if(jo.count("windowIds") > 0 && jo["windowIds"].GetType() == JSONNode::JSONARRAY)
    {
        const JSONNode::JSONArray& array = jo["windowIds"].GetArray();

        for(size_t i = 0; i < array.size(); ++i)
        {
            const JSONNode& node = array[i];

            if(node.GetType() != JSONNode::JSONINTEGER)
                continue;

            std::cout << clientAtts.GetTitle() <<  " requesting window: " << node.GetInt() << " " << std::endl;
            clientAtts.GetWindowIds().push_back(node.GetInt());
        }
    }

    if(jo.count("geometry") > 0)
    {
        std::string geometry = jo["geometry"].GetString();

        /// split into width & height...
        size_t index = geometry.find("x");
        if(index != std::string::npos && index != 0 && index != geometry.size()-1)
        {
            int geometryWidth = atoi(geometry.substr(0,index).c_str());
            int geometryHeight = atoi(geometry.substr(index+1).c_str());

            clientAtts.SetImageWidth(geometryWidth);
            clientAtts.SetImageHeight(geometryHeight);
            //std::cout << "geometry: " << clientAtts.clientWidth << " " << clientAtts.clientHeight << std::endl;
        }
    }

    /// advanced rendering can be true or false (image only), or string none,image,data
    if(jo.count("canRender") == 0) {
        clientAtts.SetRenderingType(ViewerClientAttributes::None);
        clientAtts.GetRenderingTypes().push_back(ViewerClientAttributes::None);
    }
    else
    {
        const JSONNode& node = jo["canRender"];
        QString type = node.GetString().c_str();
        type = type.toLower();

        /// TODO: remove the boolean check and make all current clients comply..
        if(node.GetType() == JSONNode::JSONBOOL) {
            clientAtts.SetRenderingType( node.GetBool() ? ViewerClientAttributes::Image :
                                                          ViewerClientAttributes::None);
            clientAtts.GetRenderingTypes().push_back(node.GetBool() ? ViewerClientAttributes::Image :
                                                                      ViewerClientAttributes::None);
        }
        else if(node.GetType() == JSONNode::JSONSTRING)
        {
            if(type == "image") {
                clientAtts.SetRenderingType(ViewerClientAttributes::Image);
                clientAtts.GetRenderingTypes().push_back((int)ViewerClientAttributes::Image);
            }
            else if(type == "data") {
                clientAtts.SetRenderingType(ViewerClientAttributes::Data);
                clientAtts.GetRenderingTypes().push_back((int)ViewerClientAttributes::Data);
            }
            else {
                clientAtts.SetRenderingType(ViewerClientAttributes::None);
                clientAtts.GetRenderingTypes().push_back((int)ViewerClientAttributes::None);
            }
        }
        else
        {
            clientAtts.SetRenderingType(ViewerClientAttributes::None);
            clientAtts.GetRenderingTypes().push_back((int)ViewerClientAttributes::None);
        }
    }
    stringVector args;

    /// assign whether connection is of type WebSocket or TCPConnection
    /// Register Type & Register Callback
    RemoteProcess::SetCustomConnectionCallback(createCustomConnection,&typeOfConnection);

    TRY
    {
        void* data[3];
        data[0] = &typeOfConnection;
        data[1] = (void*)finalSocket;
        data[2] = (void*)subject->GetViewerState();

        newClient->LaunchClient(program,args,AddNewClient,data,0,0);

        /// Now that client has launched RemoveCallback..
        subject->AddNewViewerClientConnection(newClient);
        std::cout << "user: "******" successfully connected" << std::endl;
    }
    CATCHALL
    {
        std::cout << "user: "******" failed to connected" << std::endl;
        delete newClient;
    }
    ENDTRY

    RemoteProcess::SetCustomConnectionCallback(0,0); /// reset connection..
}
Exemplo n.º 3
0
void CClientApp::sendCommandToServer(QVariantMap cmdMap)
{
    QTcpSocket *socket = new QTcpSocket(this);
    //serverIP = "192.168.0.238";

    QString command = cmdMap["command"].toString();
    QJsonObject jsonObj;

    if (command == "listDevices")
    {
        jsonObj.insert("command", command);
    }
    else if (command == "listCommands")
    {
        QString deviceUID = cmdMap["uid"].toString();
        jsonObj.insert("command", command);
        jsonObj.insert("uid", deviceUID);
    }
    else if (command == "sendCommandToDevice")
    {
        QString deviceUID = cmdMap["uid"].toString();
        QString deviceCmd = cmdMap["deviceCmd"].toString();
        QString deviceParam = cmdMap["param"].toString();
        jsonObj.insert("command", command);
        jsonObj.insert("uid", deviceUID);
        jsonObj.insert("deviceCmd", deviceCmd);
        jsonObj.insert("param", deviceParam);
    }

    QJsonDocument doc(jsonObj);
    Q_EMIT m_pSender->commandReturned("SendCmdToServer: " + QString::fromLatin1(doc.toJson()) + "\n", false);

    QObject::connect(socket, &QTcpSocket::readyRead, [=]
    {
        QByteArray byteArray = socket->readAll();
        QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray);
        QJsonObject jsonObj = jsonDoc.object();

        QString kText("Cmd Return Result: " + QString::number(jsonObj["status"].toInt()) + "\n");
        if (jsonObj["status"].toInt() == 200)
        {
            QVariantMap retMap = jsonObj.toVariantMap();
            qDebug() << jsonObj["devices"].toArray().size();
            parseDataToQML(retMap);
            kText += QString::fromLatin1(byteArray) + "\n";
        }
        Q_EMIT m_pSender->commandReturned(kText, false);
        socket->disconnectFromHost();
    });

    QObject::connect(socket, &QTcpSocket::disconnected, [=]
    {
        socket->deleteLater();
    });

    socket->connectToHost(serverIP, 3479, QIODevice::ReadWrite);

    socket->write(doc.toJson());
    bool bSentCmd = socket->waitForBytesWritten();
    QString result = (bSentCmd ? "true" : "false");
    Q_EMIT m_pSender->commandReturned("Cmd Sent: " + result, false);
}
Exemplo n.º 4
0
void CClient::readyRead()
{
    QTcpSocket *socket = m_socket;

    QByteArray data = socket->readAll(); //-- QINT64
    QByteArray code = data.left(500); //-- On prend un échantillon pour voir le code
    QString ligne = QString(code);

    if (ligne.length() > 0)
    {
        //-- On analyse ce qu'on a reçu à savoir si c'est un code de commande
        if (ligne.at(0) == COMMAND_CODE)
        {
            QStringList lst = ligne.split('|');

            if (lst[0] == "%SURNOM")
            {
                ligne = QString(data);
                lst = ligne.split('|');

                m_Surnom = lst[1];
                emit signalUserName(GetNomClient());

                //-- On répond pour dire que nous avons reçu la commande
                QByteArray bOK;
                bOK.append(QString("%OK"));
                socket->write(bOK);
                socket->waitForBytesWritten();

                sleep(1);

                emit demandeEnvoiListeClients();
            }

            if (lst[0] == "%MESSAGE")
            {
                ligne = QString(data);
                lst = ligne.split('|');

                emit transmetMessage(lst[1], lst[2], lst[3]);
            }

            if (lst[0] == "%FICHIER")
            {               
                //-- %1 - Source
                //-- %2 - Destinataire
                //-- %3 - Nb bytes ecrit
                //-- %4 - Nb bytes total
                //-- %5 - Nom fichier
                //-- %6 - Data

                //QMessageBox::information(0, "", QString("%1|%2|%3|%4|%5").arg(lst[1], lst[2], lst[3], lst[4], lst[5]));
                int posDepartImage = 7 + lst[1].length() + lst[2].length() + lst[3].length() + lst[4].length() + lst[5].length();

                emit transmetFichier(lst[1], lst[2], lst[3], lst[4], lst[5], data.right(data.count() - posDepartImage));
            }

            if (lst[0] == "%PING")
            {
                emit pingRecu(GetNomClient());
            }
        }
    }
}
Exemplo n.º 5
0
void Server::sendImage()
{
    //screenshot();

    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);

    out << (quint32)0;
    /*******************************/
    virConnectPtr conn = NULL; /* the hypervisor connection */
    virDomainPtr dom = NULL; /* the domain to be screenshotted */
    virStreamPtr st = NULL;
    char *mimetype = NULL;

    conn = virConnectOpen("qemu:///system");
    if (conn == NULL) {
        fprintf(stderr, "Failed to connect to hypervisor\n");
        if(st != NULL)
            virStreamFree(st);

        if(mimetype !=NULL)
            free(mimetype);

        if (dom != NULL)
            virDomainFree(dom);

        if (conn != NULL)
            virConnectClose(conn);

        return;
    }

    /* Find the domain of the given id */
    dom = virDomainLookupByName(conn, "win7-1");
    if (dom == NULL) {
        fprintf(stderr, "Failed to connect to hypervisor\n");
        if(st != NULL)
            virStreamFree(st);

        if(mimetype !=NULL)
            free(mimetype);

        if (dom != NULL)
            virDomainFree(dom);

        if (conn != NULL)
            virConnectClose(conn);

        return;
    }

    st = virStreamNew(conn, 0);
    mimetype = virDomainScreenshot(dom, st, 0, 0);
    if(mimetype == NULL) {
        fprintf(stderr, "Failed in virDomainScreenshot funcation\n");
        if(st != NULL)
            virStreamFree(st);

        if(mimetype !=NULL)
            free(mimetype);

        if (dom != NULL)
            virDomainFree(dom);

        if (conn != NULL)
            virConnectClose(conn);

        return;
    }

    if(virStreamRecvAll(st, mysink, &out) < 0) {
        fprintf(stderr, "Failed in virStreamRecvAll funcation\n");
        if(st != NULL)
            virStreamFree(st);

        if(mimetype !=NULL)
            free(mimetype);

        if (dom != NULL)
            virDomainFree(dom);

        if (conn != NULL)
            virConnectClose(conn);

        return;
    }

    if (virStreamFinish(st) < 0) {
        fprintf(stderr, "Failed in virStreamFinish funcation\n");
        if(st != NULL)
            virStreamFree(st);

        if(mimetype !=NULL)
            free(mimetype);

        if (dom != NULL)
            virDomainFree(dom);

        if (conn != NULL)
            virConnectClose(conn);

        return;
    }

    if(st != NULL)
        virStreamFree(st);

    if(mimetype !=NULL)
        free(mimetype);

    if (dom != NULL)
        virDomainFree(dom);

    if (conn != NULL)
        virConnectClose(conn);
    /*******************************/

    out.device()->seek(0);
    out << (quint32)(block.size() - sizeof(quint32));

    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    connect(clientConnection, SIGNAL(disconnected()),
            clientConnection, SLOT(deleteLater()));

    clientConnection->write(block);
    clientConnection->disconnectFromHost();

    QTextStream info(stdout);
    info << tr("has sended %1 bytes\n").arg(block.size() - 4);
}
Exemplo n.º 6
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    for(int i = 0 ; i < argc; i++){
        qDebug() << argv[i] << endl;
    }

    if(argc >= 4)
    {
        //Getting first argument for application
        QString arg = argv[1];
        //Sending mode
        if(arg == "send")
        {
            QTcpSocket *tcpSocket = new QTcpSocket(&a);
            QString port = argv[3];
            tcpSocket->connectToHost(QHostAddress(argv[2]), port.toInt());
            if(!tcpSocket->waitForConnected(10*1000)){
                qDebug() << "Connection cant be established to host: " << argv[2] << ", at port: " << port << endl;
            }else{
                //Sending mode = file
                QString type(argv[4]);
                if(type == "file")
                {
                    QFile file(argv[5]);
                    if(!file.open(QFile::ReadOnly))
                    {
                        qDebug() << "Cannot open file" << endl;
                    }else
                    {
                        qDebug() << "File size in bytes: " << file.size() << endl;
                        int counter = 0;
                        //Divide file into chunks of 300KB
                        int chunkSize = 3 * 100000;
                        while(counter < file.size()){
                                if(!file.seek(counter)){
                                    qDebug() << "Cant seek the file to : " << counter << endl;
                                }else{
                                    QByteArray buffer = file.read(chunkSize);
                                    if(!buffer.isEmpty()){
                                        int bytesWritten = tcpSocket->write(buffer);
                                        counter += bytesWritten;
                                        if(!tcpSocket->waitForBytesWritten(10*1000))
                                        {
                                            qDebug() << "Error no bytes written" << tcpSocket->errorString() << endl;
                                        }else
                                        {
                                            qDebug() << "Bytes for writting: " << buffer.size() << ", " << bytesWritten << " bytes written. " << endl;
                                        }
                                    }else{
                                      qDebug() << "0 bytes read from file, error: " << file.errorString() << endl;
                                      break;
                                    }
                                }
                        }

                    }
                //Sending mode = string
                }else if(type == "string")
                {
                    QByteArray data = argv[5];
                    int bytesWritten = tcpSocket->write(data);
                    if(!tcpSocket->waitForBytesWritten(10000))
                    {
                        qDebug() << "Error no bytes written" << tcpSocket->errorString() << endl;
                    }else
                    {
                        qDebug() << bytesWritten << " bytes written. " << endl;
                    }
                }else{
                    qDebug() << "Unknown sending format " << endl;
                }
            }
            tcpSocket->close();
            delete tcpSocket;
        //Receiving mode
        }else if(arg == "receive")
        {
            QTcpServer *tcpServer = new QTcpServer(&a);
            QString port = argv[3];
            if(!tcpServer->listen(QHostAddress(QString(argv[2])),port.toInt())){
                qDebug() << "Error, could not start listening, " << tcpServer->serverError() << endl;
            }else{

                QString fileName;
                QString destinationPath;
                //Getting name and path for the new file from user
                bool tryAgain = true;
                while(tryAgain){
                    qDebug() << "Enter filename for the new file (ex: picture.png) :";
                    QTextStream s(stdin);
                    fileName = s.readLine();
                    qDebug() << "Enter destination path: ";
                    QTextStream d(stdin);
                    destinationPath = d.readLine();
                    if (!fileName.isEmpty() && !destinationPath.isEmpty())
                    {
                        qDebug() << "The destination string: " << destinationPath + fileName;
                        tryAgain = false;
                    }else{
                        qDebug() << "You didnt enter filename, try again" << endl;
                    }
                }

                bool working = true;
                while(working){
                    if(tcpServer->waitForNewConnection(10*1000)){
                        QTcpSocket *sock = tcpServer->nextPendingConnection();
                        sock->waitForReadyRead(10*1000);
                        QByteArray receivedData;
                        QFile file_handle(destinationPath + fileName);
                        //While there is bytes available for receiving, receive them and write chunks of min 300KB to file
                        while(sock->bytesAvailable()){
                            qDebug() << sock->bytesAvailable() << " bytes available for writting" << endl;
                            receivedData.append(sock->readAll());
                            if(receivedData.size() > 3 * 100000){
                                if(!file_handle.isOpen()){
                                    if(!file_handle.open(QFile::WriteOnly | QFile::Append | QFile::Text)){
                                        qDebug() << "Could not open file for writing!" << endl;
                                    }else{
                                        file_handle.write(receivedData);
                                        file_handle.flush();
                                        file_handle.waitForBytesWritten(10*1000);
                                        qDebug() << "Written " << receivedData.size() << " to file. In KB = " << receivedData.size() / 1000 << endl;
                                        receivedData.clear();
                                    }
                                }else{
                                    file_handle.write(receivedData);
                                    file_handle.flush();
                                    file_handle.waitForBytesWritten(10*1000);
                                    qDebug() << "Written " << receivedData.size() << " to file. In KB = " << receivedData.size() / 1000 << endl;
                                    receivedData.clear();
                                }
                            }
                            sock->waitForReadyRead(10*1000);
                        }
                        file_handle.close();
                        //In case there is still data in buffer, but data is smaller than 300KB than append that remaining data to file also
                        if(receivedData.size() != 0){
                            qDebug() << "Preparing to write remaining chunks of data" << endl;
                            if(!file_handle.open(QFile::WriteOnly)){
                                qDebug() << "Could not open file for writing!" << endl;
                            }else{
                                file_handle.write(receivedData);
                                file_handle.flush();
                                file_handle.waitForBytesWritten(10*1000);
                                qDebug() << "Written " << receivedData.size() << " to file. In MB = " << receivedData.size() / 1000000 << endl;
                                receivedData.clear();
                                file_handle.close();
                            }
                        }

                        sock->close();
                        delete sock;
//                        file_thread->deleteLater();

                        qDebug() << "Should i wait for other request? (y/n) default = yes" ;
                        char  answer;
                        cin >> answer;
                        if(answer == 'n'){
                            working = false;
                            tcpServer->close();
                            delete tcpServer;
                        }
                    }else{
                        qDebug() << "No incoming connection" << endl;
                        qDebug() << "Should i check for another request? (Yes / No)" ;
                        char answer;
                        cin >> answer;
                        if(answer == 'n'){
                            working = false;
                            tcpServer->close();
                            delete tcpServer;
                        }
                    }
                }
Exemplo n.º 7
0
void HttpServerThread::run()
{
    m_server = new BlockingHttpServer(m_features & Ssl);
    m_server->listen();
    m_port = m_server->serverPort();
    m_ready.release();

    const bool doDebug = qgetenv("KDSOAP_DEBUG").toInt();

    if (doDebug)
        qDebug() << "HttpServerThread listening on port" << m_port;

    // Wait for first connection (we'll wait for further ones inside the loop)
    QTcpSocket *clientSocket = m_server->waitForNextConnectionSocket();
    Q_ASSERT(clientSocket);

    Q_FOREVER {
        // get the "request" packet
        if (doDebug) {
            qDebug() << "HttpServerThread: waiting for read";
        }
        if (clientSocket->state() == QAbstractSocket::UnconnectedState ||
            !clientSocket->waitForReadyRead(2000)) {
            if (clientSocket->state() == QAbstractSocket::UnconnectedState) {
                delete clientSocket;
                if (doDebug) {
                    qDebug() << "Waiting for next connection...";
                }
                clientSocket = m_server->waitForNextConnectionSocket();
                Q_ASSERT(clientSocket);
                continue; // go to "waitForReadyRead"
            } else {
                qDebug() << "HttpServerThread:" << clientSocket->error() << "waiting for \"request\" packet";
                break;
            }
        }
        const QByteArray request = m_partialRequest + clientSocket->readAll();
        if (doDebug) {
            qDebug() << "HttpServerThread: request:" << request;
        }

        // Split headers and request xml
        const bool splitOK = splitHeadersAndData(request, m_receivedHeaders, m_receivedData);
        if (!splitOK) {
            //if (doDebug)
            //    qDebug() << "Storing partial request" << request;
            m_partialRequest = request;
            continue;
        }

        m_headers = parseHeaders(m_receivedHeaders);

        if (m_headers.value("Content-Length").toInt() > m_receivedData.size()) {
            //if (doDebug)
            //    qDebug() << "Storing partial request" << request;
            m_partialRequest = request;
            continue;
        }

        m_partialRequest.clear();

        if (m_headers.value("_path").endsWith("terminateThread")) // we're asked to exit
            break; // normal exit

        // TODO compared with expected SoapAction
        QList<QByteArray> contentTypes = m_headers.value("Content-Type").split(';');
        if (contentTypes[0] == "text/xml" && m_headers.value("SoapAction").isEmpty()) {
            qDebug() << "ERROR: no SoapAction set for Soap 1.1";
            break;
        }else if( contentTypes[0] == "application/soap+xml" && !contentTypes[2].startsWith("action")){
            qDebug() << "ERROR: no SoapAction set for Soap 1.2";
            break;
        }

        //qDebug() << "headers received:" << m_receivedHeaders;
        //qDebug() << headers;
        //qDebug() << "data received:" << m_receivedData;


        if (m_features & BasicAuth) {
            QByteArray authValue = m_headers.value("Authorization");
            if (authValue.isEmpty())
                authValue = m_headers.value("authorization"); // as sent by Qt-4.5
            bool authOk = false;
            if (!authValue.isEmpty()) {
                //qDebug() << "got authValue=" << authValue; // looks like "Basic <base64 of user:pass>"
                Method method;
                QString headerVal;
                parseAuthLine(QString::fromLatin1(authValue.data(),authValue.size()), &method, &headerVal);
                //qDebug() << "method=" << method << "headerVal=" << headerVal;
                switch (method) {
                case None: // we want auth, so reject "None"
                    break;
                case Basic:
                    {
                        const QByteArray userPass = QByteArray::fromBase64(headerVal.toLatin1());
                        //qDebug() << userPass;
                        // TODO if (validateAuth(userPass)) {
                        if (userPass == ("kdab:testpass")) {
                            authOk = true;
                        }
                        break;
                    }
                default:
                    qWarning("Unsupported authentication mechanism %s", authValue.constData());
                }
            }

            if (!authOk) {
                // send auth request (Qt supports basic, ntlm and digest)
                const QByteArray unauthorized = "HTTP/1.1 401 Authorization Required\r\nWWW-Authenticate: Basic realm=\"example\"\r\nContent-Length: 0\r\n\r\n";
                clientSocket->write( unauthorized );
                if (!clientSocket->waitForBytesWritten(2000)) {
                    qDebug() << "HttpServerThread:" << clientSocket->error() << "writing auth request";
                    break;
                }
                continue;
            }
        }

        // send response
        QByteArray response = makeHttpResponse(m_dataToSend);
        if (doDebug) {
            qDebug() << "HttpServerThread: writing" << response;
        }
        clientSocket->write(response);

        clientSocket->flush();
    }
    // all done...
    delete clientSocket;
    delete m_server;
    if (doDebug) {
        qDebug() << "HttpServerThread terminated";
    }
}
void getActiveCellCenters(NDArray& cellCenterValues, const QString &hostName, quint16 port, const qint32& caseId, const QString& porosityModel)
{
    QString serverName = hostName;
    quint16 serverPort = port;

    const int timeout = riOctavePlugin::timeOutMilliSecs;

    QTcpSocket socket;
    socket.connectToHost(serverName, serverPort);

    if (!socket.waitForConnected(timeout))
    {
        error((("Connection: ") + socket.errorString()).toLatin1().data());
        return;
    }

    // Create command and send it:

    QString command = QString("GetActiveCellCenters %1 %2").arg(caseId).arg(porosityModel);
    QByteArray cmdBytes = command.toLatin1();

    QDataStream socketStream(&socket);
    socketStream.setVersion(riOctavePlugin::qtDataStreamVersion);

    socketStream << (qint64)(cmdBytes.size());
    socket.write(cmdBytes);

    // Get response. First wait for the header

    while (socket.bytesAvailable() < (int)(2 * sizeof(quint64)))
    {
        if (!socket.waitForReadyRead(timeout))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    // Read timestep count and blocksize

    quint64 activeCellCount;
    quint64 byteCount;

    socketStream >> activeCellCount;
    socketStream >> byteCount;

    if (!(byteCount && activeCellCount))
    {
        error ("Could not find the requested data in ResInsight");
        return;
    }

    dim_vector dv;
    dv.resize(2);
    dv(0) = activeCellCount;
    dv(1) = 3;

    cellCenterValues.resize(dv);

    while (socket.bytesAvailable() < (qint64)(byteCount))
    {
        if (!socket.waitForReadyRead(timeout))
        {
            error((("Waiting for data: ") + socket.errorString()).toLatin1().data());
            return;
        }
        OCTAVE_QUIT;
    }

    quint64 bytesRead = 0;
    double* internalMatrixData = cellCenterValues.fortran_vec();
    bytesRead = socket.read((char*)(internalMatrixData), byteCount);

    if (byteCount != bytesRead)
    {
        error("Could not read binary double data properly from socket");
        octave_stdout << "Active cell count: " << activeCellCount << std::endl;
    }

    return;
}
Exemplo n.º 9
0
/**
  This method will be invoked by Qt framework to read the incoming client HTTP 
  command from its client connection.
*
@param: none
*
@return: none
*******************************************************************************/
void CuteHttpServer::readRequestString()
{
    // who sent the Qt signal?
    QTcpSocket* conn = dynamic_cast<QTcpSocket*>(sender());
    assert(conn != 0);

    int connID = findSavedConn(conn);        
    assert(connID != -1);

    // read from socket
    char buff[1024 + 1];
    size_t readBytes;
    string leftoverBytes;
        
    while(true)
    {       
        readBytes = conn->read(buff, 1024);

        if(readBytes < 0) 
        {
            TRACE_ERR2("http_srv: error when reading from socket:", conn->errorString());
            break;
        }

        if(readBytes == 0)
            continue; // reader timeout

        string input(buff, readBytes);
        size_t pos = 0, lastpos = 0;
        size_t endMarkerSz = 2;
        bool leftover = false;
        size_t offset = 0;

        // partition input into single requests
        while(true)
        {
            // read HTTP lines:
            while(true)
            {
                pos = input.find(c_httpLineEnd, pos + 1);
               
                if(pos != string::npos)
                {
                    // end of req?
                    if(lastpos + 2 == pos)
                        // empty line!
                        break;
                    else
                    {
                        lastpos = pos;
                        continue;
                    }
                }
                else
                {
                    // incomplete!
                    leftover = true;
                    break;
                }
            }
            
            if(leftover)
            {
                TRACE_ERR(" TODO::: ############## - leftover");

                // return internal SVR error at the moment
                CuteSrvRequest dummy;
                string resp = 
                    m_parser.makeErrorResp(dummy, 500, "SORRY:: bad input parsing, lefover found!!!"); 

                // respond with 500
                conn->write(resp.c_str(), resp.size());
                conn->flush();
                break;
            }

            string req;
            string resp;            
            size_t len = 0;

            len = pos + endMarkerSz - offset;
            req.assign(input.c_str(), offset, len);                       

            if(TR_WEBIF) 
                TRACE2("http_srv: Request received=", req); 

            // start processing
            unsigned needMore = processRequest(req.c_str(), connID, resp);

            if(needMore)
            {
                string postData;

                // data already in buffer?
                if(pos + endMarkerSz + needMore <= readBytes)
                {
                    postData.append(input, pos,  endMarkerSz + needMore);
                }
                else
                {
                    TRACE_ERR(" TODO::: ############## - wait for more POST data");

                    // return internal SVR error at the moment
                    CuteSrvRequest dummy;
                    string resp = 
                        m_parser.makeErrorResp(dummy, 500, "SORRY:: bad input parsing, wait for POST data!!!"); 

                    // respond with 500
                    conn->write(resp.c_str(), resp.size());
                    conn->flush();
                    break;
                }

                processRequest(req.c_str(), connID, resp, &postData);
            }

            // respond
            conn->write(resp.c_str(), resp.size());
            conn->flush();

            // next request possible?                                
            pos += endMarkerSz;  

            if(pos == input.size())
                break;

            offset = pos;
        }

        // ????? ??? ? ?? 

        // all messages read!
        break;
    }

    // all data read!
    return;
}
Exemplo n.º 10
0
void getWellStatus(std::vector<QString>& wellTypes, std::vector<int>& wellStatuses, const QString &hostName, quint16 port, 
                        const qint64& caseId, const QString& wellName, const int32NDArray& requestedTimeSteps)
{
    QString serverName = hostName;
    quint16 serverPort = port;

    QTcpSocket socket;
    socket.connectToHost(serverName, serverPort);

    if (!socket.waitForConnected(riOctavePlugin::connectTimeOutMilliSecs))
    {
        error((("Connection: ") + socket.errorString()).toLatin1().data());
        return;
    }

    // Create command and send it:

    QString command;
    command += QString("GetWellStatus") + " " + QString::number(caseId) + " " + wellName;

    for (int i = 0; i < requestedTimeSteps.length(); ++i)
    {
        if (i == 0) command += " ";
        command += QString::number(static_cast<int>(requestedTimeSteps.elem(i)) - 1); // To make the index 0-based
        if (i != requestedTimeSteps.length() -1) command += " ";
    }

    QByteArray cmdBytes = command.toLatin1();

    QDataStream socketStream(&socket);
    socketStream.setVersion(riOctavePlugin::qtDataStreamVersion);

    socketStream << (qint64)(cmdBytes.size());
    socket.write(cmdBytes);

    // Get response. First wait for the header

    while (socket.bytesAvailable() < (int)(sizeof(quint64)))
    {
        if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    quint64 byteCount;
    socketStream >> byteCount;

    while (socket.bytesAvailable() < (int)(byteCount))
    {
        if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs))
        {
            error((("Waiting for data: ") + socket.errorString()).toLatin1().data());
            return;
        }
        OCTAVE_QUIT;
    }

    quint64 timeStepCount;
    socketStream >> timeStepCount;

    QString wellType;
    qint32 wellStatus;

    for (size_t i = 0; i < timeStepCount; i++)
    {
        socketStream >> wellType;
        socketStream >> wellStatus;

        wellTypes.push_back(wellType);
        wellStatuses.push_back(wellStatus);
    }

    return;
}
Exemplo n.º 11
0
/** A file is requested by the host
  *
  * This function is called when the client retirieve a file. The file
  * is sent to the client from the \c uploaded directory.
  *
  * \param filename The filename without path
  *
  */
void RainbruRPG::Network::Ftp::FtpTransfer::
commandRETR(const QString& filename){
  LOGI("Sending file...");
  QString s("Sending file ");
  s+=filename;
  emit(log(s));
  LOGI(s.toLatin1());
  nextCommand=FTC_RETR;

  // Get the absolute filename
  GlobalURI gu;
  std::string stdFilename(filename.toLatin1());
  std::string fullFileName=gu.getUploadFile(stdFilename);
  nextFilename=filename;
  nextOnlyFilename=filename;

  LOGCATS("Opening file '");
  LOGCATS(fullFileName.c_str());
  LOGCAT();

  QFile f(fullFileName.c_str());
  QIODevice::OpenMode om;

  // We are in Binary mode
  if (transferType==FTT_BINARY){
    om=QIODevice::ReadOnly;
  }
  // We are in ASCII mode
  else if (transferType==FTT_ASCII){
    om=QIODevice::ReadOnly|QIODevice::Text;
  }

  if(f.open(om)){
    QTcpSocket sock;
    if (waitForConnection(&sock)){
      emit(startTransferFile(filename, f.size()));
      int rep=0;
      
      while (!f.atEnd()){
	rep=sock.write(f.read(MAX_READ_LENGTH));
	if (rep==-1){
	  LOGE("An error occured during RETR command");
	  break;
	}
	else{
	  LOGCATS("Writing ");
	  LOGCATI(rep);
	  LOGCATS(" bytes");
	  LOGCAT();
	  
	  sock.waitForBytesWritten(3000);
	}
      }
      
      // Transfer complete
      emit(log("Transfer channel closed"));
      emit(transferComplete(filename));
      sock.disconnectFromHost();
      LOGI("Transfer complete");
      f.close();

    }
  }
  else{
    emit(log("An error occured during opening file :"));
    QFile::FileError fe=f.error();

    QString feText;
    if (fe==QFile::OpenError){
      feText=("5 The file could not be opened.");
    }
    else{
      feText.setNum(fe);
    }
    emit(log(feText));
  }
}
Exemplo n.º 12
0
void QMplayer::newConnection()
{
    QTcpSocket *con = tcpServer->nextPendingConnection();
    connect(con, SIGNAL(disconnected()),
            con, SLOT(deleteLater()));

    QByteArray req;
    while(con->waitForReadyRead(100))
    {
        req += con->readAll();
    }

    QString res;
    QTextStream buf(&req);
    buf.setCodec(QTextCodec::codecForName("utf8"));
    QString line;
    QString reqPath = "";           // path from http request
    QString filename = "";          // file on the disk
    QString encPath = "";           // transcoded file
    QString host = "";
    QFile file;
    bool sendFile = false;
    int itemIndex = 0;

    for(;;)
    {
        line = buf.readLine();
        if(line.isNull())
        {
            break;
        }
        if(line.startsWith("GET "))
        {
            int index = req.indexOf(' ', 4);
            if(index > 0)
            {
                reqPath = req.mid(4, index - 4);
                for(int i = 0; i < reqPath.count(); i++)
                {
                    if(reqPath.at(i) == '%')
                    {
                        i += 2;
                        if(i >= reqPath.count())
                        {
                            break;
                        }
                        QChar ch = (QChar)(reqPath.mid(i - 1, 2).toInt(0, 16));
                        reqPath.replace(i - 2, 3, ch);
                    }
                }
            }
        }
        else if(line.startsWith("Host: "))
        {
            host = line.right(line.length() - 6).trimmed();
        }
    }

    res.append("HTTP/1.0 200 OK\r\n");
    res.append("Content-Type: text/html; charset=utf-8\r\n\r\n");
    res.append("<html>");
    res.append("<body>");

    if(reqPath.length() == 0)
    {
        res.append("Valid GET request not found");
    }
    else if(host.length() == 0)
    {
        res.append("Host not found in html header");
    }
    else if(reqPath == "/")
    {
        QString dir = "";
        for(int i = 2; i < lw->count(); i++)
        {
            QListWidgetItem *item = lw->item(i);
            QString path = item->text();
            bool isDir = isDirectory(path);
            if(isDir)
            {
                res.append(path);
                res.append("</br>");
                dir = pathToUrl(path);
            }
            else
            {
                res.append("\r\n<a href=\"http://");
                res.append(host);
                res.append(dir);
                res.append(pathToUrl(path));
                res.append("\">");
                res.append(path);
                res.append("</a></br>\r\n");
            }
        }
    }
    else
    {
        res.append(reqPath);
        res.append("</br>");
        QString dir = "";
        QString testDir;
        for(int i = 2; i < lw->count(); i++)
        {
            QListWidgetItem *item = lw->item(i);
            QString path = item->text();
            QString testPath = pathToUrl(path);
            bool isDir = isDirectory(path);
            if(isDir)
            {
                dir = path;
                testDir = testPath;
            }
            else if(reqPath == (testDir + testPath))
            {
                filename = dir;
                if(!filename.endsWith('/') && !filename.endsWith('\\'))
                {
                    filename.append('/');
                }
                filename.append(path);
                itemIndex = i;
                break;
            }
        }
        if(filename.length() == 0)
        {
            res.append("file not found");
        }
        else
        {
            encPath = filename;
            // Encode just avi files for now
            if(encPath.endsWith(".avi") ||
               encPath.endsWith(".mp4"))
            {
                encPath.insert(encPath.lastIndexOf('.'), ".qmplayer");
            }
            QFileInfo fi(encPath);
            if(fi.exists())
            {
                QString size;
                size.setNum(fi.size());
                res.append("file size: ");
                res.append(size);

                if(processRunning(process))
                {
                    res.append("</br>encoding in progress</br>Reload page to check status or download");
                }
                else
                {
                    QString mime = "text/plain";
                    if(reqPath.endsWith(".avi"))
                    {
                        mime ="video/avi";
                    }
                    else if(reqPath.endsWith(".mp4"))
                    {
                        mime = "video/mp4";
                    }
                    else if(reqPath.endsWith(".ogv"))
                    {
                        mime = "video/theora";
                    }
                    else if(reqPath.endsWith(".ogg"))
                    {
                        mime = "audio/vorbis";
                    }
                    else if(reqPath.endsWith(".mp3"))
                    {
                        mime = "audio/mpeg";
                    }

                    res.clear();
                    res.append("HTTP/1.0 200 OK\r\n");
                    res.append("Content-Type: ");
                    res.append(mime);
                    res.append("\r\nContent-Length: ");
                    res.append(size);
                    res.append("\r\n\r\n");

                    sendFile = true;
                }
            }
            else if(processRunning(process))
            {
                res.append("Another encoding is in progress");
            }
            else
            {
                QStringList args;
                args.append(filename);
                args.append("-ovc");
                args.append("lavc");
                args.append("-lavcopts");
                args.append("vcodec=mpeg4:vhq:vbitrate=300");
                args.append("-vf");
                args.append("scale=320:240,eq2=1.2:0.5:-0.25,rotate=2");
                args.append("-oac");
                args.append("mp3lame");
                args.append("-ofps");
                args.append("15");
                args.append("-lameopts");
                args.append("br=64:cbr");
                args.append("-o");
                args.append(encPath);

                process = new QProcess(this);
                process->setProcessChannelMode(QProcess::ForwardedChannels);
                process->start("mencoder", args);
#ifdef Q_WS_WIN
                PROCESS_INFORMATION *pi = (PROCESS_INFORMATION *) process->pid();
                SetPriorityClass(pi->hProcess, IDLE_PRIORITY_CLASS);
#endif
                // FIXME: whatever we send to back, browser wont show anything
                if(process->waitForStarted(10000))
                {
                    res.append("Encoding started</br>Reload page to check status or download");
                }
                else
                {
                    res.append("Failed to start mencoder:</br>");
                    res.append(process->errorString());
                    delete(process);
                    process = NULL;
                }
            }
        }
    }

    if(!sendFile)
    {
        res.append("</body>");
        res.append("</html>");
    }
    con->write(res.toUtf8());

    if(sendFile)
    {
        QFile f(encPath);
        char buf[4096];
        f.open(QFile::ReadOnly);
        int count;
        while((count = f.read(buf, 4096)) > 0)
        {
            con->write(buf, count);
            con->flush();
            con->waitForBytesWritten(-1);
        }
    }

    con->close();
    con->disconnectFromHost();
}
Exemplo n.º 13
0
void CClientApp::processDeviceCommandSocket()
{
    QTcpSocket *socket = deviceCmdServer->nextPendingConnection();

    QString kText("Recieve TCP Socket\n");
    Q_EMIT m_pSender->commandReturned(kText, false);

    QObject::connect(socket, &QTcpSocket::readyRead, [=]
    {
        QByteArray byteArray = socket->readAll();
        QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray);
        QJsonObject jsonObj = jsonDoc.object();

        QString command = jsonObj["command"].toString();

        QString retJsonString;

        QJsonObject retJsonObj;

        QString kText("Recieve Cmd: " + command + "\n");

        if (command == "supportCmds")
        {
            retJsonObj.insert("status", 200);
            QJsonArray cmdArray;
            /*
            QJsonObject cmdObj1;
            cmdObj1.insert("command", "adjustTemperature");
            cmdObj1.insert("command_displayName", "Set Temperature");
            cmdObj1.insert("param_type", "integer");
            cmdObj1.insert("param_max", "100");
            cmdObj1.insert("param_min", "20");

            QJsonObject cmdObj2;
            cmdObj2.insert("command", "query");
            cmdObj2.insert("command_displayName", "Query Status");
            cmdObj2.insert("param_type", "none");

            cmdArray.append(cmdObj1);
            cmdArray.append(cmdObj2);
            */
            retJsonObj.insert("SupportCmds", cmdArray);

            connected = true;
        }
        else if (command == "queryDisplayInfo")
        {
            retJsonObj.insert("status", 200);
            QJsonArray keyArray;
            keyArray.append("Power");
            //keyArray.append("WindStrength");
            //keyArray.append("Humidity");

            retJsonObj.insert("DisplayInfo", keyArray);

            //retJsonObj.insert("Temperature", QString::number(temperature));
            //retJsonObj.insert("WindStrength", "Medium");
            //retJsonObj.insert("Humidity", "60");
            retJsonObj.insert("Power", "On");
        }
        /*else if (command == "adjustTemperature")
        {
        temperature = jsonObj["param"].toString().toInt();
        retJsonObj.insert("status", 200);
        }*/
        else
        {
            kText += command + " " + jsonObj["param"].toVariant().toString() + "\n";
            retJsonObj.insert("status", 200);
        }

        QJsonDocument retDoc(retJsonObj);

        kText += "WritingServer: " + QString::fromLatin1(retDoc.toJson()) + "\n";

        socket->write(retDoc.toJson());

        bool isSuccess = socket->waitForBytesWritten();
        QString result = (isSuccess ? "true" : "false");
        kText += "Written: " + result + "\n";

        socket->disconnectFromHost();
        Q_EMIT m_pSender->commandReturned(kText, false);
    });

    QObject::connect(socket, &QTcpSocket::disconnected, [=]
    {
        socket->deleteLater();
    });
}
QString ConnectionThread::processLine(QTcpSocket & sock,
                                      const QString & line)
{
    Debug() << "Got Line: " << line;
    QStringList toks = line.split(QRegExp("\\s+"), QString::SkipEmptyParts);
    if (toks.size() < 1) return QString::null;
    QString cmd = toks.front();
    toks.pop_front();
    cmd = cmd.toUpper();
    if (cmd == "NOOP") {
        return ""; // noop command alwasy prints OK -- used to test server connectivity and for keepaliveage, etc
    } else if (cmd == "GETTIME") {
        return QString::number(getTime(), 'f', 9);
    } else if (cmd == "GETFRAMENUM") {
        StimPlugin *p = stimApp()->glWin()->runningPlugin();
        if (p) {
            return QString::number(p->getFrameNum());
        } else {
            Error() << "GETFRAMENUM command received but no plugin was running.";
        }
    } else if (cmd == "GETHWFRAMENUM") {
        GetHWFrameCountEvent *e = new GetHWFrameCountEvent();
        GetSetData *d = e->d;
        stimApp()->postEvent(this, e);
        unsigned hwfc = d->getReply<unsigned>();
        delete d;
        return QString::number(hwfc);
    } else if (cmd == "GETREFRESHRATE") {
        unsigned rate = stimApp()->refreshRate();
        return QString::number(rate);
    } else if (cmd == "GETCURRENTRSEED") {
        int s = stimApp()->glWin() 
			    ?  (stimApp()->glWin()->runningPlugin() 
				    ? stimApp()->glWin()->runningPlugin()->currentRSeed() 
				    : 0)
				: 0;
        return QString::number(s);
    } else if (cmd == "GETWIDTH") {
        return QString::number(stimApp()->glWin()->width());
    } else if (cmd == "GETHEIGHT") {
        return QString::number(stimApp()->glWin()->height());
    } else if (cmd == "GETFRAME" && toks.size()) {
        bool ok;
        unsigned framenum = toks[0].toUInt(&ok), numFrames = 1;
		Vec2i co, cs, ds; // params 3,4,5,6,7,8 are crop-origin-x, crop-origin-y, crop-size-width, crop-size-height, downsample-factor-x, downsample-factor-y
        toks.pop_front();
		if (toks.size()) {
			bool ok2;
			numFrames = toks.front().toUInt(&ok2);
			if (ok2) toks.pop_front();
			if (!ok2 || numFrames < 1) numFrames = 1;
			Vec2i *vp[] = { &co, &cs, &ds, 0 };
			for (Vec2i **vcur = vp; *vcur; ++vcur) {				
				Vec2i & v = **vcur;
				v.x = toks.size() ? toks.front().toUInt(&ok2) : 0;
				if (ok2) toks.pop_front();
				if (!ok2 || v.x < 0) v.x = 0;
				v.y = toks.size() ? toks.front().toUInt(&ok2) : 0;
				if (ok2) toks.pop_front();
				if (!ok2 || v.y < 0) v.y = 0;
			}
		}
		if (!ds.x) ds.x = 1;
		if (!ds.y) ds.y = 1;
        int datatype = GL_UNSIGNED_BYTE;
        if (toks.size()) {
            QString s = toks.join(" ").toUpper().trimmed();
            if (s == "BYTE") datatype = GL_BYTE;
            else if (s == "UNSIGNED BYTE") datatype = GL_UNSIGNED_BYTE;
            else if (s == "SHORT") datatype = GL_SHORT;
            else if (s == "UNSIGNED SHORT") datatype = GL_UNSIGNED_SHORT;
            else if (s == "INT") datatype = GL_INT;
            else if (s == "UNSIGNED INT") datatype = GL_UNSIGNED_INT;
            else if (s == "FLOAT") datatype = GL_FLOAT;
            else {
                Error() << "GETFRAME command invalid datatype `" << s << "'.";
                return QString::null;
            }
        }
        if (ok) {
            GetFrameEvent *e = new GetFrameEvent(framenum, numFrames, co, cs, ds, datatype);
            GetSetData *d = e->d;
            stimApp()->postEvent(this, e);
			const double tgen0 = getTime();
            QList<QByteArray> frames (d->getReply<QList<QByteArray> >());
            delete d;
            if (!frames.isEmpty()) {
				const unsigned long fbytes = frames.count()*frames.front().size();
				Debug() << "Generating " << frames.count() << " frames (" << fbytes << " bytes) took " << getTime()-tgen0 << " secs";
                sock.write((QString("BINARY DATA ") + QString::number(fbytes) + "\n").toUtf8());
				const double t0 = getTime();
				for (QList<QByteArray>::const_iterator it = frames.begin(); it != frames.end(); ++it)
					sock.write(*it);
				Debug() << "Sending " << numFrames << " frames (" << fbytes << " bytes) took " << getTime()-t0 << " secs";
                return "";
            }
        }
    } else if (cmd == "LIST") {
        QList<QString> lst = stimApp()->glWin()->plugins();
        QString ret;
        QTextStream ts(&ret, QIODevice::WriteOnly|QIODevice::Truncate);
        for(QList<QString>::const_iterator it = lst.begin(); it != lst.end(); ++it) {
            ts << (*it) << "\n";
        }
        ts.flush();
        return ret;
	} else if (cmd == "GETFRAMEVARS") { 
			QVector<double> data;
			int nrows, ncols;
			FrameVariables::readAllFromLast(data, &nrows, &ncols);
			sock.write(QString().sprintf("MATRIX %d %d\n", nrows, ncols).toUtf8());
			if (data.size()) sock.write(QByteArray::fromRawData(reinterpret_cast<char *>(&data[0]),data.size()*sizeof(double)));
			return "";
	} else if (cmd == "GETFRAMEVARNAMES") {
			QString ret = "";
			QTextStream ts(&ret);
			QStringList hdr = FrameVariables::readHeaderFromLast();
					
			int i = 0;
			for (QStringList::iterator it = hdr.begin(); it != hdr.end(); ++it, ++i) {
					ts << *it << "\n";
			}
			ts.flush();
			return ret;		
    } else if (cmd == "GETSTATS") {
        QString theStr("");
        QTextStream strm(&theStr, QIODevice::WriteOnly/*|QIODevice::Text*/);
        GetSetEvent *e = new GetHWFrameCountEvent();
        GetSetData *d = e->d;
        stimApp()->postEvent(this, e);
        unsigned hwfc = d->getReply<unsigned>();
        delete d;
        e = new IsConsoleHiddenEvent();
        d = e->d;
        stimApp()->postEvent(this, e);
        bool isConsoleHidden = d->getReply<bool>();
        delete d;
        StimPlugin *p = stimApp()->glWin()->runningPlugin();

        strm.setRealNumberPrecision(3);
        strm.setRealNumberNotation(QTextStream::FixedNotation);
        strm << "runningPlugin = " << (p ? p->name() : "") << "\n"
             << "isPaused = " << (stimApp()->glWin()->isPaused() ? "1" : "0") << "\n"
			 << "isInitialized = " << (p ? (p->isInitialized() ? 1 : 0) : 0) << "\n" 
             << "isConsoleWindowHidden = " << (isConsoleHidden ? "1" : "0") << "\n"
             << "statusBarString = " << (p ? p->getSBString() : "") << "\n"
             << "currentTime = " << QDateTime::currentDateTime().toString() << "\n"
             << "beginTime = " << (p ? p->getBeginTime().toString() : "") << "\n"
             << "width = " << stimApp()->glWin()->width() << "\n"
             << "height = " << stimApp()->glWin()->height() << "\n"
             << "fpsAvg = " << (p ? p->getFps() : 0.) << "\n"
             << "fpsMin = " << (p ? p->getFpsMin() : 0.) << "\n"
             << "fpsMax = " << (p ? p->getFpsMax() : 0.) << "\n"
             << "fpsLast = " << (p ? p->getFpsCur() : 0.) << "\n"
             << "frameNum = " << (p ? p->getFrameNum() : -1) << "\n"
             << "hardwareFrameCount = " << hwfc << "\n"
             << "haAccurateHWFrameCount = " << (hasAccurateHWFrameCount() ? "1" : "0") << "\n"
             << "calibraredRefreshRate = " << stimApp()->refreshRate() << "\n"
             << "hwRefreshRate = " << getHWRefreshRate() << "\n"
             << "hasAccurateHWRefreshRate = " << (hasAccurateHWRefreshRate() ? 1 : 0) << "\n"
             << "numMissedFrames = " << (p ? p->getNumMissedFrames() : 0) << "\n";
        QDateTime now(QDateTime::currentDateTime()), beginTime(p ? p->getBeginTime() : now);
        double secs = beginTime.secsTo(now), fskipsPerSec = 0.;
        if (p && secs > 0.) {
            fskipsPerSec = p->getNumMissedFrames() / secs;
        }
        strm << "missedFramesPerSec = " << fskipsPerSec << "\n"
             << "saveDirectory = " << stimApp()->outputDirectory() << "\n"
             << "pluginList = ";
        QList<QString> plugins = stimApp()->glWin()->plugins();
        for (QList<QString>::const_iterator it = plugins.begin(); it != plugins.end(); ++it) {
            if (it != plugins.begin()) strm << ", ";
            strm << *it;
        }
        strm << "\n"
             << "programUptime = " << getTime() << "\n"
             << "nProcessors = " << getNProcessors() << "\n"
             << "hostName = " << getHostName() << "\n"
             << "uptime = " << getUpTime() << "\n";
        
        strm.flush();
        return theStr;
    } else if (cmd == "GETPARAMS" && toks.size()) {
        QString pluginName = toks.join(" ");
        StimPlugin *p;
        if ( (p = stimApp()->glWin()->pluginFind(pluginName)) ) {
            return p->getParams().toString();
        }
    } else if (cmd == "GETPARAMHISTORY" && toks.size()) {
        QString pluginName = toks.join(" ");
        StimPlugin *p;
        if ( (p = stimApp()->glWin()->pluginFind(pluginName)) ) {
            return p->paramHistoryToString() + "\n";
        }
    } else if (cmd == "SETPARAMHISTORY" && toks.size()) {
        QString pluginName = toks.join(" ");
        StimPlugin *p = stimApp()->glWin()->pluginFind(pluginName);
		if (!p) {
			Error() << "SETPARAMHISTORY issued on a non-existant plugin";
		} else if (stimApp()->glWin()->runningPlugin() == p) {
			Error() << "SETPARAMHISTORY cannot be issued on a plugin that is running";
		} else {
            Debug() << "Sending: READY";
            sock.write("READY\n");
            QString paramstr ("");
            QTextStream paramts(&paramstr, QIODevice::WriteOnly/*|QIODevice::Text*/);
            QString line;
            while ( sock.canReadLine() || sock.waitForReadyRead() ) {
                line = sock.readLine().trimmed();
                if (!line.length()) break;
                Debug() << "Got Line: " << line;
                paramts << line << "\n";
            }
            paramts.flush();
			p->setPendingParamHistoryFromString(paramstr);
			p->setSaveParamHistoryOnStopOverride(true); // also tell plugin to save this param history, since it came from an external source
            return "";
		}
	} else if (cmd == "NUMPARAMSQUEUED" && toks.size()) {
        QString pluginName = toks.join(" ");
        StimPlugin *p = stimApp()->glWin()->pluginFind(pluginName);
		if (!p) {
			Error() << "NUMPARAMSQUEUED issued on a non-existant plugin";
		} else {
			return QString::number(p->pendingParamsHistorySize());
		}	
	} else if (cmd == "SETPARAMQUEUE") {
        QString pluginName = toks.join(" ");
        StimPlugin *p = stimApp()->glWin()->pluginFind(pluginName);
		if (!p) {
			Error() << "SETPARAMQUEUE issued on a non-existant plugin";
		} else if (stimApp()->glWin()->runningPlugin() == p) {
			Error() << "SETPARAMQUEUE cannot be issued on a plugin that is running";
		} else {
            Debug() << "Sending: READY";
            sock.write("READY\n");
            QString paramstr ("");
            QTextStream paramts(&paramstr, QIODevice::WriteOnly/*|QIODevice::Text*/);
            QString line;
            while ( sock.canReadLine() || sock.waitForReadyRead() ) {
                line = sock.readLine().trimmed();
                if (!line.length()) break;
                Debug() << "Got Line: " << line;
                paramts << line << "\n";
            }
            paramts.flush();
			if (p->enqueueParamsForPendingParamsHistoryFromString(paramstr)) {
				p->setSaveParamHistoryOnStopOverride(false); // also tell plugin to NOT save this param history, since presumably it can be generated again from calling client code..
				return "";
			} else {
				Error() << "SETPARAMQUEUE failed to enqueue params from specified param-queue";
			}
		}
    } else if (cmd == "SETPARAMS" && toks.size()) {
        QString pluginName = toks.join(" ");
        StimPlugin *p;
        if ( (p = stimApp()->glWin()->pluginFind(pluginName)) ) {
            Debug() << "Sending: READY";
            sock.write("READY\n");
            QString paramstr ("");
            QTextStream paramts(&paramstr, QIODevice::WriteOnly/*|QIODevice::Text*/);
            QString line;
            while ( sock.canReadLine() || sock.waitForReadyRead() ) {
                line = sock.readLine().trimmed();
                if (!line.length()) break;
                Debug() << "Got Line: " << line;
                paramts << line << "\n";
            }
            paramts.flush();
            p->setParams(paramstr, p == stimApp()->glWin()->runningPlugin());
            return "";
        } else if (!p) {
            Error() << "SETPARAMS issued on a non-existant plugin";
        }
    } else if (cmd == "RUNNING") {
        StimPlugin *p = stimApp()->glWin()->runningPlugin();
        if (p) {
            return p->name();
        }
        return "";
    } else if (cmd == "ISPAUSED") {
        return QString::number(stimApp()->glWin()->isPaused());
    } else if (cmd == "ISINITIALIZED") {
        StimPlugin *p = stimApp()->glWin()->runningPlugin();
        if (p) {
			return QString::number(p->isInitialized());
        }
        return "0";
    } else if (cmd == "PAUSE") {
        if (!stimApp()->glWin()->isPaused())
            stimApp()->glWin()->pauseUnpause();
        return "";
    } else if (cmd == "UNPAUSE") {
        if (stimApp()->glWin()->isPaused())
            stimApp()->glWin()->pauseUnpause();
        return "";
    } else if (cmd == "ISCONSOLEHIDDEN") {
        GetSetEvent *e = new IsConsoleHiddenEvent;
        GetSetData *d = e->d;
        stimApp()->postEvent(this, e);
        QString ret = QString::number(int(d->getReply<bool>()));
        delete d;
        return ret;
    } else if (cmd == "CONSOLEHIDE") {
        stimApp()->postEvent(this, new ConsoleHideEvent());
        return "";
    } else if (cmd == "CONSOLEUNHIDE") {
        stimApp()->postEvent(this, new ConsoleUnHideEvent());
        return "";
    } else if (cmd == "ISVSYNCDISABLED") {
        return QString::number(stimApp()->isVSyncDisabled() ? 1 : 0);
    } else if (cmd == "SETVSYNCDISABLED") {
		const bool disabled = toks.join("").toInt();
		stimApp()->postEvent(this, new SetVSyncDisabledEvent(disabled));
		return "";
    } else if (cmd == "START" && toks.size()) {
        // this commands needs to be executed in the main thread
        // to avoid race conditions and also to have a valid opengl context
        QString pluginName = toks.front();
        bool startUnpaused = toks.size() > 1 && toks[1].toInt();
        if ( (stimApp()->glWin()->pluginFind(pluginName)) ) {
            stimApp()->postEvent(this, new StartStopPluginEvent(pluginName, startUnpaused));
            return "";
        }
    } else if (cmd == "STOP") {
        // this commands needs to be executed in the main thread
        // to avoid race conditions and also to have a valid opengl context
        bool doSave = toks.join("").toInt();
        if (stimApp()->glWin()->runningPlugin())
            stimApp()->postEvent(this, new StartStopPluginEvent(doSave)); 
        return "";
    } else if (cmd == "GETSAVEDIR") {
        return stimApp()->outputDirectory();
    } else if (cmd == "SETSAVEDIR") {
        QString dir = toks.join(" ");
        return stimApp()->setOutputDirectory(dir) ? QString("") : QString::null;
    } else if (cmd == "GETVERSION") {
        return VERSION_STR;
    } else if (cmd == "BYE") {
        sock.close();
    } 
    // add more cmds here
    return QString::null;
}
Exemplo n.º 15
0
void QWsServer::dataReceived()
{
	QTcpSocket * tcpSocket = qobject_cast<QTcpSocket*>( sender() );
	if (tcpSocket == 0)
		return;

	bool allHeadersFetched = false;

	const QLatin1String emptyLine("\r\n");

	while ( tcpSocket->canReadLine() )
	{
		QString line = tcpSocket->readLine();

		if (line == emptyLine)
		{
			allHeadersFetched = true;
			break;
		}

		headerBuffer[ tcpSocket ].append(line);
	}

	if (!allHeadersFetched)
	    return;

	QString request( headerBuffer[ tcpSocket ].join("") );

	QRegExp regExp;
	regExp.setMinimal( true );
	
	// Extract mandatory datas
	// Version
	regExp.setPattern( QWsServer::regExpVersionStr );
	regExp.indexIn(request);
	QString versionStr = regExp.cap(1);
	EWebsocketVersion version;
	if ( ! versionStr.isEmpty() )
	{
		version = (EWebsocketVersion)versionStr.toInt();
	}
	else if ( tcpSocket->bytesAvailable() >= 8 )
	{
		version = WS_V0;
		request.append( tcpSocket->read(8) );
	}
	else
	{
		version = WS_VUnknow;
	}

	// Resource name
	regExp.setPattern( QWsServer::regExpResourceNameStr );
	regExp.indexIn(request);
	QString resourceName = regExp.cap(1);
	
	// Host (address & port)
	regExp.setPattern( QWsServer::regExpHostStr );
	regExp.indexIn(request);
	QString host = regExp.cap(1);
	QStringList hostTmp = host.split(':');
	QString hostAddress = hostTmp[0];
	QString hostPort;
	if ( hostTmp.size() > 1 )
        hostPort = hostTmp.last(); // fix for IPv6
	
	// Key
	QString key, key1, key2, key3;
	if ( version >= WS_V4 )
	{
		regExp.setPattern( QWsServer::regExpKeyStr );
		regExp.indexIn(request);
		key = regExp.cap(1);
	}
	else
	{
		regExp.setPattern( QWsServer::regExpKey1Str );
		regExp.indexIn(request);
		key1 = regExp.cap(1);
		regExp.setPattern( QWsServer::regExpKey2Str );
		regExp.indexIn(request);
		key2 = regExp.cap(1);
		regExp.setPattern( QWsServer::regExpKey3Str );
		regExp.indexIn(request);
		key3 = regExp.cap(1);
	}
	
	////////////////////////////////////////////////////////////////////

	// If the mandatory fields are not specified, we abord the connection to the Websocket server
	if ( version == WS_VUnknow || resourceName.isEmpty() || hostAddress.isEmpty() || ( key.isEmpty() && ( key1.isEmpty() || key2.isEmpty() || key3.isEmpty() ) ) )
	{
		// Send bad request response
		QString response = QWsServer::composeBadRequestResponse( QList<EWebsocketVersion>() << WS_V6 << WS_V7 << WS_V8 << WS_V13 );
		tcpSocket->write( response.toUtf8() );
		tcpSocket->flush();
		return;
	}
	
	////////////////////////////////////////////////////////////////////
	
	// Extract optional datas

	// Origin
	regExp.setPattern( QWsServer::regExpOriginStr );
	if ( regExp.indexIn(request) == -1 )
	{
		regExp.setPattern( QWsServer::regExpOrigin2Str );
		regExp.indexIn(request);
	}
	QString origin = regExp.cap(1);

	// Protocol
	regExp.setPattern( QWsServer::regExpProtocolStr );
	regExp.indexIn(request);
	QString protocol = regExp.cap(1);

	// Extensions
	regExp.setPattern( QWsServer::regExpExtensionsStr );
	regExp.indexIn(request);
	QString extensions = regExp.cap(1);
	
	////////////////////////////////////////////////////////////////////
	
	// Compose opening handshake response
	QString response;

	if ( version >= WS_V6 )
	{
		QString accept = computeAcceptV4( key );
		response = QWsServer::composeOpeningHandshakeResponseV6( accept, protocol );
	}
	else if ( version >= WS_V4 )
	{
		QString accept = computeAcceptV4( key );
		QString nonce = generateNonce();
		response = QWsServer::composeOpeningHandshakeResponseV4( accept, nonce, protocol );
	}
	else
	{
		QString accept = computeAcceptV0( key1, key2, key3 );
		response = QWsServer::composeOpeningHandshakeResponseV0( accept, origin, hostAddress, hostPort, resourceName , protocol );
	}
	
	// Handshake OK, disconnect readyRead
	disconnect( tcpSocket, SIGNAL(readyRead()), this, SLOT(dataReceived()) );

	// Send opening handshake response
	if ( version == WS_V0 )
        tcpSocket->write( response.toLatin1() );
	else
		tcpSocket->write( response.toUtf8() );
	tcpSocket->flush();

	QWsSocket * wsSocket = new QWsSocket( this, tcpSocket, version );
	wsSocket->setResourceName( resourceName );
	wsSocket->setHost( host );
	wsSocket->setHostAddress( hostAddress );
	wsSocket->setHostPort( hostPort.toInt() );
	wsSocket->setOrigin( origin );
	wsSocket->setProtocol( protocol );
	wsSocket->setExtensions( extensions );
	wsSocket->serverSideSocket = true;
	
	// ORIGINAL CODE
	//int socketDescriptor = tcpSocket->socketDescriptor();
	//incomingConnection( socketDescriptor );
	
	// CHANGED CODE FOR LINUX COMPATIBILITY
	addPendingConnection( wsSocket );
	emit newConnection();
}
Exemplo n.º 16
0
void getGridProperty(NDArray& propertyFrames, const QString &serverName, quint16 serverPort,
                        const int& caseId, int gridIdx, QString propertyName, const int32NDArray& requestedTimeSteps, QString porosityModel)
{
    QTcpSocket socket;
    socket.connectToHost(serverName, serverPort);

    if (!socket.waitForConnected(riOctavePlugin::connectTimeOutMilliSecs))
    {
        error((("Connection: ") + socket.errorString()).toLatin1().data());
        return;
    }

    QDataStream socketStream(&socket);
    socketStream.setVersion(riOctavePlugin::qtDataStreamVersion);

    // Create command as a string with arguments , and send it:

    QString command;
    command += "GetGridProperty " + QString::number(caseId) + " " + QString::number(gridIdx) + " " + propertyName + " " + porosityModel;

    for (int i = 0; i < requestedTimeSteps.length(); ++i)
    {
        if (i == 0) command += " ";
        command += QString::number(static_cast<int>(requestedTimeSteps.elem(i)) - 1); // To make the index 0-based
        if (i != requestedTimeSteps.length() -1) command += " ";
    }

    QByteArray cmdBytes = command.toLatin1();

    socketStream << (qint64)(cmdBytes.size());
    socket.write(cmdBytes);

    // Get response. First wait for the header

    while (socket.bytesAvailable() < (int)(4*sizeof(quint64)))
    {
        if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    // Read sizes

    quint64 totalByteCount;
    quint64 cellCountI;
    quint64 cellCountJ;
    quint64 cellCountK;
    quint64 timestepCount;

    socketStream >> cellCountI;
    socketStream >> cellCountJ;
    socketStream >> cellCountK;
    socketStream >> timestepCount;

    totalByteCount = cellCountI*cellCountJ*cellCountK*timestepCount*sizeof(double);
    if (!(totalByteCount))
    {
        error ("Could not find the requested data in ResInsight");
        return;
    }

    dim_vector dv;
    dv.resize(4);
    dv(0) = cellCountI;
    dv(1) = cellCountJ;
    dv(2) = cellCountK;
    dv(3) = timestepCount;

    propertyFrames.resize(dv);


    // Wait for available data

    while (socket.bytesAvailable() < (int)totalByteCount)
    {
        if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs))
        {
            error(("Waiting for data : " + socket.errorString()).toLatin1().data());
            return ;
        }
        OCTAVE_QUIT;
    }

    qint64 bytesRead = 0;
    double * internalMatrixData = propertyFrames.fortran_vec();

    // Raw data transfer. Faster.
    bytesRead = socket.read((char*)(internalMatrixData ), totalByteCount);

    if ((int)totalByteCount != bytesRead)
    {
        error("Could not read binary double data properly from socket");
    }

    QString tmp = QString("riGetGridProperty : Read %1").arg(propertyName);

    if (caseId < 0)
    {
        tmp += QString(" from current case,");
    }
    else
    {
        tmp += QString(" from case with Id: %1,").arg(caseId);
    }

    tmp += QString(" grid index: %1, ").arg(gridIdx);

    octave_stdout << tmp.toStdString() << " I, J, K " << cellCountI << ", " << cellCountJ << ", " << cellCountK << ", Timesteps : " << timestepCount << std::endl;

    return;
}
Exemplo n.º 17
0
bool CetonRTSP::ProcessRequest(
    const QString &method, const QStringList* headers)
{
    QMutexLocker locker(&_rtspMutex);
    QTcpSocket socket;
    socket.connectToHost(_ip, _port);

    QStringList requestHeaders;
    requestHeaders.append(QString("%1 %2 RTSP/1.0").arg(method, _requestUrl));
    requestHeaders.append(QString("User-Agent: MythTV Ceton Recorder"));
    requestHeaders.append(QString("CSeq: %1").arg(++_sequenceNumber));
    if (_sessionId != "0")
        requestHeaders.append(QString("Session: %1").arg(_sessionId));
    if (headers != NULL)
    {
        for(int i = 0; i < headers->count(); i++)
        {
            QString header = headers->at(i);
            requestHeaders.append(header);
        }
    }
    requestHeaders.append(QString("\r\n"));
    QString request = requestHeaders.join("\r\n");


    LOG(VB_RECORD, LOG_DEBUG, LOC + QString("write: %1").arg(request));
    socket.write(request.toLatin1());

    _responseHeaders.clear();
    _responseContent.clear();

    QRegExp firstLineRegex(
        "^RTSP/1.0 (\\d+) ([^\r\n]+)", Qt::CaseSensitive, QRegExp::RegExp2);
    QRegExp headerRegex(
        "^([^:]+):\\s*([^\\r\\n]+)", Qt::CaseSensitive, QRegExp::RegExp2);
    QRegExp blankLineRegex(
        "^[\\r\\n]*$", Qt::CaseSensitive, QRegExp::RegExp2);

    bool firstLine = true;
    while (true)
    {
        if (!socket.canReadLine())
        {
            bool ready = socket.waitForReadyRead();
            if (!ready)
            {
                LOG(VB_RECORD, LOG_ERR, LOC + "RTSP server did not respond");
                return false;
            }
            continue;
        }

        QString line = socket.readLine();
        LOG(VB_RECORD, LOG_DEBUG, LOC + QString("read: %1").arg(line));

        if (firstLine)
        {
            if (firstLineRegex.indexIn(line) == -1)
            {
                _responseCode = -1;
                _responseMessage =
                    QString("Could not parse first line of response: '%1'")
                    .arg(line);
                return false;
            }

            QStringList parts = firstLineRegex.capturedTexts();
            _responseCode = parts.at(1).toInt();
            _responseMessage = parts.at(2);

            firstLine = false;
            continue;
        }

        if (blankLineRegex.indexIn(line) != -1) break;

        if (headerRegex.indexIn(line) == -1)
        {
            _responseCode = -1;
            _responseMessage = QString("Could not parse response header: '%1'")
                .arg(line);
            return false;
        }
        QStringList parts = headerRegex.capturedTexts();
        _responseHeaders.insert(parts.at(1), parts.at(2));
    }

    QString cSeq = _responseHeaders.value("CSeq");
    if (cSeq != QString("%1").arg(_sequenceNumber))
    {
        LOG(VB_RECORD, LOG_WARNING, LOC +
            QString("Expected CSeq of %1 but got %2")
            .arg(_sequenceNumber).arg(cSeq));
    }

    _responseContent.clear();
    int contentLength = _responseHeaders.value("Content-Length").toInt();
    if (contentLength > 0)
    {
        _responseContent.resize(contentLength);
        char* data = _responseContent.data();
        int bytesRead = 0;
        while (bytesRead < contentLength)
        {
            if (socket.bytesAvailable() == 0)
                socket.waitForReadyRead();

            int count = socket.read(data+bytesRead, contentLength-bytesRead);
            if (count == -1)
            {
                _responseCode = -1;
                _responseMessage = "Could not read response content";
                return false;
            }
            bytesRead += count;
        }
    }
    return true;
}
Exemplo n.º 18
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);
}
void QWsServer::dataReceived()
{
	QTcpSocket * clientSocket = qobject_cast<QTcpSocket*>(sender());
	if (clientSocket == 0)
		return;

	QString request( clientSocket->readAll() );

	QRegExp regExp;
	regExp.setMinimal( true );
	
	// Extract mandatory datas
	
	// Version
	regExp.setPattern( QWsServer::regExpVersionStr );
	regExp.indexIn(request);
	QString versionStr = regExp.cap(1);
	int version = 0;
	if ( ! versionStr.isEmpty() )
		version = versionStr.toInt();
	
	// Resource name
	regExp.setPattern( QWsServer::regExpResourceNameStr );
	regExp.indexIn(request);
	QString resourceName = regExp.cap(1);
	
	// Host (address & port)
	regExp.setPattern( QWsServer::regExpHostStr );
	regExp.indexIn(request);
	QStringList sl = regExp.cap(1).split(':');
	QString hostAddress = sl[0];
	QString hostPort;
	if ( sl.size() > 1 )
		hostPort = sl[1];
	
	// Key
	QString key, key1, key2, key3;
	if ( version >= 6 )
	{
		regExp.setPattern( QWsServer::regExpKeyStr );
		regExp.indexIn(request);
		key = regExp.cap(1);
	}
	else
	{
		regExp.setPattern( QWsServer::regExpKey1Str );
		regExp.indexIn(request);
		key1 = regExp.cap(1);
		regExp.setPattern( QWsServer::regExpKey2Str );
		regExp.indexIn(request);
		key2 = regExp.cap(1);
		regExp.setPattern( QWsServer::regExpKey3Str );
		regExp.indexIn(request);
		key3 = regExp.cap(1);
	}
	
	// Extract optional datas
	// Origin
	QString origin;
	if ( version < 6 || version > 8 )
	{
		regExp.setPattern( QWsServer::regExpOriginStr );
		regExp.indexIn(request);
		origin = regExp.cap(1);
	}
	else
	{
		regExp.setPattern( QWsServer::regExpOriginV6Str );
		regExp.indexIn(request);
		origin = regExp.cap(1);
	}

	// Protocol
	regExp.setPattern( QWsServer::regExpProtocolStr );
	regExp.indexIn(request);
	QString protocol = regExp.cap(1);

	// Extensions
	regExp.setPattern( QWsServer::regExpExtensionsStr );
	regExp.indexIn(request);
	QString extensions = regExp.cap(1);
	
	////////////////////////////////////////////////////////////////////

	if ( version < 6 )
	{
		qDebug() << "======== Handshake Received \n"
				 << request
				 << "======== \n";
	}

	// If the mandatory params are not setted, we abord the connection to the Websocket server
	if ( hostAddress.isEmpty()
		|| resourceName.isEmpty()
		|| ( key.isEmpty() && ( key1.isEmpty() || key2.isEmpty() || key3.isEmpty() ) )
	   )
		return;
	
	////////////////////////////////////////////////////////////////////
	
	// Compose handshake answer
	
	QString answer;
	
	QString accept;
	if ( version >= 6 )
	{
		accept = computeAcceptV2( key );
		answer.append("HTTP/1.1 101 Switching Protocols\r\n");
		answer.append("Upgrade: websocket\r\n");
		answer.append("Connection: Upgrade\r\n");
		answer.append("Sec-WebSocket-Accept: " + accept + "\r\n" + "\r\n");
	}
	else if ( version < 6 )
	{
		accept = computeAcceptV1( key1, key2, key3 );
		answer.append("HTTP/1.1 101 WebSocket Protocol Handshake\r\n");
		answer.append("Upgrade: Websocket\r\n");
		answer.append("Connection: Upgrade\r\n");
		answer.append("Sec-WebSocket-Origin: " + origin + "\r\n");
		answer.append("Sec-WebSocket-Location: ws://" + hostAddress + ( hostPort.isEmpty() ? "" : (":"+hostPort) ) + resourceName + "\r\n");
		if ( !protocol.isEmpty() )
			answer.append("Sec-WebSocket-Protocol: " + protocol + "\r\n");
		answer.append( accept );
	}
	
	if ( version < 6 )
	{
		qDebug() << "======== Handshake sent \n"
				 << answer
				 << "======== \n";
	}

	// Handshake OK, new connection
	disconnect(clientSocket, SIGNAL(readyRead()), this, SLOT(dataReceived()));

	// Send handshake answer
	clientSocket->write( answer.toUtf8() );
	clientSocket->flush();

	// TEMPORARY CODE FOR LINUX COMPATIBILITY
	QWsSocket * wsSocket = new QWsSocket( clientSocket, this );
	addPendingConnection( wsSocket );
	emit newConnection();

	/*
	// ORIGINAL CODE
	int socketDescriptor = clientSocket->socketDescriptor();
	incomingConnection( socketDescriptor );
	*/
}
Exemplo n.º 20
0
 void sendRequest() {
     QTcpSocket *proxySocket = qobject_cast<QTcpSocket*>(sender());
     QByteArray requestData = proxySocket->property("requestData").toByteArray();
     proxySocket->write(requestData);
 }
Exemplo n.º 21
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    //Declare variables here
    bool quit = false, admin = false;
    char buffer[2000], command[2000], user[100], password[100];

    //TCP Connection
    QTcpSocket *socket = new QTcpSocket();
    socket->connectToHost("sniperdad.com", 4000);

    //Checks for connection
    if(!socket->waitForConnected(5000))
    {
        qDebug() << "Error: " << socket->errorString();
        cout << "Exiting Program";
        return a.exec();
    }
    else{
        cout << "Connected to server!" << endl;
    }

    cout << "Welcome Guest, type \"help\" for a list of commands\n";

    while(!quit){

        //Test Admin Stuff, Probably move to server side
        if (admin == false) {
            cout << "<Guest>";
        }
        else {
            cout << "<Admin>";
        }
        //End Test admin Stuff

        //Grabs user input
        fseek(stdin,0,SEEK_END); //Resets stdin to beginning
        fgets(command,sizeof(command),stdin); // Grabs whole line of command
        chomp(command); // Removes newline from command

        //Client side commands
        if (strcmp (command , "quit") == 0){
            quit = true;
            break;
        }
        else if (strcmp (command , "login") == 0){
            cout << "Enter your username:"******"Enter your password:"******"login ");
            strcat(command,user);
            strcat(command," ");
            strcat(command,password);
            cout << endl;
        }

//      cout << ":" << command << ":" << endl; //Test Stuff: Shows what were sending to socket

        //sends data to socket and waits for response
        socket->write(command);
        socket->flush();
        socket->waitForReadyRead(-1);
        socket->read(buffer, sizeof(buffer));
        cout << buffer << "\n";

        //Test Admin Stuff, Probably move to server side
        if (strcmp( buffer , "Login Sucessful!") == 0){
            admin = true;
        }
        if (strcmp( buffer , "Logged Out!") == 0){
            admin = false;
        }
        //End Test admin Stuff

    }
Exemplo n.º 22
0
 void transferData() {
     QTcpSocket *proxySocket = qobject_cast<QTcpSocket*>(sender());
     QTcpSocket *socket = qobject_cast<QTcpSocket*>(proxySocket->parent());
     socket->write(proxySocket->readAll());
 }
Exemplo n.º 23
0
void getDynamicNNCValues(Matrix& propertyFrames, const QString &serverName, quint16 serverPort,
                         const qint64& caseId, QString propertyName, const int32NDArray& requestedTimeSteps)
{
    QTcpSocket socket;
    socket.connectToHost(serverName, serverPort);

    if (!socket.waitForConnected(riOctavePlugin::connectTimeOutMilliSecs))
    {
        error((("Connection: ") + socket.errorString()).toLatin1().data());
        return;
    }

    QDataStream socketStream(&socket);
    socketStream.setVersion(riOctavePlugin::qtDataStreamVersion);

    // Create command as a string with arguments , and send it:
    QString command;
    command += "GetDynamicNNCValues " + QString::number(caseId) + " " + propertyName;

    for (int i = 0; i < requestedTimeSteps.numel(); ++i)
    {
        if (i == 0) command += " ";
        command += QString::number(static_cast<int>(requestedTimeSteps.elem(i)) - 1); // To make the index 0-based
        if (i != requestedTimeSteps.numel() -1) command += " ";
    }

    QByteArray cmdBytes = command.toLatin1();

    socketStream << (qint64)(cmdBytes.size());
    socket.write(cmdBytes);

    // Get response. First wait for the header

    while (socket.bytesAvailable() < (int)(2*sizeof(quint64)))
    {
        if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    // Read connection count and timestep count
    quint64 connectionCount;
    quint64 timestepCount;

    socketStream >> connectionCount;
    socketStream >> timestepCount;

    propertyFrames.resize(connectionCount, timestepCount);

    if (!(connectionCount && timestepCount))
    {
        error ("Could not find the requested data in ResInsight");
        return;
    }

    quint64 totalByteCount = timestepCount * connectionCount * sizeof(double);

    double* internalMatrixData = propertyFrames.fortran_vec();
    QStringList errorMessages;
    if (!RiaSocketDataTransfer::readBlockDataFromSocket(&socket, (char*)(internalMatrixData), totalByteCount, errorMessages))
    {
        for (int i = 0; i < errorMessages.size(); i++)
        {
            error(errorMessages[i].toLatin1().data());
        }

        return;
    }

    QString tmp = QString("riGetDynamicNNCValues : Read %1").arg(propertyName);

    if (caseId < 0)
    {
        tmp += QString(" from current case.");
    }
    else
    {
        tmp += QString(" from case with Id: %1.").arg(caseId);
    }
    octave_stdout << tmp.toStdString() << " Connections: " << connectionCount << ", Time steps : " << timestepCount << std::endl;

    return;
}
Exemplo n.º 24
0
//SLOT to readyRead. Called upon data arrival
void MiniServer::readyRead() {
    QTcpSocket *socket = (QTcpSocket *)sender();                                //Get the socket that sent data
    int p = 0, len = socDataList.size();
    socketData *socDes = NULL;
    for ( ; p < len; p++) {                                                     //Get socDes according to that socket
        if (socDataList.at(p)->socketDesciptor == socket->socketDescriptor()) {
            socDes = socDataList.at(p);
            break;
        }
    }
    QByteArray Data = socket->readAll();                //Read data from the buffer that comes on the socket
    int i = 0;

    //Process the message which will start with start byte and then data
    for (i = 0; i < Data.size(); i++) {
        //If dataRead is on then read data into buffer till buffer's size is matched to expected size
        if (!socDes->readingStart && socDes->dataRead && socDes->buffer.size() < (socDes->end-(qint64)(socDes->start.toLong())+1)) {
            socDes->buffer.append(Data[i]);
            continue;
        }

        //If expected data is in buffer then ....
        if ((socDes->buffer.size() == (socDes->end - (qint64)(socDes->start.toLong()) + 1)) && socDes->dataRead) {
            //qDebug() << "got";
            fstream file;
            file.open(this->filename.toUtf8().constData(), ios::in | ios::out | ios::ate);
            if (!map[(qint64)(socDes->start.toLong())]) {           //If data is already not written

                QCryptographicHash *ha = new QCryptographicHash(QCryptographicHash::Md5);
                ha->addData(socDes->buffer.constData());
                QString hash = QString(ha->result().toHex());

                if (!hash.compare(this->pieceHashes.at(((qint64)socDes->start.toLong())/this->pieceSize))) {        //Check hash of the piece
                    //Mark it as data written and write data and emit signal that data is written
                    map[(qint64)(socDes->start.toLong())] = true;
                    file.seekp(socDes->start.toLong(), ios::beg);
                    file.write(socDes->buffer.constData(), socDes->buffer.size());
                    this->numberOfBytesWritten += socDes->buffer.size();    //Update number of bytes written
                    emit dataGot();
                    if (this->numberOfBytesWritten == this->size) {
                        file.close();                                       //Check if file transfer is done
                        emit fileTransferDone();
                    }
                } else {

                    //If piece is dirty then ask the request the next client to send data.
                    qint64 end = this->size-1 < ((qint64)socDes->start.toLong() + this->pieceSize - 1) ? this->size-1 : ((qint64)socDes->start.toLong() + this->pieceSize - 1);
                    QString request = " R " + QString::number((qint64)socDes->start.toLong()) + " " + QString::number(end) + " ";

                    int i = 0;
                    for ( ; i < clientList.size(); i++) {
                        if (clientList.at(i)->socketDescriptor() == socket->socketDescriptor())
                            break;
                    }
                    i = (i + 1) % clientList.size();
                    clientList.at(i)->write(request.toUtf8());
                    clientList.at(i)->waitForBytesWritten();
                    file.close();
                    continue;
                }
            }

            //Issue next request till sizechk is less than size
            if(this->sizechk < this->size) {
                qint64 end = this->size-1 < (this->sizechk + this->pieceSize - 1) ? this->size-1 : (this->sizechk + this->pieceSize - 1);
                QString request = " R " + QString::number(this->sizechk) + " " + QString::number(end) + " ";
                this->sizechk = end + 1;
                socket->write(request.toUtf8());
                socket->waitForBytesWritten();
            } else {

                //Else check if there is some data missing and request that data
                qint64 start = 0;
                while (start < this->size) {
                    if (!map[start]) {
                        qint64 end = this->size-1 < (start + this->pieceSize - 1) ? (this->size - 1) : (start + this->pieceSize - 1);
                        QString request = " R " + QString::number(start) + " " + QString::number(end) + " ";
                        socket->write(request.toUtf8());
                        socket->waitForBytesWritten();
                        break;
                    }
                    start += this->pieceSize;
                }
            }

            file.close();
            socDes->buffer.clear();
            socDes->dataRead = false;
            continue;
        }
        if (!socDes->readingStart) {                    //Start reading start byte
            socDes->start.clear();
            socDes->readingStart = true;
            socDes->dataRead = false;
            continue;
        }
        if (socDes->readingStart) {                     //start reading start till ' ' comes
            if (char(Data[i]) != ' ') {
                socDes->start.append(Data[i]);
                continue;
            }
            else {
                socDes->readingStart = false;           //Decide end byte and make dataRead true
                socDes->end = (this->size - 1) < ((qint64)(socDes->start.toLong()) + this->pieceSize - 1) ? (this->size - 1) : (qint64)(socDes->start.toLong()) + this->pieceSize - 1;
                socDes->dataRead = true;
                continue;
            }
        }
    }
}
Exemplo n.º 25
-1
bool QgsHelp::urlExists( const QString &url )
{
  QUrl helpUrl( url );
  QTcpSocket socket;

  QgsSettings settings;
  bool proxyEnabled = settings.value( QStringLiteral( "proxy/proxyEnabled" ), false ).toBool();
  if ( proxyEnabled )
  {
    QNetworkProxy proxy;
    QString proxyHost = settings.value( QStringLiteral( "proxy/proxyHost" ), QString() ).toString();
    int proxyPort = settings.value( QStringLiteral( "proxy/proxyPort" ), QString() ).toString().toInt();
    QString proxyUser = settings.value( QStringLiteral( "proxy/proxyUser" ), QString() ).toString();
    QString proxyPassword = settings.value( QStringLiteral( "proxy/proxyPassword" ), QString() ).toString();

    QString proxyTypeString = settings.value( QStringLiteral( "proxy/proxyType" ), QString() ).toString();

    if ( proxyTypeString == QLatin1String( "DefaultProxy" ) )
    {
      QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery();
      if ( !proxies.isEmpty() )
      {
        proxy = proxies.first();
      }
    }
    else
    {
      QNetworkProxy::ProxyType proxyType = QNetworkProxy::DefaultProxy;
      if ( proxyTypeString == QLatin1String( "Socks5Proxy" ) )
      {
        proxyType = QNetworkProxy::Socks5Proxy;
      }
      else if ( proxyTypeString == QLatin1String( "HttpProxy" ) )
      {
        proxyType = QNetworkProxy::HttpProxy;
      }
      else if ( proxyTypeString == QLatin1String( "HttpCachingProxy" ) )
      {
        proxyType = QNetworkProxy::HttpCachingProxy;
      }
      else if ( proxyTypeString == QLatin1String( "FtpCachingProxy" ) )
      {
        proxyType = QNetworkProxy::FtpCachingProxy;
      }
      proxy = QNetworkProxy( proxyType, proxyHost, proxyPort, proxyUser, proxyPassword );
    }
    socket.setProxy( proxy );
  }

  socket.connectToHost( helpUrl.host(), 80 );
  if ( socket.waitForConnected() )
  {
    socket.write( "HEAD " + helpUrl.path().toUtf8() + " HTTP/1.1\r\n"
                  "Host: " + helpUrl.host().toUtf8() + "\r\n\r\n" );
    if ( socket.waitForReadyRead() )
    {
      QByteArray bytes = socket.readAll();
      if ( bytes.contains( "200 OK" ) ||  bytes.contains( "302 Found" ) ||  bytes.contains( "301 Moved" ) )
      {
        return true;
      }
    }
  }

  return false;
}