Exemple #1
0
int UCHome_Main_SiteConst::fetchFeedData() 
{
    q_debug()<<"impled";
    
    QTcpSocket *sock = NULL;

    sock = new QTcpSocket();
    
    sock->connectToHost(this->host, this->port);
    if(!sock->waitForConnected()) {
        q_debug()<<"Connect error";
        return FETCH_FEED_ERROR;
    }
    
    QString request;
    request = 
        QString(
                "GET %1 HTTP/1.1\r\n"
                "Host: uchome.developer.manyou.com\r\n"
                "User-Agent: Opera/9.62 (X11; Linux i686; U; zh-cn)\r\n"
                "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
                "Accept-Language: zh-cn,zh;q=0.5\r\n"
                "Accept-Charset: gb2312,utf-8;q=0.7,*;q=0.7\r\n"
                //"Keep-Alive: 300\r\n"
                //"Connection: keep-alive\r\n"
                "Connection: close\r\n"
                "Cookie: %2\r\n"
                "\r\n"
                )
        .arg(this->feed_url, this->cookies);

    q_debug()<<request;
    sock->write(request.toAscii());
    if(!sock->waitForBytesWritten()) {
        q_debug()<<"Write error";
        return FETCH_FEED_ERROR;
    }

    char header[8192] = {0} ;
    char b2[2] = {0};
    char *bp = &header[0];
    char *tp = bp;
    qint64 rlen = 0;
    qint64 oklen = 0;

    if(!sock->waitForReadyRead()) {
        q_debug()<<"wait read error";
        return LOGIN_ERROR;
    }

    while(true) {
        oklen = sock->bytesAvailable();
        if(oklen < 0 ) {
            q_debug()<<"wait read errorsdfjsdifsdifsdifj";
        }
        while(oklen-- > 0) {
            rlen = sock->read(b2, 1);
            *tp++ = b2[0];
            if(tp - bp > 4 && strncmp(tp-4, "\r\n\r\n", 4) == 0) {
                break;
            }
        }
        if(strncmp(tp-4, "\r\n\r\n", 4) == 0) {
            break;
        }
    }
    //parse header, got file length
    QString html_header = header;

    QStringList header_lines = QString(header).split("\r\n");
    qint64 content_length = -1;
    for(int i = 0; i < header_lines.count(); i ++) {
        if(header_lines.at(i).startsWith("Content-length")) {
            content_length = header_lines.at(i).split(":").at(1).trimmed().toLongLong();
        }
    }
    
    if(content_length == -1) {
        q_debug()<<"Unknown content-length for header:"<< html_header;
        //return FETCH_FEED_ERROR;
    }

    QByteArray html;
    QByteArray hb ;
    while(true) {
        oklen = sock->bytesAvailable();
        if(oklen > 0) {
            hb= sock->readAll();
            html += hb;
        }else if(oklen == 0) {
            if(!sock->waitForReadyRead()) {
                q_debug()<<"wait read error";
                break;
            }
        }else{
            q_debug()<<"bytesAvalibale < 0";
            break;
        }
    }
    
    this->feed_page_html = html;
    q_debug()<<"read len =? content-length: "<<html.length()<<" =? "<<content_length;
    q_debug()<<html.left(6)<<html.right(20);

    this->clean_my_name_lable();

    return FETCH_FEED_OK;
}
void AndroidRetracer::run()
{
    m_androidUtils.reloadAdb();
    QString errorStr;
    bool setupRet;
    QMetaObject::invokeMethod(this, "setup", Qt::BlockingQueuedConnection,
                              Q_RETURN_ARG(bool, setupRet),
                              Q_ARG(QString *, &errorStr));

    if (!setupRet) {
        emit finished(errorStr);
        return;
    }

    if (!m_androidUtils.runAdb(QStringList() << _("shell") << _("am") << _("start") << _("-n") << packageName + activityName)) {
        emit finished(tr("Can't start apitrace application"));
        return;
    }
    QByteArray which;
    if (!m_androidUtils.runAdb(QStringList() << _("shell") << _("readlink") << _("$(which ps)") , &which)) {
        emit finished(tr("Can't start adb"));
        return;
    }

    bool isBusyBox = which.startsWith("busybox");
    QStringList psArgs;
    psArgs << _("shell") << _("ps");
    if (isBusyBox)
        psArgs << _("-w");

    qint64 processPID;
    bool wasStarted = false;
    QTime startTime;
    startTime.start();

    QTcpSocket stdoutSocket;
    QTcpSocket stderrSocket;

    ImageHash thumbnails;

    QVariantMap parsedJson;
    trace::Profile* profile = isProfiling() ? new trace::Profile() : NULL;

    QList<ApiTraceError> errors;
    QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$");

    QString msg = QLatin1String("Replay finished!");
    QByteArray ubjsonBuffer;
    QByteArray outputBuffer;
    bool keepGoing = true;
    while(keepGoing) {
        if (!wasStarted || startTime.elapsed() > 1000) {
            QByteArray psOut;
            m_androidUtils.runAdb(psArgs, &psOut);
            processPID = extractPid(psOut);
            if (wasStarted)
                startTime.restart();
        }

        if (processPID == -1) {
            if (wasStarted) {
                break;
            } else {
                if (startTime.elapsed() > 3000) { // wait 3 seconds to start
                    emit finished(tr("Unable to start retrace on device."));
                    return;
                }
            }
            msleep(100);
            continue;
        }

        // we have a valid pid, it means the application started
        if (!wasStarted) {
            // connect the sockets
            int tries = 0;
            do {
                stdoutSocket.connectToHost(QHostAddress::LocalHost, m_stdoutPort);
            } while (!stdoutSocket.waitForConnected(100) && ++tries < 10);
            if (stdoutSocket.state() != QAbstractSocket::ConnectedState) {
                emit finished(tr("Can't connect to stdout socket."));
                return;
            }

            // Android doesn't suport GPU and PPD profiling (at leats not on my devices)
            //setProfiling(false, isProfilingCpu(), false);

            QString args = (retraceArguments() << m_androdiFileName).join(" ") + _("\n");
            stdoutSocket.write(args.toUtf8());
            if (!stdoutSocket.waitForBytesWritten()) {
                emit finished(tr("Can't send params."));
                return;
            }


            stderrSocket.connectToHost(QHostAddress::LocalHost, m_stderrPort);
            stderrSocket.waitForConnected(100);
            if (stderrSocket.state() != QAbstractSocket::ConnectedState) {
                emit finished(tr("Can't connect to stderr socket."));
                return;
            }
            wasStarted = true;
        }

        // We are going to read both channels at the same time

        // read stdout channel
        if (stdoutSocket.waitForReadyRead(100)) {
            if (captureState())
                ubjsonBuffer.append(stdoutSocket.readAll());
            else if (captureThumbnails()) {
                // read one image
                image::PNMInfo info;
                QByteArray header;
                int headerLines = 3; // assume no optional comment line
                for (int headerLine = 0; headerLine < headerLines; ++headerLine) {
                    QByteArray line = readLine(stdoutSocket);
                    if (line.isEmpty()) {
                        keepGoing = false;
                        break;
                    }
                    header += line;
                    // if header actually contains optional comment line, ...
                    if (headerLine == 1 && line[0] == '#') {
                        ++headerLines;
                    }
                }

                const char *headerEnd = image::readPNMHeader(header.constData(), header.size(), info);

                // if invalid PNM header was encountered, ...
                if (headerEnd == NULL ||
                    info.channelType != image::TYPE_UNORM8) {
                    qDebug() << "error: invalid snapshot stream encountered";
                    keepGoing = false;
                    break;
                }

                unsigned channels = info.channels;
                unsigned width = info.width;
                unsigned height = info.height;

                // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height";

                QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888);

                int rowBytes = channels * width;
                for (int y = 0; y < height; ++y) {
                    unsigned char *scanLine = snapshot.scanLine(y);
                    if (!read(stdoutSocket, (char *) scanLine, rowBytes)) {
                        keepGoing = false;
                        break;
                    }
                }

                QImage thumb = thumbnail(snapshot);
                thumbnails.insert(info.commentNumber, thumb);
            } else if (isProfiling()) {
                QByteArray line = readLine(stdoutSocket);
                if (line.isEmpty()) {
                    keepGoing = false;
                    break;
                }
                line.append('\0');
                trace::Profiler::parseLine(line.constData(), profile);
            } else {
                outputBuffer.append(stdoutSocket.readAll());
            }
        }

        // read stderr channel
        if (stderrSocket.waitForReadyRead(5) && stderrSocket.canReadLine()) {
            QString line = stderrSocket.readLine();
            if (regexp.indexIn(line) != -1) {
                ApiTraceError error;
                error.callIndex = regexp.cap(1).toInt();
                error.type = regexp.cap(2);
                error.message = regexp.cap(3);
                errors.append(error);
            } else if (!errors.isEmpty()) {
                // Probably a multiligne message
                ApiTraceError &previous = errors.last();
                if (line.endsWith("\n")) {
                    line.chop(1);
                }
                previous.message.append('\n');
                previous.message.append(line);
            }
        }
    }

    if (outputBuffer.size() < 80)
        msg = outputBuffer;

    if (captureState()) {
        QBuffer io(&ubjsonBuffer);
        io.open(QIODevice::ReadOnly);

        parsedJson = decodeUBJSONObject(&io).toMap();
        ApiTraceState *state = new ApiTraceState(parsedJson);
        emit foundState(state);
    }

    if (captureThumbnails() && !thumbnails.isEmpty()) {
        emit foundThumbnails(thumbnails);
    }

    if (isProfiling() && profile) {
        emit foundProfile(profile);
    }

    if (!errors.isEmpty()) {
        emit retraceErrors(errors);
    }

    emit finished(msg);
}
void HttpProxy::onSocketReadyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    QTcpSocket *proxySocket = nullptr;

    QByteArray reqData = socket->readAll();
    int pos = reqData.indexOf("\r\n");
    QByteArray reqLine = reqData.left(pos);
    reqData.remove(0, pos + 2);

    QList<QByteArray> entries = reqLine.split(' ');
    QByteArray method = entries.value(0);
    QByteArray address = entries.value(1);
    QByteArray version = entries.value(2);

    QString host;
    quint16 port;
    QString key;

    if (method != "CONNECT") {
        QUrl url = QUrl::fromEncoded(address);
        if (!url.isValid()) {
            emit info("Invalid URL: " + url.toString());
            socket->disconnectFromHost();
            return;
        }
        host = url.host();
        port = url.port(80);
        QString req = url.path();
        if (url.hasQuery()) {
            req.append('?').append(url.query());
        }
        reqLine = method + " " + req.toUtf8() + " " + version + "\r\n";
        reqData.prepend(reqLine);
        key = host + ':' + QString::number(port);
        proxySocket = socket->findChild<QTcpSocket *>(key);
        if (proxySocket) {
            proxySocket->write(reqData);
            return;//if we find an existing socket, then use it and return
        }
    } else {//CONNECT method
        /*
         * according to http://tools.ietf.org/html/draft-luotonen-ssl-tunneling-03
         * the first line would CONNECT HOST:PORT VERSION
         */
        QList<QByteArray> host_port_list = address.split(':');
        host = QString(host_port_list.first());
        port = host_port_list.last().toUShort();
    }

    proxySocket = new QTcpSocket(socket);
    proxySocket->setProxy(upstreamProxy);
    if (method != "CONNECT") {
        proxySocket->setObjectName(key);
        proxySocket->setProperty("reqData", reqData);
        connect (proxySocket, &QTcpSocket::connected, this, &HttpProxy::onProxySocketConnected);
        connect (proxySocket, &QTcpSocket::readyRead, this, &HttpProxy::onProxySocketReadyRead);
    } else {
        connect (proxySocket, &QTcpSocket::connected, this, &HttpProxy::onProxySocketConnectedHttps);
    }
    connect (proxySocket, &QTcpSocket::disconnected, proxySocket, &QTcpSocket::deleteLater);
    connect (proxySocket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QTcpSocket::error), this, &HttpProxy::onSocketError);
    proxySocket->connectToHost(host, port);
}
void setEclipseProperty(const Matrix& propertyFrames, const QString &hostName, quint16 port,
                        const qint64& caseId, QString propertyName, const int32NDArray& requestedTimeSteps, QString porosityModel)
{
    QTcpSocket socket;
    socket.connectToHost(hostName, port);

    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 += "SetActiveCellProperty " + QString::number(caseId) + " " + propertyName + " " + porosityModel;

    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);

    // Write property data header

    dim_vector mxDims = propertyFrames.dims();

    qint64 cellCount = mxDims.elem(0);
    qint64 timeStepCount = mxDims.elem(1);
    qint64 timeStepByteCount = cellCount * sizeof(double);

    socketStream << (qint64)(timeStepCount);
    socketStream << (qint64)timeStepByteCount;

    const double* internalData = propertyFrames.fortran_vec();

    QStringList errorMessages;
    if (!RiaSocketDataTransfer::writeBlockDataToSocket(&socket, (const char *)internalData, timeStepByteCount*timeStepCount, errorMessages))
    {
        for (int i = 0; i < errorMessages.size(); i++)
        {
            octave_stdout << errorMessages[i].toStdString();
        }

        return;
    }

    QString tmp = QString("riSetActiveCellProperty : Wrote %1").arg(propertyName);

    if (caseId == -1)
    {
        tmp += QString(" to current case.");
    }
    else
    {
        tmp += QString(" to case with Id = %1.").arg(caseId);
    }
    octave_stdout << tmp.toStdString() << " Active Cells : " << cellCount << " Time steps : " << timeStepCount << std::endl;

    while(socket.bytesToWrite() && socket.state() == QAbstractSocket::ConnectedState)
    {
        // octave_stdout << "Bytes to write: " << socket.bytesToWrite() << std::endl;
        socket.waitForBytesWritten(riOctavePlugin::shortTimeOutMilliSecs);
        OCTAVE_QUIT;
    }

    //octave_stdout << "    Socket write completed" << std::endl;

    if (socket.bytesToWrite() && socket.state() != QAbstractSocket::ConnectedState)
    {
        error("riSetActiveCellProperty : ResInsight refused to accept the data. Maybe the dimensions or porosity model is wrong");
    }

#ifdef WIN32
    // TODO: Due to synchronization issues seen on Windows 10, it is required to do a sleep here to be able to catch disconnect
    // signals from the socket. No sleep causes the server to hang.

    Sleep(100);

#endif //WIN32

    return;
}
Exemple #5
0
QByteArray BtQt::sendTrackerRequest(BtTrackerRequest const &req, QUrl trackerUrl)
{
    if(trackerUrl.scheme() != "http") {
        /* There may be "udp" or "https" or other schemes,
         * but not supported now */
        qDebug() << "Request to announce" << trackerUrl;
        qDebug() << "Protocol not supported!";
        return QByteArray();
    }
    /* For the reason that QUrl has used RFC3986 instead of RFC 1738,
     * I have to emulate an HTTP GET request using tcp socket. */
    QTcpSocket socket;
    QString host = trackerUrl.host();
    quint16 port = trackerUrl.port(80);
#ifndef QT_NO_DEBUG
    qDebug() << "Host: " << host;
    qDebug() << "Port: " << port;
#endif // QT_NO_DEBUG
    /*
     *QString host = trackerUrl.toEncoded(QUrl::RemoveScheme | QUrl::RemovePath
     *        | QUrl::RemoveAuthority);
     */
    socket.connectToHost(host, port);
    if(!socket.waitForConnected(1000)) {
        qDebug() << "Can not establish tcp connection to"  << host + ":" + QString::number(port);
        throw -1;
    }
    socket.setSocketOption(QAbstractSocket::KeepAliveOption, 1);

    /* HTTP 1.1 header, for more information please go to RFC2616 */
    QByteArray header;
    header.append("HOST: " + host + ":" + QString::number(port) + "\r\n");
    header.append("User-Agent: " + BtQt::application + " " + BtQt::version + "\r\n");
    header.append("Accept: */*\r\n");
    header.append("Connection: Keep-Alive\r\n");
    header.append("\r\n");

    QByteArray string;
    if(trackerUrl.hasQuery()) {
        string = "GET " + trackerUrl.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority) + '&' + req.toRequestData() + " HTTP/1.1\r\n";
    } else {
        string = "GET " + trackerUrl.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority) + '?' + req.toRequestData() + " HTTP/1.1\r\n";
    }

#ifndef QT_NO_DEBUG
    qDebug() << "Header: " << header;
    qDebug() << "String: " << string;
#endif // QT_NO_DEBUG

    socket.write(string + header);

    if(!socket.waitForReadyRead(1000)) {
        qDebug() << "There were some error occured or possibly time out! Can not get reply!";
        throw -1;
    }
    QByteArray trackerReply = socket.readAll();
    if(trackerReply.isEmpty()) {
        qDebug() << "Warnning! We got an empty reply!";
    }

    /* Get the reply data */
    int replyIdx = trackerReply.indexOf("\r\n\r\n") + 4;

    return trackerReply.mid(replyIdx);
}
Exemple #6
0
/**
 * @details
 */
void PelicanTCPBlobServerTest::test_connection()
{
    // Use Case:
    // ?????? TODO
    // Expect: TODO
    //
    // Create and configure TCP server
    QString xml = "<PelicanTCPBlobServer>"
                  "   <connection port=\"0\"/>"  // 0 = find unused system port
                  "</PelicanTCPBlobServer>";
    ConfigNode config(xml);
    PelicanTCPBlobServer server(config);
    sleep(1);

    // Create a client and connect it to the server
    QTcpSocket tcpSocket;
    tcpSocket.connectToHost( QHostAddress::LocalHost, server.serverPort() );
    if (!tcpSocket.waitForConnected(5000) || tcpSocket.state() == QAbstractSocket::UnconnectedState)
        CPPUNIT_FAIL("Client could not connect to server");

    // Define the data type which the client will except and send request
    StreamDataRequest req;
    DataRequirements require;
    require.setStreamData("testData");
    req.addDataOption(require);

    PelicanClientProtocol clientProtocol;
    QByteArray data = clientProtocol.serialise(req);
    tcpSocket.write(data);
    tcpSocket.waitForBytesWritten(data.size());
    tcpSocket.flush();

    /// ensure we are registered before continuing
    while( server.clientsForStream("testData") == 0 )
    {
        sleep(1);
    }

    {
        // Test Server send
        TestDataBlob blob;
        blob.setData("Testing TCPServer");
        server.send("testData", &blob);

        // Evaluate the response from the server
        tcpSocket.waitForReadyRead();
        boost::shared_ptr<ServerResponse> r = clientProtocol.receive(tcpSocket);
        CPPUNIT_ASSERT( r->type() == ServerResponse::Blob );
        TestDataBlob blobResult;
        blobResult.deserialise(tcpSocket, ((DataBlobResponse*)r.get())->byteOrder());
        CPPUNIT_ASSERT(blobResult == blob);
    }

    {
        // Test Server send
        TestDataBlob blob;
        blob.setData("Testing TCPServer again");
        server.send("testData", &blob);

        // Evaluate the response from the server
        tcpSocket.waitForReadyRead();
        boost::shared_ptr<ServerResponse> r = clientProtocol.receive(tcpSocket);
        CPPUNIT_ASSERT( r->type() == ServerResponse::Blob );
        TestDataBlob blobResult;
        blobResult.deserialise(tcpSocket, ((DataBlobResponse*)r.get())->byteOrder());
        CPPUNIT_ASSERT(blobResult == blob);
    }
}
Exemple #7
0
int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);

    const QStringList args = app.arguments();
    QString arg_port;
    QString arg_server;
    QString arg_xmlFile;
    bool arg_crash = false;
    bool arg_garbage = false;
    uint arg_wait = 0;

    const QProcessEnvironment sysEnv = QProcessEnvironment::systemEnvironment();
    arg_xmlFile = sysEnv.value("QCIT_INPUT_FILE");

    for (int i = 1; i < args.size(); ++i) {
        const QString& arg = args.at(i);
        if (arg.startsWith(QLatin1String("--xml-socket="))) {
            arg_server = arg.mid(13, arg.indexOf(':') - 13);
            arg_port = arg.mid(13 + arg_server.length() + 1);
        } else if (args.size() > i + 1
                    && (args.at(i) == QLatin1String("-i")
                        || args.at(i) == QLatin1String("--xml-input"))) {
            arg_xmlFile = args.at(i+1);
            ++i;
        } else if (arg == QLatin1String("-c") || arg == QLatin1String("--crash")) {
            arg_crash = true;
        } else if (arg == QLatin1String("-g") || arg == QLatin1String("--garbage")) {
            arg_garbage = true;
        } else if (args.size() > i + 1 && (arg == QLatin1String("-w") || arg == QLatin1String("--wait"))) {
            bool ok;
            arg_wait = args.at(i+1).toUInt(&ok);
            if (!ok) {
                qerr << "ERROR: invalid wait time given" << args.at(i+1) << endl;
                usage(qerr);
                return 4;
            }
        } else if (args.at(i) == QLatin1String("--help") || args.at(i) == QLatin1String("-h")) {
            usage(qout);
            return 0;
        }
    }

    if (arg_xmlFile.isEmpty()) {
        qerr << "ERROR: no XML input file given" << endl;
        usage(qerr);
        return 1;
    }
    if (arg_server.isEmpty()) {
        qerr << "ERROR: no server given" << endl;
        usage(qerr);
        return 2;
    }
    if (arg_port.isEmpty()) {
        qerr << "ERROR: no port given" << endl;
        usage(qerr);
        return 3;
    }

    QFile xmlFile(arg_xmlFile);
    if (!xmlFile.exists() || !xmlFile.open(QIODevice::ReadOnly)) {
        qerr << "ERROR: invalid XML file" << endl;
        usage(qerr);
        return 10;
    }
    bool ok = false;
    quint16 port = arg_port.toUInt(&ok);
    if (!ok) {
        qerr << "ERROR: invalid port" << endl;
        usage(qerr);
        return 30;
    }

    QTcpSocket socket;
    socket.connectToHost(arg_server, port, QIODevice::WriteOnly);
    if (!socket.isOpen()) {
        qerr << "ERROR: could not open socket to server:" << arg_server << ":" << port << endl;
        usage(qerr);
        return 20;
    }
    if (!socket.waitForConnected()) {
        qerr << "ERROR: could not connect to socket: " << socket.errorString() << endl;
        return 21;
    }

    OutputGenerator generator(&socket, &xmlFile);
    QObject::connect(&generator, SIGNAL(finished()), &app, SLOT(quit()));
    generator.setCrashRandomly(arg_crash);
    generator.setOutputGarbage(arg_garbage);
    generator.setWait(arg_wait);

    return app.exec();
}
void LockTestClient::startTests()
{
    QTcpSocket socket;
    socket.connectToHost ( "localhost", 55555);
    char control;
    
    #define GetNextCommand()      if(socket.waitForReadyRead (-1) )\
                                                        {\
                                                            if(socket.bytesAvailable() > 1)\
                                                                qDebug()<<"Something is wrong here";\
                                                            socket.getChar(&control);\
                                                            if(control == 'a')\
                                                            {\
                                                                socket.disconnectFromHost();\
                                                                return;\
                                                            }\
                                                            if(control != 'n')\
                                                            { \
                                                                 qDebug()<<"Wrong control command";\
                                                            }\
                                                        }
    
    if(socket.waitForConnected (-1))
    {
        QFile file("lock.file");
        
        if(!file.open(QIODevice::ReadWrite))
        {
            qDebug()<<"Could not open lockfile";
            return;
        }
        
        if(1)
        {
            GetNextCommand();
            //Trying to readlock the same region
            QxtFileLock lock(&file,0x10,20,QxtFileLock::ReadLock);
            if(lock.lock())
                socket.putChar('s');    //s for success f for fail
            else
                socket.putChar('f');
            socket.waitForBytesWritten(-1);
        }
        
        if(1)
        {
            GetNextCommand();
             //Trying to lock the same region with different locks
            QxtFileLock lock(&file,0x10,20,QxtFileLock::WriteLock); 
            
            if(!lock.lock())
                socket.putChar('s');    //s for success f for fail
            else
                socket.putChar('f');
            socket.waitForBytesWritten(-1);
        }
        
        if(1)
        {
            GetNextCommand();
             //Trying to writelock the same region
            QxtFileLock lock(&file,0x10,20,QxtFileLock::WriteLock); 
            
            if(!lock.lock())
                socket.putChar('s');    //s for success f for fail
            else
                socket.putChar('f');
            socket.waitForBytesWritten(-1);
        }
        
        if(1)
        {
            GetNextCommand();
             //Trying to writelock different regions
            QxtFileLock lock(&file,0x10+21,20,QxtFileLock::WriteLock); 
            
            if(lock.lock())
                socket.putChar('s');    //s for success f for fail
            else
                socket.putChar('f');
            socket.waitForBytesWritten(-1);
        }
        
    }
}
/*!
    \internal
*/
void QInterProcessChannel::init()
{
    while ( isRunning() )
        quit();
    
    if ( pServerTimer )
    {
        pServerTimer->stop();
        delete pServerTimer;
        pServerTimer = 0;
    }
    
    bool ok = true;
    
    m_port = 0;
    m_addr = QHostAddress::LocalHost;
    
    pServer = new QTcpServer(this);
    pServer->listen(m_addr, m_port);
    
    connect(pServer , SIGNAL( newConnection() ),
            this    , SLOT  ( connection() ) );
    
    if ( QFile::exists(rcFile) )
    {
        /*
            found a server config file, let us assume it is from a running server
        */
        //qDebug("checking old server...");
        
        QSettings conf(rcFile, QSettings::IniFormat);
        
        m_port = conf.value("port").toUInt();
        m_addr = QHostAddress(conf.value("address").toString());
        
        QTcpSocket *pSocket = new QTcpSocket(this);
        
        if ( !m_addr.isNull() && m_port )
        {
            pSocket->connectToHost(m_addr, m_port);
            ok = pSocket->waitForConnected(WAIT_TIMEOUT);
            
            if ( ok ) ok &= (bool)pSocket->write("--check");
            if ( ok ) ok &= (bool)pSocket->waitForBytesWritten(WAIT_TIMEOUT);
            if ( ok ) ok &= (bool)pSocket->waitForReadyRead(WAIT_TIMEOUT);
            if ( ok ) ok &= (pSocket->readAll() == "[ALIVE]");
            
        } else {
            ok = false;
        }
        
        if ( !ok )
        {
            QFile::remove(rcFile);
        }
        
        pSocket->disconnectFromHost();
        delete pSocket;
    }
    
    if ( !QFile::exists(rcFile) )
    {
        // no server found... Create one
        //qDebug("setting up new server...");
        
        m_port = pServer->serverPort();
        m_addr = pServer->serverAddress();
        
        QSettings conf(rcFile, QSettings::IniFormat);
        conf.setValue("port", m_port);
        conf.setValue("address", m_addr.toString());
        
        emit gotServerRole();
        emit serverRoleChanged(true);
    } else {
        // server found we'll hook on it later on...
        pServer->close();
        pServer = 0;
        
        emit serverRoleChanged(false);
    }
    
    start();
}
void getCaseGroups(std::vector<QString>& groupNames, std::vector<int>& groupIds, const QString &hostName, quint16 port)
{
    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("GetCaseGroups");
    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(riOctavePlugin::longTimeOutMilliSecs))
        {
            error((("Waiting for data: ") + socket.errorString()).toLatin1().data());
            return;
        }
        OCTAVE_QUIT;
    }

    quint64 byteCount;
    socketStream >> byteCount;

    quint64 groupCount;
    socketStream >> groupCount;

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

    quint64 group = 0;
    while (group < groupCount)
    {
        QString caseGroupName;
        qint64 caseGroupId;

        socketStream >> caseGroupName;
        socketStream >> caseGroupId;

        groupNames.push_back(caseGroupName);
        groupIds.push_back(caseGroupId);

        group++;
    }

    return;
}
void getActiveCellCenters(NDArray& cellCenterValues, const QString &hostName, quint16 port, const qint32& caseId, const QString& porosityModel)
{
    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 = 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(riOctavePlugin::shortTimeOutMilliSecs))
        {
            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(riOctavePlugin::longTimeOutMilliSecs))
        {
            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;
}
Exemple #12
0
void getTimeStepDates(  std::vector<double>& decimalDays,
                        const qint64& caseId,
                        const QString& hostName,
                        quint16 port)
{
    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 = QString("GetTimeStepDays %1").arg(caseId);
    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;

    octave_stdout << "byte count: " << byteCount << ", Timesteps: " << timeStepCount << std::endl;

    for (size_t i = 0; i < timeStepCount; i++)
    {
        double doubleValue;

        socketStream >> doubleValue;
        decimalDays.push_back(doubleValue);
    }

    return;
}
Exemple #13
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::shortTimeOutMilliSecs))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    quint64 byteCount;
    socketStream >> byteCount;

    while (socket.bytesAvailable() < (int)(byteCount))
    {
        if (!socket.waitForReadyRead(riOctavePlugin::shortTimeOutMilliSecs))
        {
            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;
}
Exemple #14
0
//! [4]
void FortuneThread::run()
{
    mutex.lock();
//! [4] //! [5]
    QString serverName = hostName;
    quint16 serverPort = port;
    mutex.unlock();
//! [5]

//! [6]
    while (!quit) {
//! [7]
        const int Timeout = 5 * 1000;

        QTcpSocket socket;
        socket.connectToHost(serverName, serverPort);
//! [6] //! [8]

        if (!socket.waitForConnected(Timeout)) {
            emit error(socket.error(), socket.errorString());
            return;
        }
//! [8] //! [9]

        while (socket.bytesAvailable() < (int)sizeof(quint16)) {
            if (!socket.waitForReadyRead(Timeout)) {
                emit error(socket.error(), socket.errorString());
                return;
            }
//! [9] //! [10]
        }
//! [10] //! [11]

        quint16 blockSize;
        QDataStream in(&socket);
        in.setVersion(QDataStream::Qt_4_0);
        in >> blockSize;
//! [11] //! [12]

        while (socket.bytesAvailable() < blockSize) {
            if (!socket.waitForReadyRead(Timeout)) {
                emit error(socket.error(), socket.errorString());
                return;
            }
//! [12] //! [13]
        }
//! [13] //! [14]

        mutex.lock();
        QString fortune;
        in >> fortune;
        emit newFortune(fortune);
//! [7] //! [14] //! [15]

        cond.wait(&mutex);
        serverName = hostName;
        serverPort = port;
        mutex.unlock();
    }
//! [15]
}
Exemple #15
0
int main(int argc, char* argv[])
{
  terrama2::core::TerraMA2Init terramaRaii("example", 0);
  QCoreApplication app(argc, argv);

  QJsonObject obj;
  QJsonArray providersArray;
  providersArray.push_back(terrama2::core::toJson(buildInputProvider()));
  obj.insert("DataProviders", providersArray);

  QJsonArray seriesArray;
  seriesArray.push_back(terrama2::core::toJson(buildInputDataSeries()));
  obj.insert("DataSeries", seriesArray);

  QJsonDocument doc(obj);

  std::shared_ptr<terrama2::core::DataManager> dataManager = std::make_shared<MockDataManager>();
  terrama2::core::TcpManager tcpManager(dataManager, std::weak_ptr<terrama2::core::ProcessLogger>());
  tcpManager.listen(QHostAddress::Any, 30000);

  QByteArray bytearray;
  QDataStream out(&bytearray, QIODevice::WriteOnly);


  QJsonObject logDb;
  logDb.insert("PG_HOST", QString::fromStdString(TERRAMA2_DATABASE_HOST));
  logDb.insert("PG_PORT", QString::fromStdString(TERRAMA2_DATABASE_PORT));
  logDb.insert("PG_USER", QString::fromStdString(TERRAMA2_DATABASE_USERNAME));
  logDb.insert("PG_PASSWORD", QString::fromStdString(TERRAMA2_DATABASE_PASSWORD));
  logDb.insert("PG_DB_NAME", QString::fromStdString(TERRAMA2_DATABASE_DBNAME));

  QJsonObject serviceConf;
  serviceConf.insert("instance_id", 1);
  serviceConf.insert("log_database", logDb);

  QJsonDocument serviceConfDoc(serviceConf);
  QByteArray serviceConfBytearray;
  QDataStream out2(&serviceConfBytearray, QIODevice::WriteOnly);
  auto jsonServiceConf = serviceConfDoc.toJson(QJsonDocument::Compact);
  out2 << static_cast<uint32_t>(0);
  out2 << static_cast<uint32_t>(terrama2::core::TcpSignal::UPDATE_SERVICE_SIGNAL);
  out2 << jsonServiceConf;
  serviceConfBytearray.remove(8, 4);//Remove QByteArray header
  out2.device()->seek(0);
  out2 << static_cast<uint32_t>(serviceConfBytearray.size() - sizeof(uint32_t));



  auto json = doc.toJson(QJsonDocument::Compact);
  out << static_cast<uint32_t>(0);
  out << static_cast<uint32_t>(terrama2::core::TcpSignal::ADD_DATA_SIGNAL);
  out << json;
  bytearray.remove(8, 4);//Remove QByteArray header
  out.device()->seek(0);
  out << static_cast<uint32_t>(bytearray.size() - sizeof(uint32_t));



  QTcpSocket socket;
  socket.connectToHost("localhost", 30000);
  socket.write(serviceConfBytearray);
  socket.waitForBytesWritten();
  socket.write(bytearray);

  QTimer timer;
  QObject::connect(&timer, SIGNAL(timeout()), QCoreApplication::instance(), SLOT(quit()));
  timer.start(10000);
  app.exec();

  

  return 0;
}
Exemple #16
0
void BasicEmulator::reset()
{
    LOG_DEBUG("End of BasicEmulator::reset");

    // Connect to emulator daemon
    QTcpSocket socket;
    socket.connectToHost(QHostAddress(m_addr), m_port);
    if( !socket.waitForConnected(3 * 1000))
    {
        LOG_ERROR(QString("Cannot connect to emulator daemon @ %1:%2")
            .arg(m_addr).arg(m_port));
        return;
    }
    
    // Send request
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out << (quint32)0;
    out << QString("Basic");
    out << QString("RESET");
    out.device()->seek(0);
    out << (quint32)(block.size() - 4);

    socket.write(block);
    socket.waitForBytesWritten(-1);
    
    // Receive response
    while( socket.bytesAvailable() < 4 )
    {
        if( !socket.waitForReadyRead(5 * 1000))
        {
            LOG_WARN("BasicEmulator reset timed out");
            return;
        }
    }
    
    quint32 blockSize;
    QDataStream in(&socket);
    in >> blockSize;
    
    while( socket.bytesAvailable() < blockSize )
    {
        if( !socket.waitForReadyRead(5 * 1000))
        {
            LOG_WARN("BasicEmulator reset timed out");
            return;
        }
    }
    
    bool ok;
    QString description;
    in >> ok >> description;
    
    // Display result
    if( ok )
    {
        LOG_INFO("Parameters successfully reset");
        LOG_INFO(QString("Description: %1").arg(description));
        
        m_params.clear();
    }
    else
    {
        LOG_WARN("Parameter reset failed");
        LOG_WARN(QString("Description: %1").arg(description));
    }

    // Close connection
    socket.close();
    LOG_DEBUG("End of BasicEmulator::reset");
}
Exemple #17
0
void Tunneld::onENetPeerConnected(ENetHost *enhost, ENetPeer *enpeer, quint32 data)
{
    qDebug()<<enhost<<enpeer<<enpeer->address.vaddr<<data<<".";

    QTcpSocket *sock = new QTcpSocket();
    QObject::connect(sock, &QTcpSocket::readyRead, this, &Tunneld::onTcpReadyRead, Qt::QueuedConnection);
    QObject::connect(sock, &QTcpSocket::disconnected, this, &Tunneld::onTcpDisconnected, Qt::QueuedConnection);

    enpeer->timeoutLimit *= 10;
    enpeer->timeoutMinimum *= 10;
    enpeer->timeoutMaximum *= 10;

    ToxTunChannel *chan = new ToxTunChannel();
    chan->m_sock = sock;
    chan->m_enpeer = enpeer;
    chan->m_enhost = enhost;
    chan->m_peer_pubkey = "";
    // chan->m_peer_pubkey = QString(enpeer->toxid);
    chan->m_peer_pubkey = m_toxkit->friendGetPublicKey(enpeer->address.vaddr);
    chan->m_host = "127.0.0.1";
    chan->m_port = data;  // connect to port
    chan->m_conid = this->nextConid();


    if (peerChansCount(enpeer) > 0) {
        int cc0 = peerChansCount(enpeer);
        qDebug()<<enpeer->incomingPeerID<<cc0;
        ToxTunChannel *tchan = peerLastChan(enpeer);
        qDebug()<<tchan<<tchan->m_conid
                <<tchan->sock_closed<<tchan->peer_sock_closed<<tchan->enet_closed;
        // promiseChannelCleanup(tchan);

        // 无条件把相关联的chan清理掉
        if (tchan->sock_closed == true && tchan->peer_sock_closed == false) {
            qDebug()<<"need force cleanup:"<<tchan->m_conid;
            tchan->peer_sock_closed = true;
            tchan->force_closed = true;
            promiseChannelCleanup(tchan); 
        }
        else
        if (tchan->sock_closed == false && tchan->peer_sock_closed == false) {
            qDebug()<<"need force cleanup:"<<tchan->m_conid;
            tchan->peer_sock_closed = true;
            tchan->sock_closed = true;
            tchan->force_closed = true;
            promiseChannelCleanup(tchan); 
        }

        int cc1 = peerChansCount(enpeer);
        if (cc1 != 0) {
            qDebug()<<enpeer->incomingPeerID<<cc0;            
        }
        assert(peerChansCount(enpeer) == 0);
        // assert(1 == 2);
    }
    peerAddChan(enpeer, chan);


    this->m_sock_chans[sock] = chan;
    // this->m_enpeer_chans[enpeer] = chan;
    this->m_conid_chans[chan->m_conid] = chan;

    // sock->connectToHost("127.0.0.1", 8118);
    sock->connectToHost(chan->m_host, chan->m_port);
    sock->waitForConnected();
}
void getCellCorners(NDArray& cellCornerValues, const QString &hostName, quint16 port, const qint32& caseId, const quint32& gridIndex)
{
    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 = QString("GetCellCorners %1 %2").arg(caseId).arg(gridIndex);
    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)(5 * sizeof(quint64)))
    {
        if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    quint64 cellCountI;
    quint64 cellCountJ;
    quint64 cellCountK;
    quint64 cellCount;
    quint64 byteCount;

    socketStream >> cellCount;
    socketStream >> cellCountI;
    socketStream >> cellCountJ;
    socketStream >> cellCountK;
    socketStream >> byteCount;

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

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

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

        OCTAVE_QUIT;
    }

    return;
}
void getCases(std::vector<qint64>& caseIds, std::vector<QString>& caseNames, std::vector<QString>& caseTypes, std::vector<qint64>& caseGroupIds, const qint64& caseGroupId, const QString &hostName, quint16 port)
{
    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 = QString("GetCases %1").arg(caseGroupId);
    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::shortTimeOutMilliSecs))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    quint64 byteCount;
    socketStream >> byteCount;

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

    quint64 caseCount;
    socketStream >> caseCount;

    qint64  caseId = -1;
    QString caseName;
    QString caseType;
    qint64  caseGroupIdFromSocket = -1;

    for (size_t i = 0; i < caseCount; i++)
    {
        socketStream >> caseId;
        socketStream >> caseName;
        socketStream >> caseType;
        socketStream >> caseGroupIdFromSocket;

        caseIds.push_back(caseId);
        caseNames.push_back(caseName);
        caseTypes.push_back(caseType);
        caseGroupIds.push_back(caseGroupIdFromSocket);
    }

    return;
}
Exemple #20
0
int main(void)
{
    QTcpSocket socket;

    socket.connectToHost("127.0.0.1", 8888);

    if (!socket.waitForConnected()) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to connect");
        return -1;
    }

    if (!socket.waitForReadyRead()) {
        LOG_ENTRY(MyLogger::ERROR, "No data received");
        return -1;
    }

    //////////////////////
    //got the HELLO
    /////////////////////
    QByteArray message = socket.readAll();

    int size = qFromBigEndian<qint32>((const uchar*) message.data());
    LOG_ENTRY(MyLogger::INFO, "Message recived. Size: "<<size);
    message = message.mid(4);
    if (size != 1
            || MessageCodes::getMessageType(message) != MessageCodes::HELLO) {
        LOG_ENTRY(MyLogger::ERROR,
                "Received wrong message: "<<MessageCodes::getMessageType(message));
        return -1;
    }

    LOG_ENTRY(MyLogger::INFO, "Received HELLO");

    QString protocolVersion = "v1.0";

    message = MessageCodes::getMessageCode(MessageCodes::REQUEST_PROTOCOL)
            + protocolVersion.toUtf8();

    uchar rawSize[4];
    qToBigEndian((qint32) message.size(), rawSize);

    message = QByteArray((char*) rawSize, 4) + message;
    //////////////////////
    //sent REQUEST_PROTOCOL
    ///////////////////////
    socket.write(message);
    if (!socket.waitForBytesWritten()) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to send data");
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "REQUEST_PROTOCOL sent");

    if (socket.bytesAvailable() == 0 && !socket.waitForReadyRead()) {
        LOG_ENTRY(MyLogger::ERROR, "No data received");
        return -1;
    }

    ///////////////////////
    //Got ACK
    //////////////////////
    message = socket.readAll();

    size = qFromBigEndian<qint32>((const uchar*) message.data());
    LOG_ENTRY(MyLogger::INFO, "Message recived. Size: "<<size);
    message = message.mid(4);
    if (size != 1
            || MessageCodes::getMessageType(message) != MessageCodes::ACK) {
        LOG_ENTRY(MyLogger::ERROR,
                "Received wrong message: "<<MessageCodes::getMessageType(message));
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "Received ACK");

    ///////////
    // Let's read the private key
    //////////

    AsymetricAlgorithm *algorithm = CryptographicFactory::getAsymAlgorithm(
            "RSA_OAEP_SHA");

    if (!algorithm) {
        LOG_ENTRY(MyLogger::ERROR, "No such algorithm");
        return -1;
    }
    QByteArray key;
    QFile file("keys/Providers::Provider1.pub");
    if (file.exists() && file.open(QIODevice::ReadOnly)) {
        key = file.readAll();

        try {
            algorithm->setPublicKey(key);
            LOG_ENTRY(MyLogger::INFO,
                    "Content of "<<file.fileName()<<" used as key file.");
        } catch (AsymetricAlgorithm::AsymmetricAlgorithmException& e) {
            LOG_ENTRY(MyLogger::ERROR,
                    "Unable to use content of file: "<<file.fileName()<<" as key: "<<e.what());
        }
    } else {
        LOG_ENTRY(MyLogger::ERROR,
                "Unable to use file: "<<file.fileName()<<" as key file");
        return -1;
    }

    char randoms[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };

    QString clientID = "Clients::Client1";

    message = MessageCodes::getMessageCode(MessageCodes::CLIENT_ID)
            + QByteArray(randoms, 8) + clientID.toUtf8();

    try {
        message = algorithm->encrypt(message);
    } catch (...) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to encrypt");
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "");

    qToBigEndian((qint32) message.size(), rawSize);

    message = QByteArray((char*) rawSize, 4) + message;
    //////////////////////
    //sent CLIENT_ID
    ///////////////////////
    socket.write(message);
    if (!socket.waitForBytesWritten()) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to send data");
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "CLIENT_ID sent");

    if (socket.bytesAvailable() == 0 && !socket.waitForReadyRead()) {
        LOG_ENTRY(MyLogger::ERROR, "No data received");
        return -1;
    }

    ///////////////////////
    //Got confirmation and sign of client
    //////////////////////
    message = socket.readAll();

    //prepare signer to verify
    SignAlgorithm *signer = CryptographicFactory::getSignAlgorithm(
            "RSASSA_PKCSv15_SHA256");
    signer->setPublicKey(key);

    size = qFromBigEndian<qint32>((const uchar*) message.data());
    LOG_ENTRY(MyLogger::INFO, "Message recived. Size: "<<size);
    message = message.mid(4);
    if (size <= 0
            || MessageCodes::getMessageType(message)
                    != MessageCodes::CHOOSE_ALGORITHM) {
        LOG_ENTRY(MyLogger::ERROR,
                "Received wrong message: "<<MessageCodes::getMessageType(message));
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO,
            "Received CHOOSE_ALGORITHM, hash size: "<< message.mid(5, size - 5).size());

    if (!signer->verify(QByteArray(randoms, 8) + clientID.toUtf8(),
            message.mid(1, size - 1))) {
        LOG_ENTRY(MyLogger::ERROR, "Signature missmatch");
        return -1;
    }

    LOG_ENTRY(MyLogger::INFO, "Signature valid.");

    //prepare the message for choosing algorithm
    message = MessageCodes::getMessageCode(MessageCodes::CHOOSEN_ALGORITHM)
            + QString("AES_CBC").toUtf8();

    try {
        message = algorithm->encrypt(message);
    } catch (...) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to encrypt");
        return -1;
    }

    qToBigEndian((qint32) message.size(), rawSize);

    message = QByteArray((char*) rawSize, 4) + message;
    //////////////////////
    //sent CHOOSEN_Algorithm
    ///////////////////////
    socket.write(message);
    if (!socket.waitForBytesWritten()) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to send data");
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "CHOOSE_ALGORITHM sent");

    if (socket.bytesAvailable() == 0 && !socket.waitForReadyRead()) {
        LOG_ENTRY(MyLogger::ERROR, "No data received");
        return -1;
    }

    ///////////////////////
    //Got ACK
    //////////////////////
    message = socket.readAll();

    size = qFromBigEndian<qint32>((const uchar*) message.data());
    LOG_ENTRY(MyLogger::INFO, "Message recived. Size: "<<size);
    message = message.mid(4);
    if (size != 1
            || MessageCodes::getMessageType(message) != MessageCodes::ACK) {
        LOG_ENTRY(MyLogger::ERROR,
                "Received wrong message: "<<MessageCodes::getMessageType(message));
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "Received ACK");

    //////////////////
    //generate the key, count the hash encrytp and send it
    //////////////////

    SymetricAlgorithm *sym = CryptographicFactory::getSymAlgorithm("AES_CBC");
    HashAlgorithm *hash = CryptographicFactory::getHashAlgorithm("SHA_256");

    if (!sym || !hash) {
        LOG_ENTRY(MyLogger::ERROR, "No such algorithm");
        return -1;
    }

    sym->generateKey();
    QByteArray symetricKey = sym->getKey();
    qToBigEndian((qint32) symetricKey.size(), rawSize);

    message = MessageCodes::getMessageCode(MessageCodes::ESTABLISH_ENCRYPTION)
            + QByteArray((char*) rawSize, 4) + sym->getKey() + sym->getIv();

    QByteArray messageHash = hash->generateHash(message);

    qToBigEndian((qint32) messageHash.size(), rawSize);

    message = QByteArray((char*) rawSize, 4) + message + messageHash;

    try {
        message = algorithm->encrypt(message);
    } catch (...) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to encrypt");
        return -1;
    }

    qToBigEndian((qint32) message.size(), rawSize);
    LOG_ENTRY(MyLogger::INFO, message.size());
    message = QByteArray((char*) rawSize, 4) + message;

    socket.write(message);
    if (!socket.waitForBytesWritten()) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to send data");
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "ESTABLISH_ENCRYPTION sent");

    if (socket.bytesAvailable() == 0 && !socket.waitForReadyRead()) {
        LOG_ENTRY(MyLogger::ERROR, "No data received");
        return -1;
    }

    /////////////////////////
    //get CHOOSE_AUTH_MODULE
    ////////////////////////
    message = socket.readAll();

    size = qFromBigEndian<qint32>((const uchar*) message.data());
    LOG_ENTRY(MyLogger::INFO, "Message received. Size: "<<size);
    message = message.mid(4);

    //check the hash
    QByteArray plainMessage = sym->decrypt(message);
    size = qFromBigEndian<qint32>((const uchar*) plainMessage.data());
    messageHash = plainMessage.right(size);
    plainMessage = plainMessage.mid(4, plainMessage.size() - 4 - size);

    if (!hash->verifyHash(plainMessage, messageHash)) {
        LOG_ENTRY(MyLogger::ERROR, "Wrong hash given");
        return -1;
    }

    if (plainMessage.size() != 1
            || MessageCodes::getMessageType(plainMessage)
                    != MessageCodes::CHOOSE_AUTH_MODULE) {
        LOG_ENTRY(MyLogger::ERROR,
                "Received wrong message: "<<MessageCodes::getMessageType(plainMessage)<<" size: "<<plainMessage.size());
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "Received CHOOSE_AUTH_MODULE");

    ////////////////////
    // send CHOOSEN_AUTH_MODULE
    ///////////////////

    plainMessage = MessageCodes::getMessageCode(
            MessageCodes::CHOOSEN_AUTH_MODULE) + QString("LoginPass").toUtf8();

    messageHash = hash->generateHash(plainMessage);

    qToBigEndian((qint32) messageHash.size(), rawSize);

    message = QByteArray((char*) rawSize, 4) + plainMessage + messageHash;

    try {
        message = sym->encrypt(message);
    } catch (...) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to encrypt");
        return -1;
    }

    qToBigEndian((qint32) message.size(), rawSize);
    LOG_ENTRY(MyLogger::INFO, message.size());
    message = QByteArray((char*) rawSize, 4) + message;

    socket.write(message);
    if (!socket.waitForBytesWritten()) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to send data");
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "CHOOSEN_AUTH_MODULE sent");

    if (socket.bytesAvailable() == 0 && !socket.waitForReadyRead()) {
        LOG_ENTRY(MyLogger::ERROR, "No data received");
        return -1;
    }

    ////////////////////////////////////////////////////////////////////////
    // LOGIN PASS AUTH
    ///////////////////////////////////////////////////////////////////////
    //get AUTH_DATA
    message = socket.readAll();

    size = qFromBigEndian<qint32>((const uchar*) message.data());
    LOG_ENTRY(MyLogger::INFO, "Message received. Size: "<<size);
    message = message.mid(4);

    //check the hash
    plainMessage = sym->decrypt(message);
    size = qFromBigEndian<qint32>((const uchar*) plainMessage.data());
    messageHash = plainMessage.right(size);
    plainMessage = plainMessage.mid(4, plainMessage.size() - 4 - size);

    if (!hash->verifyHash(plainMessage, messageHash)) {
        LOG_ENTRY(MyLogger::ERROR, "Wrong hash given");
        return -1;
    }

    if (MessageCodes::getMessageType(plainMessage) != MessageCodes::AUTH_DATA) {
        LOG_ENTRY(MyLogger::ERROR,
                "Received wrong message: "<<MessageCodes::getMessageType(plainMessage)<<" size: "<<plainMessage.size());
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "Received AUTH_DATA");

    plainMessage = plainMessage.mid(1);

    if (plainMessage[0] != (char) 0) {
        LOG_ENTRY(MyLogger::ERROR, "Received wrong auth message");
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "Received REQUEST_LOGIN");

    ////////////////////
    // send LOGIN
    ///////////////////

    char authCode = 1;
    plainMessage = MessageCodes::getMessageCode(MessageCodes::AUTH_DATA)
            + QByteArray(&authCode, 1) + QString("LoginTestowy").toUtf8();

    messageHash = hash->generateHash(plainMessage);

    qToBigEndian((qint32) messageHash.size(), rawSize);

    message = QByteArray((char*) rawSize, 4) + plainMessage + messageHash;

    try {
        message = sym->encrypt(message);
    } catch (...) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to encrypt");
        return -1;
    }

    qToBigEndian((qint32) message.size(), rawSize);
    LOG_ENTRY(MyLogger::INFO, message.size());
    message = QByteArray((char*) rawSize, 4) + message;

    socket.write(message);
    if (!socket.waitForBytesWritten()) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to send data");
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "AUTH_DATA sent");

    if (socket.bytesAvailable() == 0 && !socket.waitForReadyRead()) {
        LOG_ENTRY(MyLogger::ERROR, "No data received");
        return -1;
    }

    ////////////////////
    // get REQUEST_PASSWORD
    ///////////////////
    message = socket.readAll();

    size = qFromBigEndian<qint32>((const uchar*) message.data());
    LOG_ENTRY(MyLogger::INFO, "Message received. Size: "<<size);
    message = message.mid(4);

    //check the hash
    plainMessage = sym->decrypt(message);
    size = qFromBigEndian<qint32>((const uchar*) plainMessage.data());
    messageHash = plainMessage.right(size);
    plainMessage = plainMessage.mid(4, plainMessage.size() - 4 - size);

    if (!hash->verifyHash(plainMessage, messageHash)) {
        LOG_ENTRY(MyLogger::ERROR, "Wrong hash given");
        return -1;
    }

    if (MessageCodes::getMessageType(plainMessage) != MessageCodes::AUTH_DATA) {
        LOG_ENTRY(MyLogger::ERROR,
                "Received wrong message: "<<MessageCodes::getMessageType(plainMessage)<<" size: "<<plainMessage.size());
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "Received AUTH_DATA");

    plainMessage = plainMessage.mid(1);

    if (plainMessage[0] != (char) 2) {
        LOG_ENTRY(MyLogger::ERROR, "Received wrong auth message");
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "Received REQUEST_PASSWORD");

    ////////////////////
    // send Password
    ///////////////////

    authCode = 3;
    plainMessage = MessageCodes::getMessageCode(MessageCodes::AUTH_DATA)
            + QByteArray(&authCode, 1) + QString("PasswordTestowe").toUtf8();

    messageHash = hash->generateHash(plainMessage);

    qToBigEndian((qint32) messageHash.size(), rawSize);

    message = QByteArray((char*) rawSize, 4) + plainMessage + messageHash;

    try {
        message = sym->encrypt(message);
    } catch (...) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to encrypt");
        return -1;
    }

    qToBigEndian((qint32) message.size(), rawSize);
    LOG_ENTRY(MyLogger::INFO, message.size());
    message = QByteArray((char*) rawSize, 4) + message;

    socket.write(message);
    if (!socket.waitForBytesWritten()) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to send data");
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "AUTH_DATA sent");

    if (socket.bytesAvailable() == 0 && !socket.waitForReadyRead()) {
        LOG_ENTRY(MyLogger::ERROR, "No data received");
        return -1;
    }

    /////////////////////////
    //get WAITING_FOR_LOGS
    ////////////////////////
    message = socket.readAll();

    size = qFromBigEndian<qint32>((const uchar*) message.data());
    LOG_ENTRY(MyLogger::INFO, "Message received. Size: "<<size);
    message = message.mid(4);

    //check the hash
    plainMessage = sym->decrypt(message);
    size = qFromBigEndian<qint32>((const uchar*) plainMessage.data());
    messageHash = plainMessage.right(size);
    plainMessage = plainMessage.mid(4, plainMessage.size() - 4 - size);

    if (!hash->verifyHash(plainMessage, messageHash)) {
        LOG_ENTRY(MyLogger::ERROR, "Wrong hash given");
        return -1;
    }

    if (plainMessage.size() != 1
            || MessageCodes::getMessageType(plainMessage)
                    != MessageCodes::WAITING_FOR_LOGS) {
        LOG_ENTRY(MyLogger::ERROR,
                "Received wrong message: "<<MessageCodes::getMessageType(plainMessage)<<" size: "<<plainMessage.size());
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "Received WAITING_FOR_LOGS");

    ////////////////////
    // send LOGS_PORTION
    ///////////////////
    char checkCode = 0, checkState = 0;

    plainMessage = MessageCodes::getMessageCode(MessageCodes::LOGS_PORTION);
    //code of log type
    plainMessage.append(QByteArray("\0", 1));
    //timestamp
    time_t t = time(0L);
    t = (time_t) qToBigEndian((qint64)t);
    plainMessage.append(QByteArray((char *)&t, 8));
    //hostname
    plainMessage.append(QString("hostName").toUtf8() + QByteArray("\0", 1));
    //status
    plainMessage.append(QByteArray("\0", 1));
    //output
    plainMessage.append(QString("Output").toUtf8()+ QByteArray("\0", 1));

    messageHash = hash->generateHash(plainMessage);

    qToBigEndian((qint32) messageHash.size(), rawSize);

    message = QByteArray((char*) rawSize, 4) + plainMessage + messageHash;

    try {
        message = sym->encrypt(message);
    } catch (...) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to encrypt");
        return -1;
    }

    qToBigEndian((qint32) message.size(), rawSize);
    LOG_ENTRY(MyLogger::INFO, message.size());
    message = QByteArray((char*) rawSize, 4) + message;

    socket.write(message);
    if (!socket.waitForBytesWritten()) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to send data");
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "LOGS_PORTION sent");

    if (socket.bytesAvailable() == 0 && !socket.waitForReadyRead()) {
        LOG_ENTRY(MyLogger::ERROR, "No data received");
        return -1;
    }

    ////////////////////
    // Receive ACK
    ///////////////////
    message = socket.readAll();

    size = qFromBigEndian<qint32>((const uchar*) message.data());
    LOG_ENTRY(MyLogger::INFO, "Message received. Size: "<<size);
    message = message.mid(4);

    //check the hash
    plainMessage = sym->decrypt(message);
    size = qFromBigEndian<qint32>((const uchar*) plainMessage.data());
    messageHash = plainMessage.right(size);
    plainMessage = plainMessage.mid(4, plainMessage.size() - 4 - size);

    if (!hash->verifyHash(plainMessage, messageHash)) {
        LOG_ENTRY(MyLogger::ERROR, "Wrong hash given");
        return -1;
    }

    if (MessageCodes::getMessageType(plainMessage) != MessageCodes::ACK) {
        LOG_ENTRY(MyLogger::ERROR,
                "Received wrong message: "<<MessageCodes::getMessageType(plainMessage)<<" size: "<<plainMessage.size());
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "Received ACK");

    ////////////////////
    // send END
    ///////////////////

    plainMessage = MessageCodes::getMessageCode(MessageCodes::END);

    messageHash = hash->generateHash(plainMessage);

    qToBigEndian((qint32) messageHash.size(), rawSize);

    message = QByteArray((char*) rawSize, 4) + plainMessage + messageHash;

    try {
        message = sym->encrypt(message);
    } catch (...) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to encrypt");
        return -1;
    }

    qToBigEndian((qint32) message.size(), rawSize);
    LOG_ENTRY(MyLogger::INFO, message.size());
    message = QByteArray((char*) rawSize, 4) + message;

    socket.write(message);
    if (!socket.waitForBytesWritten()) {
        LOG_ENTRY(MyLogger::ERROR, "Unable to send data");
        return -1;
    }
    LOG_ENTRY(MyLogger::INFO, "END sent");

    socket.close();
    return 0;
}
Exemple #21
0
void getGridPropertyForSelectedCells(Matrix& propertyFrames, const QString &serverName, quint16 serverPort,
                        const qint64& caseId, 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 += "GetGridPropertyForSelectedCells " + QString::number(caseId) + " " + 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)(2*sizeof(quint64)))
    {
        if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    // Read timestep count and blocksize

    quint64 timestepCount;
    quint64 byteCount;
    size_t  selectedCellCount;

    socketStream >> timestepCount;
    socketStream >> byteCount;

    selectedCellCount = byteCount / sizeof(double);
    propertyFrames.resize(selectedCellCount, timestepCount);

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

    quint64 totalByteCount = byteCount * timestepCount;

    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("riGetGridPropertyForSelectedCells : 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() << " Selected cells cells : " << selectedCellCount << ", Time steps : " << timestepCount << std::endl;

    return;
}
void getMainGridDimensions(int32NDArray& gridDimensions, const QString &hostName, quint16 port, QString caseName)
{
    QString serverName = hostName;
    quint16 serverPort = port;

    const int Timeout = 5 * 1000;

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

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

    // Create command and send it:

    QString command("GetMainGridDimensions ");
    command += caseName;
    QByteArray cmdBytes = command.toLatin1();

    QDataStream socketStream(&socket);
    socketStream.setVersion(QDataStream::Qt_4_0);

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

    // Get response. First wait for the header

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

    // Read timestep count and blocksize

    quint64 iCount;
    quint64 jCount;
    quint64 kCount;

    socketStream >> iCount;
    socketStream >> jCount;
    socketStream >> kCount;

    dim_vector dv (1, 1);
    dv(0) = 3;

    gridDimensions.resize(dv);
    gridDimensions(0) = iCount;
    gridDimensions(1) = jCount;
    gridDimensions(2) = kCount;


    QString tmp = QString("riGetMainGridDimensions : Read main grid dimensions");
    if (caseName.isEmpty())
    {
        tmp += QString(" from active case.");
    }
    else
    {
        tmp += QString(" from %1.").arg(caseName);
    }
    octave_stdout << tmp.toStdString() << " Dimensions: " << iCount << ", " << jCount << ", " << kCount << std::endl;

    return;
}
Exemple #23
0
void getPropertyNames(std::vector<QString>& propNames, std::vector<QString>& propTypes, const QString &hostName, quint16 port, 
                        const qint64& caseId, QString porosityModel)
{
    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("GetPropertyNames") + " " + QString::number(caseId) + " " + 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)(sizeof(quint64)))
    {
        if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    quint64 byteCount;
    socketStream >> byteCount;
    QString byteCountString = QString::number(byteCount);

    //error(byteCountString.toLatin1().data());

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

    quint64 propCount;
    socketStream >> propCount;

    QString propName;
    QString propType;

    for (size_t i = 0; i < propCount; i++)
    {
        socketStream >> propName;
        socketStream >> propType;

        propNames.push_back(propName);
        propTypes.push_back(propType);
    }

    return;
}
Exemple #24
0
    /*------------------------------------------------------------------------------*

     *------------------------------------------------------------------------------*/
    void WebProxy::processQuery() {
        QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
        QByteArray requestData = socket->readAll();

        int pos = requestData.indexOf("\r\n");
        QByteArray requestLine = requestData.left(pos);
        requestData.remove(0, pos + 2);

        QList<QByteArray> entries = requestLine.split(' ');
        QByteArray method = entries.value(0);
        QByteArray address = entries.value(1);
        QByteArray version = entries.value(2);

        qDebug( )  << __FILE__ << __FUNCTION__ << "Processing " << address;

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

        //Act as server is request are for local server
        if ((url.host() == "") && (QFile(address).exists())) {
            //qDebug( )  << __FILE__ << __FUNCTION__ << "Sending " << address;
            QByteArray header;
            QTextStream headerStream(&header, QIODevice::WriteOnly);
            //Construct response header
            headerStream << "HTTP/1.0 200 OK" << endl;
            headerStream << "Server: gpsbook/" << qApp->applicationVersion() << endl;
            headerStream << "Date: " << QDateTime::currentDateTime().toUTC().toString("ddd, dd MMM yyyy hh:mm:ss") << "GMT" << endl;
            headerStream << "Content-Type: text/html; charset=utf-8" << endl;
            headerStream << "Connection: close" << endl;
            headerStream << "Pragma: no-cache" << endl;
            headerStream << "Cache-Control: no-cache" << endl;
            QFile file(address);
            if (!file.open(QFile::ReadOnly | QFile::Text))
            {
                 qWarning() << "Cannot open:" << address;
                 socket->disconnectFromHost();
                 return ;
            }

            QByteArray content;
            QTextStream contentStream(&content, QIODevice::WriteOnly);

            while (!file.atEnd()) {
                contentStream << file.readLine() << endl;
            }

            headerStream << "Content-Length:" << content.size() << endl;
            headerStream << "" << endl;

            socket->write(header);
            socket->write(content);
            //qDebug( )  << __FILE__ << __FUNCTION__ << "File sent (" << content.size() << "bytes) :-)";
            socket->disconnectFromHost();
        return;
        }


#if ( QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) )
        // Some finction of QUrl have been deprecated
        // This code is require for the internet browser and should be reviewed.
#else


#ifdef Q_OS_LINUX
        //Remove advert to speedup development ;-)
        if (url.toString().contains("googlesyndication") ||
            url.toString().contains("yieldmanager.com")) {
            socket->disconnectFromHost();
            return;
        }
#endif

        qDebug( )  << __FILE__ << __FUNCTION__ << "URL: " << url.toString();

        QString host = url.host();
        int port = (url.port() < 0) ? 80 : url.port();
        QByteArray req = url.encodedPath();
        if (url.hasQuery())
            req.append('?').append(url.encodedQuery());
        requestLine = method + " " + req + " " + version + "\r\n";
        requestData.prepend(requestLine);

        QString key = host + ':' + QString::number(port);
        QTcpSocket *proxySocket = socket->findChild<QTcpSocket*>(key);
        if (proxySocket) {
            proxySocket->setObjectName(key);
            proxySocket->setProperty("url", url);
            proxySocket->setProperty("requestData", requestData);
            proxySocket->write(requestData);
        } else {
            proxySocket = new QTcpSocket(socket);
            proxySocket->setObjectName(key);
            proxySocket->setProperty("url", url);
            proxySocket->setProperty("requestData", requestData);
            connect(proxySocket, SIGNAL(connected()), this, SLOT(sendRequest()));
            connect(proxySocket, SIGNAL(readyRead()), this, SLOT(transferData()));
            connect(proxySocket, SIGNAL(disconnected()), this, SLOT(closeConnection()));
            connect(proxySocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(closeConnection()));
            proxySocket->connectToHost(host, port);
        }
#endif
    } //WebProxy::processQuery
void getActiveCellProperty(Matrix& propertyFrames, const QString &serverName, quint16 serverPort,
                        const qint64& caseId, 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 += "GetActiveCellProperty " + QString::number(caseId) + " " + 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)(2*sizeof(quint64)))
    {
        if (!socket.waitForReadyRead(riOctavePlugin::shortTimeOutMilliSecs))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    // Read timestep count and blocksize

    quint64 timestepCount;
    quint64 byteCount;
    size_t  activeCellCount;

    socketStream >> timestepCount;
    socketStream >> byteCount;

    activeCellCount = byteCount / sizeof(double);
    propertyFrames.resize(activeCellCount, timestepCount);

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

    // Wait for available data for each timestep, then read data for each timestep

    for (size_t tIdx = 0; tIdx < timestepCount; ++tIdx)
    {
        while (socket.bytesAvailable() < (int)byteCount)
        {
            if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs))
            {
                error((("Waiting for timestep data number: ") + QString::number(tIdx)+  ": " + socket.errorString()).toLatin1().data());
                octave_stdout << "Active cells: " << activeCellCount << ", Timesteps: " << timestepCount << std::endl;
                return ;
            }
           OCTAVE_QUIT;
        }

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

#if 0
        // Raw data transfer. Faster. Not possible when dealing with coarsening
        // bytesRead = socket.read((char*)(internalMatrixData + tIdx * activeCellCount), byteCount);
#else
        // Compatible transfer. Now the only one working
        for (size_t cIdx = 0; cIdx < activeCellCount; ++cIdx)
        {
            socketStream >> internalMatrixData[tIdx * activeCellCount + cIdx];

            if (socketStream.status() == QDataStream::Ok) bytesRead += sizeof(double);
        }
#endif

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

        OCTAVE_QUIT;
    }

    QString tmp = QString("riGetActiveCellProperty : 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() << " Active cells : " << activeCellCount << ", Timesteps : " << timestepCount << std::endl;

    return;
}
void getEclipseProperty(Matrix& propertyFrames, const QString &hostName, quint16 port, QString caseName, QString propertyName)
{
    QString serverName = hostName;
    quint16 serverPort = port;

    const int Timeout = 5 * 1000;

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

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

    // Create command and send it:

    QString command("GetProperty ");
    command += caseName + " " + propertyName;
    QByteArray cmdBytes = command.toLatin1();

    QDataStream socketStream(&socket);
    socketStream.setVersion(QDataStream::Qt_4_0);

    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((("Wating for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    // Read timestep count and blocksize

    quint64 timestepCount;
    quint64 byteCount;
    size_t  activeCellCount;

    socketStream >> timestepCount;
    socketStream >> byteCount;

    activeCellCount = byteCount / sizeof(double);
    propertyFrames.resize(activeCellCount, timestepCount);

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

    // Wait for available data for each timestep, then read data for each timestep
    for (size_t tIdx = 0; tIdx < timestepCount; ++tIdx)
    {
        while (socket.bytesAvailable() < (int)byteCount)
        {
            if (!socket.waitForReadyRead(Timeout))
            {
                error((("Waiting for timestep data number: ") + QString::number(tIdx)+  ": " + socket.errorString()).toLatin1().data());
                octave_stdout << "Active cells: " << activeCellCount << ", Timesteps: " << timestepCount << std::endl;
                return ;
            }
           OCTAVE_QUIT;
        }

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

#if 1 // Use raw data transfer. Faster.
        bytesRead = socket.read((char*)(internalMatrixData + tIdx * activeCellCount), byteCount);
#else
        for (size_t cIdx = 0; cIdx < activeCellCount; ++cIdx)
        {
            socketStream >> internalMatrixData[tIdx * activeCellCount + cIdx];

            if (socketStream.status() == QDataStream::Ok) bytesRead += sizeof(double);
        }
#endif

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

        OCTAVE_QUIT;
    }

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

    if (caseName.isEmpty())
    {
        tmp += QString(" from active case.");
    }
    else
    {
        tmp += QString(" from %1.").arg(caseName);
    }
    octave_stdout << tmp.toStdString() << " Active cells : " << activeCellCount << ", Timesteps : " << timestepCount << std::endl;

    return;
}
int main(int argc, char *argv[])
{
    int debugMode = DEBUGMODE;


    if(debugMode)
    {

    } else {
        qInstallMessageHandler(myMessageOutputDisable);

    }

    QDEBUG() << "number of arguments:" << argc;
    QStringList args;
    QDEBUGVAR(RAND_MAX);
    if(argc > 1) {
        QCoreApplication a(argc, argv);
        args = a.arguments();

        QDEBUGVAR(args);

        qRegisterMetaType<Packet>();



        QDEBUG() << "Running command line mode.";

        Packet sendPacket;
        sendPacket.init();
        QString outBuilder;

        QTextStream o(&outBuilder);


        QTextStream out(stdout);

        QDate vDate = QDate::fromString(QString(__DATE__).simplified(), "MMM d yyyy");
        QCoreApplication::setApplicationName("Packet Sender");
        QCoreApplication::setApplicationVersion("version " + vDate.toString("yyyy-MM-dd"));

        QCommandLineParser parser;
        parser.setApplicationDescription("Packet Sender is a Network TCP and UDP Test Utility by Dan Nagle\nSee http://PacketSender.com/ for more information.");
        parser.addHelpOption();
        parser.addVersionOption();

        // A boolean option with a single name (-p)
        QCommandLineOption quietOption(QStringList() << "q" << "quiet", "Quiet mode. Only output received data.");
        parser.addOption(quietOption);


        QCommandLineOption hexOption(QStringList() << "x" << "hex", "Parse data as hex (default).");
        parser.addOption(hexOption);

        QCommandLineOption asciiOption(QStringList() << "a" << "ascii", "Parse data as mixed-ascii (like the GUI).");
        parser.addOption(asciiOption);

        QCommandLineOption pureAsciiOption(QStringList() << "A" << "ASCII", "Parse data as pure ascii (no \\xx translation).");
        parser.addOption(pureAsciiOption);

        // An option with a value
        QCommandLineOption waitOption(QStringList() << "w" << "wait",
                "Wait up to <milliseconds> for a response after sending. Zero means do not wait (Default).",
                "milliseconds");
        parser.addOption(waitOption);

        // An option with a value
        QCommandLineOption fileOption(QStringList() << "f" << "file",
                "Send contents of specified path. Max 1024 for UDP, 10 MiB for TCP.",
                "path");
        parser.addOption(fileOption);


        // An option with a value
        QCommandLineOption bindPortOption(QStringList() << "b" << "bind",
                "Bind port. Default is 0 (dynamic).",
                "port");
        parser.addOption(bindPortOption);


        QCommandLineOption tcpOption(QStringList() << "t" << "tcp", "Send TCP (default).");
        parser.addOption(tcpOption);

        // A boolean option with multiple names (-f, --force)
        QCommandLineOption udpOption(QStringList() << "u" << "udp", "Send UDP.");
        parser.addOption(udpOption);

        // An option with a value
        QCommandLineOption nameOption(QStringList() << "n" << "name",
                                      "Send previously saved packet named <name>. Other options overrides saved packet parameters.",
                                      "name");
        parser.addOption(nameOption);


        parser.addPositionalArgument("address", "Destination address. Optional for saved packet.");
        parser.addPositionalArgument("port", "Destination port. Optional for saved packet.");
        parser.addPositionalArgument("data", "Data to send. Optional for saved packet.");


        // Process the actual command line arguments given by the user
        parser.process(a);

        const QStringList args = parser.positionalArguments();

        bool quiet = parser.isSet(quietOption);
        bool hex = parser.isSet(hexOption);
        bool mixedascii = parser.isSet(asciiOption);
        bool ascii = parser.isSet(pureAsciiOption);
        unsigned int wait = parser.value(waitOption).toUInt();
        unsigned int bind = parser.value(bindPortOption).toUInt();
        bool tcp = parser.isSet(tcpOption);
        bool udp = parser.isSet(udpOption);
        bool ipv6  = false;

        QString name = parser.value(nameOption);

        QString filePath = parser.value(fileOption);


        QString address = "";
        unsigned int port = 0;

        int argssize = args.size();
        QString data, dataString;
        data.clear();
        dataString.clear();
        if(argssize >= 1) {
            address = args[0];
        }
        if(argssize >= 2) {
            port = args[1].toUInt();
        }
        if(argssize >= 3) {
            data = (args[2]);
        }

        //check for invalid options..

        if(argssize > 3) {
            OUTIF() << "Warning: Extra parameters detected. Try surrounding your data with quotes.";
        }

        if(hex && mixedascii) {
            OUTIF() << "Warning: both hex and pure ascii set. Defaulting to hex.";
            mixedascii = false;
        }

        if(hex && ascii) {
            OUTIF() << "Warning: both hex and pure ascii set. Defaulting to hex.";
            ascii = false;
        }

        if(mixedascii && ascii) {
            OUTIF() << "Warning: both mixed ascii and pure ascii set. Defaulting to pure ascii.";
            mixedascii = false;
        }

        if(tcp && udp) {
            OUTIF() << "Warning: both TCP and UDP set. Defaulting to TCP.";
            udp = false;
        }

        if(!filePath.isEmpty() && !QFile::exists(filePath)) {
            OUTIF() << "Error: specified path "<< filePath <<" does not exist.";
            filePath.clear();
            OUTPUT();
            return -1;
        }

        //bind is now default 0

        if(!bind && parser.isSet(bindPortOption)) {
            OUTIF() << "Warning: Binding to port zero is dynamic.";
        }


        if(!port && name.isEmpty()) {
            OUTIF() << "Warning: Sending to port zero.";
        }

        //set default choices
        if(!hex && !ascii && !mixedascii) {
            hex = true;
        }

        if(!tcp && !udp) {
            tcp = true;
        }

        //Create the packet to send.
        if(!name.isEmpty()) {
            sendPacket = Packet::fetchFromDB(name);
            if(sendPacket.name.isEmpty()) {
                OUTIF() << "Error: Saved packet \""<< name <<"\" not found.";
                OUTPUT();
                return -1;
            } else {
                if(data.isEmpty()) {
                    data  = sendPacket.hexString;
                    hex = true;
                    ascii = false;
                    mixedascii = false;
                }
                if(!port) {
                    port  = sendPacket.port;
                }
                if(address.isEmpty()) {
                    address  = sendPacket.toIP;
                }
                if(!parser.isSet(tcpOption) && !parser.isSet(udpOption)) {

                    if(sendPacket.tcpOrUdp.toUpper() == "TCP") {
                        tcp=true;
                        udp = false;
                    } else {
                        tcp=false;
                        udp = true;
                    }

                }

            }

        }

        if(!parser.isSet(bindPortOption)) {
            bind = 0;
        }

        if(!filePath.isEmpty() && QFile::exists(filePath)) {
            QFile dataFile(filePath);
            if(dataFile.open(QFile::ReadOnly)) {

                if(tcp) {
                    QByteArray dataArray = dataFile.read(1024*1024*10);;
                    dataString = Packet::byteArrayToHex(dataArray);
                } else {

                    QByteArray dataArray = dataFile.read(1024);
                    dataString = Packet::byteArrayToHex(dataArray);
                }

                //data format is raw.
                ascii = 0;
                hex = 0;
                mixedascii = 0;

            }
        }



        QDEBUGVAR(argssize);
        QDEBUGVAR(quiet);
        QDEBUGVAR(hex);
        QDEBUGVAR(mixedascii);
        QDEBUGVAR(ascii);
        QDEBUGVAR(address);
        QDEBUGVAR(port);
        QDEBUGVAR(wait);
        QDEBUGVAR(bind);
        QDEBUGVAR(tcp);
        QDEBUGVAR(udp);
        QDEBUGVAR(name);
        QDEBUGVAR(data);
        QDEBUGVAR(filePath);

        //NOW LETS DO THIS!

        if(ascii) { //pure ascii
            dataString = Packet::byteArrayToHex(data.toLatin1());
        }

        if(hex) { //hex
            dataString = Packet::byteArrayToHex(Packet::HEXtoByteArray(data));
        }
        if(mixedascii) { //mixed ascii
            dataString = Packet::ASCIITohex(data);
        }

        if(dataString.isEmpty()) {
            OUTIF() << "Warning: No data to send. Is your formatting correct?";
        }

        QHostAddress addy;
        if(!addy.setAddress(address)) {
            QHostInfo info = QHostInfo::fromName(address);
            if (info.error() != QHostInfo::NoError)
            {
                OUTIF() << "Error: Could not resolve address:" + address;
                OUTPUT();
                return -1;
            } else {
                addy = info.addresses().at(0);
                address = addy.toString();
            }
        }

        QHostAddress theAddress(address);
        if (QAbstractSocket::IPv6Protocol == theAddress.protocol())
        {
           QDEBUG() << "Valid IPv6 address.";
           ipv6 = true;
        }


        QByteArray sendData = sendPacket.HEXtoByteArray(dataString);
        QByteArray recvData;
        recvData.clear();
        int bytesWriten = 0;
        int bytesRead = 0;


        if(tcp) {
            QTcpSocket sock;


            if(ipv6) {
                sock.bind(QHostAddress::AnyIPv6, bind);
            } else {
                sock.bind(QHostAddress::AnyIPv4, bind);
            }
            sock.connectToHost(addy, port);
            sock.waitForConnected(1000);
            if(sock.state() == QAbstractSocket::ConnectedState)
            {
                OUTIF() << "TCP (" <<sock.localPort() <<")://" << address << ":" << port << " " << dataString;
                bytesWriten = sock.write(sendData);
                sock.waitForBytesWritten(1000);
                //OUTIF() << "Sent:" << Packet::byteArrayToHex(sendData);
                if(wait) {
                    sock.waitForReadyRead(wait);
                    recvData = sock.readAll();
                    bytesRead = recvData.size();
                    QString hexString = Packet::byteArrayToHex(recvData);
                    if(quiet) {
                        o << "\n" << hexString;
                    } else {
                        o << "\nResponse Time:" << QDateTime::currentDateTime().toString(DATETIMEFORMAT);
                        o << "\nResponse HEX:" << hexString;
                        o << "\nResponse ASCII:" << Packet::hexToASCII(hexString);
                    }
                }
                sock.disconnectFromHost();
                sock.waitForDisconnected(1000);
                sock.close();

                OUTPUT();
                return bytesWriten;


            } else {
                OUTIF() << "Error: Failed to connect to " << address;

                OUTPUT();
                return -1;
            }


        } else {
            QUdpSocket sock;
            if(ipv6) {
                if(!sock.bind(QHostAddress::AnyIPv6, bind)) {
                    OUTIF() << "Error: Could not bind to " << bind;

                    OUTPUT();
                    return -1;
                }

            } else {
                if(!sock.bind(QHostAddress::AnyIPv4, bind)) {
                    OUTIF() << "Error: Could not bind to " << bind;

                    OUTPUT();
                    return -1;
                }

            }
            OUTIF() << "UDP (" <<sock.localPort() <<")://" << address << ":" << port << " " << dataString;

            bytesWriten = sock.writeDatagram(sendData, addy, port);
            //OUTIF() << "Wrote " << bytesWriten << " bytes";
            sock.waitForBytesWritten(1000);

            if(wait) {
                sock.waitForReadyRead(wait);

                if(sock.hasPendingDatagrams()) {
                    QHostAddress sender;
                    quint16 senderPort;
                    recvData.resize(sock.pendingDatagramSize());

                    sock.readDatagram(recvData.data(), recvData.size(),
                                            &sender, &senderPort);

                    QString hexString = Packet::byteArrayToHex(recvData);
                    if(quiet) {
                        o << "\n" << hexString;
                    } else {
                        o << "\nResponse Time:" << QDateTime::currentDateTime().toString(DATETIMEFORMAT);
                        o << "\nResponse HEX:" << hexString;
                        o << "\nResponse ASCII:" << Packet::hexToASCII(hexString);
                    }
                }
            }

            sock.close();

            OUTPUT();
            return bytesWriten;

        }





        OUTPUT();



    } else {
        QApplication a(argc, argv);

        QDEBUGVAR(args);

        qRegisterMetaType<Packet>();

        QFile file(":/packetsender.css");
        if(file.open(QFile::ReadOnly)) {
           QString StyleSheet = QLatin1String(file.readAll());
         //  qDebug() << "stylesheet: " << StyleSheet;
           a.setStyleSheet(StyleSheet);
        }

        MainWindow w;


        w.show();

        return a.exec();

    }



    return 0;

}
void sJarvisNodeServer::connectNode(QString host, qint16 port)
{
    QTcpSocket* c = new QTcpSocket(this);
    c->connectToHost(host,port);
    validateClient(c);
}
Exemple #29
0
const QByteArray Auth::calculateAuthKey()
{
    QSqlDatabase db = QSqlDatabase::database ( m_db );

    bool ok = false;
    QSqlQuery query(db);

    ok = query.exec( QString("SELECT Value from Config where Name = 'ZM_AUTH_HASH_SECRET'") );
    if (!ok || !query.next()) {
        qDebug("Hash Error: error getting zm_auth_hash_secret from db %s", qPrintable(query.lastError().text()));
        return QByteArray();
    }

    QString auth_key = query.value(0).toString(); // HASH Secret

    ok = query.exec( QString("SELECT Value from Config where Name = 'ZM_AUTH_HASH_IPS'") );
    if (!ok || !query.next()) {
        qDebug("Hash Error: error getting zm_auth_hash_ips from db %s", qPrintable(query.lastError().text()));
        return QByteArray();
    }

    bool use_remote_addr = query.value(0).toBool(); // Include remote addr?

    ok = query.exec( QString("SELECT now()") );
    if (!ok || !query.next()) {
        qDebug("Hash Error: Can not read Server Time. now() function doesn't work %s",
               qPrintable(query.lastError().text()));
        return QByteArray();
    }

    QDateTime dateTime = query.value(0).toDateTime();

    auth_key += m_userName;
    auth_key += m_hashPassword;

    if ( use_remote_addr )
    {
        QTcpSocket socket;
        socket.connectToHost( db.hostName(), ConnectionManager::connectionWebPort( m_db ), QIODevice::ReadOnly );
        //if we can get ip address from the socket in 3000 ms
        if ( socket.waitForConnected( 3000 ) ){
            auth_key += socket.localAddress().toString();
        } else {
            //else try with HostInfo
            QHostInfo hinfo = QHostInfo::fromName ( QHostInfo::localHostName()  );
            QHostInfo checkLocalHost = QHostInfo::fromName ( db.hostName()  );
            if ( ! checkLocalHost.addresses().isEmpty() )
                if ( checkLocalHost.addresses().first().toString() == "127.0.0.1" ) hinfo = checkLocalHost;

            if ( !hinfo.addresses().isEmpty() )
            {
                //TODO: fix this. Use the correct interface address and not the first
                QHostAddress address = hinfo.addresses().first();
                auth_key += address.toString();
            }
        }
    }

    dateTime = dateTime.toTimeSpec( Qt::LocalTime );
    auth_key += QString::number( dateTime.time().hour() ); //hour
    auth_key += QString::number( dateTime.date().day() ); //day of month
    auth_key += QString::number( dateTime.date().month() -1 ); //month
    auth_key += QString::number( dateTime.date().year() - 1900 ); //years since 1900

    qDebug ( qPrintable("authkey: " + auth_key) );

    QByteArray ret = QCryptographicHash::hash( auth_key.toUtf8(), QCryptographicHash::Md5 );
    //qDebug ( qPrintable(QString (auth_key.toUtf8())) );
    qDebug ( qPrintable("authkey hex: " + ret.toHex()) );

    m_authKey = ret.toHex();
    return m_authKey;
}
Exemple #30
0
int UCHome_Main_SiteConst::login()
{
    QTcpSocket *sock = NULL;
    
    sock = new QTcpSocket();
    sock->connectToHost(this->host, this->port);
    if(!sock->waitForConnected()) {
        q_debug()<<"error:";
        return LOGIN_ERROR;
    }

    QString data ;
    data = QString("username=%1&password=%2&cookietime=315360000&refer=space.php%3Fdo%3Dhome&loginsubmit=%B5%C7%C2%BC&formhash=3040598c").arg(this->username, this->password) ;
    
    QString request;
    request = 
        QString("POST /uchome/do.php?ac=login&&ref HTTP/1.1\r\n"
                "Host: uchome.developer.manyou.com\r\n"
                "User-Agent: Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.0.4) Gecko/2008112913 Gentoo Minefield/3.0.4\r\n"
                "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
                "Accept-Language: zh-cn,zh;q=0.5\r\n"
                "Accept-Charset: gb2312,utf-8;q=0.7,*;q=0.7\r\n"
                "Keep-Alive: 300\r\n"
                "Connection: keep-alive\r\n"
                "Referer: http://uchome.developer.manyou.com/uchome/index.php\r\n"
                "Content-Type: application/x-www-form-urlencoded\r\n"
                "Content-Length: %1\r\n\r\n")
        .arg(data.length());

    ;
    request += data;
    q_debug()<<request;

    sock->write(request.toAscii());
    if(!sock->waitForBytesWritten()) {
        q_debug()<<"write error";
        return LOGIN_ERROR;
    }
    char header[8192] = {0} ;
    char b2[2] = {0};
    char *bp = &header[0];
    char *tp = bp;
    qint64 rlen = 0;
    qint64 oklen = 0;
    while(true) {
        if(!sock->waitForReadyRead()) {
            q_debug()<<"wait read error";
            return LOGIN_ERROR;
        }
        oklen = sock->bytesAvailable();
        if(oklen < 0 ) {
            q_debug()<<"wait read errorsdfjsdifsdifsdifj";
        }
        while(oklen-- > 0) {
            rlen = sock->read(b2, 1);
            *tp++ = b2[0];
            if(tp - bp > 4 && strncmp(tp-4, "\r\n\r\n", 4) == 0) {
                break;
            }
        }
        if(strncmp(tp-4, "\r\n\r\n", 4) == 0) {
            break;
        }
    }
    //parse header, got file length
    QStringList cookie_lines;
    QStringList header_lines = QString(header).split("\r\n");
    qint64 content_length = -1;
    for(int i = 0; i < header_lines.count(); i ++) {
        if(header_lines.at(i).startsWith("Content-length")) {
            content_length = header_lines.at(i).split(":").at(1).trimmed().toLongLong();
        }
        if(header_lines.at(i).startsWith("Set-Cookie:")
           && header_lines.at(i).indexOf("=deleted") == -1) {
            cookie_lines<<header_lines.at(i);
        }
    }
    q_debug()<<"Got Content-length:"<<content_length<<"\n"<<header
             <<cookie_lines;
    if(cookie_lines.count() == 0) {
        q_debug()<<"No login ok cookie found";
        return LOGIN_ERROR;
    }
    int has_uchome_auth = 0;
    int has_uchome_loginuser = 0;
    for(int i = 0 ; i < cookie_lines.count(); i ++) {
        if(cookie_lines.at(i).indexOf("uchome_auth=") != -1) {
            has_uchome_auth = 1;
        }
        if(cookie_lines.at(i).indexOf("uchome_loginuser="******"may be login faild";
        return LOGIN_ERROR;
    }
    this->combine_cookies(cookie_lines);
    return LOGIN_OK;

    //no use code
    if(content_length == -1) {
        q_debug()<<"No content-length field";
        //return -1;
    }
    
    QString html ;

    while(true) {
        if(!sock->waitForReadyRead()) {
            q_debug()<<"wait read error";
            return -1;
        }
        oklen = sock->bytesAvailable();
        if(oklen > 0) {
            html += sock->readAll();
        }else{
            break;
        }
    }

    q_debug()<<"Got conent size:"<<html.length()
             <<"\n"<<html;

    return 0;    
}