Exemple #1
1
void QXmppSocksServer::slotReadyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    if (!socket || !m_states.contains(socket))
        return;

    if (m_states.value(socket) == ConnectState)
    {
        m_states.insert(socket, CommandState);

        // receive connect to server request
        QByteArray buffer = socket->readAll();
        if (buffer.size() < 3 ||
            buffer.at(0) != SocksVersion ||
            buffer.at(1) + 2 != buffer.size())
        {
            qWarning("QXmppSocksServer received invalid handshake");
            socket->close();
            return;
        }

        // check authentication method
        bool foundMethod = false;
        for (int i = 2; i < buffer.size(); i++)
        {
            if (buffer.at(i) == NoAuthentication)
            {
                foundMethod = true;
                break;
            }
        }
        if (!foundMethod)
        {
            qWarning("QXmppSocksServer received bad authentication method");
            socket->close();
            return;
        }

        // send connect to server response
        buffer.resize(2);
        buffer[0] = SocksVersion;
        buffer[1] = NoAuthentication;
        socket->write(buffer);

    } else if (m_states.value(socket) == CommandState) {
        m_states.insert(socket, ReadyState);

        // disconnect from signals
        disconnect(socket, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));

        // receive command
        QByteArray buffer = socket->readAll();
        if (buffer.size() < 4 ||
            buffer.at(0) != SocksVersion ||
            buffer.at(1) != ConnectCommand ||
            buffer.at(2) != 0x00)
        {
            qWarning("QXmppSocksServer received an invalid command");
            socket->close();
            return;
        }

        // parse host
        quint8 hostType;
        QByteArray hostName;
        quint16 hostPort;
        if (!parseHostAndPort(buffer.mid(3), hostType, hostName, hostPort))
        {
            qWarning("QXmppSocksServer could not parse type/host/port");
            socket->close();
            return;
        }

        // notify of connection
        emit newConnection(socket, hostName, hostPort);

        // send response
        buffer.resize(3);
        buffer[0] = SocksVersion;
        buffer[1] = Succeeded;
        buffer[2] = 0x00;
        buffer.append(encodeHostAndPort(
            DomainName,
            hostName,
            hostPort));
        socket->write(buffer);
    }
}
Exemple #2
0
    /*------------------------------------------------------------------------------*

     *------------------------------------------------------------------------------*/
    void WebProxy::transferData() {
        QTcpSocket *proxySocket = qobject_cast<QTcpSocket*>(sender());
        QTcpSocket *socket = qobject_cast<QTcpSocket*>(proxySocket->parent());
        socket->write(proxySocket->readAll());
    } //WebProxy::transferData
Exemple #3
0
    /*------------------------------------------------------------------------------*

     *------------------------------------------------------------------------------*/
    void WebProxy::sendRequest() {
        QTcpSocket *proxySocket = qobject_cast<QTcpSocket*>(sender());
        QByteArray requestData = proxySocket->property("requestData").toByteArray();
        proxySocket->write(requestData);
    } //WebProxy::sendRequest
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 #5
0
void MyHttpServer::slotNewConnectionHandler()
{
    qDebug() << " [ ]Have a new connection!";
    QTcpSocket* sock = m_pServer.nextPendingConnection();
    sock->waitForReadyRead();
    QByteArray request(sock->readAll());
    qDebug() << request;
    QStringList buf = QString(request).split(' ');

    if(buf.at(0) == "GET")
    {
        QString responce = "HTTP/1.1 200 OK\r\n\r\n%1";
        sock->write(responce.arg(QTime::currentTime().toString()).toLatin1());
        sock->waitForBytesWritten();
        sock->disconnectFromHost();
        sock->deleteLater();
        return;
    }

    if(buf.at(0) == "POST")
    {
	QString destUrl(buf.at(1));
        sock->waitForReadyRead();
        QByteArray data(sock->readAll());
        qDebug() << "put " << QString(data) << " into " << destUrl;
        QString responce = "HTTP/1.1 200 OK\r\n\r\n";
        sock->write(responce.toLatin1());
        sock->waitForBytesWritten();
        sock->disconnectFromHost();
        sock->deleteLater();

        //QByteArray payload;
        //payload.append(QString(data).split('=').at(1));
        //payload = QByteArray::fromBase64(QByteArray::fromPercentEncoding(payload));
        //qDebug() << payload;

        //QJsonDocument doc = QJsonDocument::fromJson(payload);
        //QJsonObject jObj = doc.object();
        //QString table = destUrl.split('/').at(2);
        //qDebug() << "table: " << table << " object: " << jObj;


        return;
    }

//    connect(sock, SIGNAL(readyRead()), this, SLOT(slotReadDataHandler()));
//    connect(sock, SIGNAL(disconnected()), this, SLOT(slotDisconnectedHandler()));
}
void PanoServerTCP::IncomingData() {
  QTcpSocket* conn = (QTcpSocket*) sender();
  vector<TcpConnection>::iterator host = std::find(connections_.begin(),
                                                   connections_.end(),
                                                   TcpConnection(conn));
  
  if (host == connections_.end()) {
    log("Client to registered at TCP server.");
    return;
  }
  
  if (conn->bytesAvailable() <= 0) {
    log("Error on incoming data. Packet is empty!");
    return;
  }
  
  QByteArray data = conn->readAll();
  int data_pos = 0;
  
  // Multiple packages possible.
  while (data_pos < data.length()) {
    // Continue package?
    if (host->pkg.length()) {
      int remaining_data_bytes = data.length() - data_pos;
      int remaining_bytes = host->target_sz - host->pkg.length();
      
      if (remaining_data_bytes <= remaining_bytes) {
        host->pkg.append(data.mid(data_pos, remaining_data_bytes));
        data_pos += remaining_data_bytes;
      } else {
        // Another package is waiting.
        host->pkg.append(data.mid(data_pos, remaining_bytes));
        data_pos += remaining_bytes;
      }
      
    } else {
      // New package.
      QDataStream data_stream(data.mid(data_pos));
      data_stream.setByteOrder(QDataStream::LittleEndian);
      int msg_id;
      int length;
      
      data_stream >> msg_id;
      data_stream >> length;
      
      data_pos += sizeof(int) * 2;
      int remaining_data_bytes = data.length() - data_pos;
      
      switch (msg_id) {
        case 0x13030002: 
        {
          log("New image uploaded");          
          // Most likely more packages are incoming ...
          host->target_sz = length;
          host->msg_id = msg_id;
          
          if (length > remaining_data_bytes) {
            host->pkg.append(data.mid(data_pos, remaining_data_bytes));
            data_pos += remaining_data_bytes;
          } else {
            host->pkg.append(data.mid(data_pos, length));
            data_pos += length;
          }
          break;
        }
        case 0x13030005:
        {
          // Image lock request.
          QDataStream img_id_stream(data.mid(data_pos));
          img_id_stream.setByteOrder(QDataStream::LittleEndian);
          int img_id;
          img_id_stream >> img_id;
          data_pos += sizeof(int);
          
          if (view_->aquireLock(img_id, conn)) {
            // Notify all clients.
            SendLockToClients(img_id);
          } else {
            log("Failed lock request from client. Lock already aquired.");
          }
          
          break;
        }
        case 0x13030006:
        {
          // Image release request.
          QDataStream img_id_stream(data.mid(data_pos));
          img_id_stream.setByteOrder(QDataStream::LittleEndian);
          int img_id;
          img_id_stream >> img_id;
          data_pos += sizeof(int);
          
          if (view_->releaseLock(img_id, conn)) {
            // Notify all clients.
            SendReleaseToClients(img_id);
          } else {
            log("Failed release request. Inconsistency error occured.\n");
          }
          
          break;
        }
        default:
          log("Unknown package incoming!");
          break;
      }
    }
      
    // Read completely?
    if (host->pkg.length() == host->target_sz) {
      switch(host->msg_id) {
        case 0x13030002:
        {
          // Get initial transformation.
          QDataStream pkg_stream(host->pkg);
          pkg_stream.setByteOrder(QDataStream::LittleEndian);
          float scale, rotation, trans_x, trans_y;
          pkg_stream >> scale >> rotation >> trans_x >> trans_y;
          
          QByteArray img_data = host->pkg.mid(sizeof(float) * 4);
          QImage img = QImage::fromData(img_data, "png");
          int img_id = view_->AddImage(img);
          log(QString("Assigned id ") + QString::number(img_id) + " to image. Sending ACK.");
          view_->updateImgPosition(img_id, scale, rotation, trans_x, trans_y);
          
          // Send img_id back.
          QByteArray img_id_package;
          int img_id_sz = sizeof(int);
          QDataStream img_id_stream(&img_id_package, QIODevice::WriteOnly);
          img_id_stream.setByteOrder(QDataStream::LittleEndian);
          img_id_stream << 0x13030003 << img_id_sz << img_id;
          Write(img_id_package, conn, 0);
          
          // Send to remaining cients.
          QByteArray to_send;
          QDataStream send_stream(&to_send, QIODevice::WriteOnly);
          send_stream.setByteOrder(QDataStream::LittleEndian);
          
          int preload_sz = sizeof(float) * 4 + sizeof(int);
          int total_sz = preload_sz + img_data.size();
          send_stream << host->msg_id << total_sz
                      << img_id << scale << rotation << trans_x << trans_y;
          
          to_send.append(img_data);
          
          Write(to_send, 0, conn);
          break;
        }
        default:
          break;
      }
      host->pkg.clear();
    }
  }
}
Exemple #7
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;
}
void HttpProxy::onProxySocketReadyRead()
{
    QTcpSocket *proxySocket = qobject_cast<QTcpSocket *>(sender());
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(proxySocket->parent());
    socket->write(proxySocket->readAll());
}
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 error("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 HttpProxy::onProxySocketConnected()
{
    QTcpSocket *proxySocket = qobject_cast<QTcpSocket *>(sender());
    QByteArray reqData = proxySocket->property("reqData").toByteArray();
    proxySocket->write(reqData);
}
void ServerPanelRpcServer::DiscardClient() {
    // Open the socket
    QTcpSocket* cSocket = (QTcpSocket*) sender();
    // Schedule the socket for deletion
    cSocket->deleteLater();
}
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;
}
Exemple #13
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
Exemple #14
0
void MessageWidget::newConnection()
{
    QTcpSocket *socket = this->tcpServer.nextPendingConnection();
    if (socket->waitForReadyRead(2000))
    {
        QString output= QString::fromUtf8(socket->readAll());


        if (output.contains(QRegExp("^SMS_RECEIVED:")))
        {//"SMS_RECEIVED:number:body
            output.remove(QRegExp("^SMS_RECEIVED:"));

            int i;
            QString number,body;

            i = output.indexOf(":");
            number = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            body = output;

            emit this->smsReceived(this->contactModel.getName(number),body);
        }
        else if (output.contains(QRegExp("^GET_SMS_LIST:")))
        {//"GET_SMS_LIST:threadId:messageId:timestamp:number:read:toa:body
            output.remove(QRegExp("^GET_SMS_LIST:"));
            int i;
            QString threadId,messageId,timestamp,number,read,toa,body;

            i = output.indexOf(":");
            threadId = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            messageId = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            timestamp = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            number = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            read = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            toa = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            body = output;

            addSMS(threadId,messageId,timestamp,number,read,toa,body);
        }
        else if (output.contains(QRegExp("^GET_CONTACT_LIST:")))
        {
            output.remove(QRegExp("^GET_CONTACT_LIST:"));
            QString id,number,name;
            int i;

            i = output.indexOf(":");
            id = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            name = output.left(i);
            output.remove(0,i+1);

            i = output.indexOf(":");
            number = output;
            number.remove("\n");

            addContact(id,number,name);
        }

        socket->disconnectFromHost();
    }
    delete socket;
}
Exemple #15
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 #16
0
void Tunneld::promiseChannelCleanup(ToxTunChannel *chan)
{
    qDebug()<<chan<<sender();
    QObject *snderobj = (QObject*)sender();
    QTimer *repeat_timer = NULL;

    qDebug()<<snderobj->objectName()<<snderobj->metaObject()->className();
    if (chan == NULL) {
        repeat_timer = (QTimer*)snderobj;
        assert(repeat_timer != NULL);
        int conid = repeat_timer->property("conid").toInt();
        if (!m_conid_chans.contains(conid)) {
            qDebug()<<"maybe too late repeat check self sock close timer event";
            repeat_timer->deleteLater();
            return;
        }
        chan = m_conid_chans[conid];
        assert(chan != NULL);
    } else {
        // snderobj is ENetPoll or QTcpSocket
    }
    QTcpSocket *sock = chan->m_sock;
    ENetPeer *enpeer = chan->m_enpeer;

    //////////
    QHash<QString, bool> promise_results;

    promise_results["sock_closed"] = chan->sock_closed;
    // promise_results["enet_closed"] = chan->enet_closed;
    promise_results["peer_sock_closed"] = chan->peer_sock_closed;

    bool promise_result = true;
    for (auto it = promise_results.begin(); it != promise_results.end(); it ++) {
        QString key = it.key();
        bool val = it.value();
        promise_result = promise_result && val;
    }

    if (true) {
        // 检测对方最近的回包情况
        if (!promise_result && repeat_timer == NULL
            && promise_results["peer_sock_closed"] && !promise_results["sock_closed"]) {
            qDebug()<<"here";
            if (chan->last_recv_peer_pkt_time == QDateTime()) {
                qDebug()<<"maybe can close socket right now, because recv nothing forever";
            }
            
            QTimer *t = new QTimer();
            t->setInterval(500);
            t->setSingleShot(true);
            t->setProperty("conid", QVariant(chan->m_conid));
            // // QObject::connect(t, &QTimer::timeout, this, &Tunneld::promiseChannelCleanup, Qt::QueuedConnection);
            QObject::connect(t, SIGNAL(timeout()), this, SLOT(promiseChannelCleanup()), Qt::QueuedConnection);
            qDebug()<<"start repeat check sock close timer:";
            t->start();
        }
        if (!promise_result && repeat_timer != NULL
            && promise_results["peer_sock_closed"] && !promise_results["sock_closed"]) {
            //
            QDateTime now_time = QDateTime::currentDateTime();
            uint32_t last_recv_to_now_time = chan->last_recv_peer_pkt_time.msecsTo(now_time);
            qDebug()<<"here:"<<last_recv_to_now_time<<enpeer->lastReceiveTime;
            if (last_recv_to_now_time > 7000) {
                qDebug()<<"last recv to now, force close self socket:"<<last_recv_to_now_time
                        <<enpeer->incomingPeerID<<enpeer->outgoingPeerID;
                // 不能直接关闭,要在当前函数执行完后,即下一次事件的时候开始执行。
                QTimer::singleShot(1, sock, &QTcpSocket::close);
                // QTimer *t = new QTimer();
                // t->setSingleShot(true);
                // QObject::connect(t, &QTimer::timeout, sock, &QTcpSocket::close, Qt::QueuedConnection);
                // t->start(1);
                
                repeat_timer->deleteLater();
            } else {
                repeat_timer->start();
            }
        }
    }
    
    if (!promise_result) {
        qDebug()<<"promise nooooot satisfied:"<<promise_results<<chan->m_conid;
        return;
    }
    
    chan->promise_close_time = QDateTime::currentDateTime();
    qDebug()<<"promise satisfied."<<chan->m_conid;

    ///// do cleanup
    bool force_closed = chan->force_closed;
    
    // enpeer->toxchan = NULL;  // cleanup
    peerRemoveChan(enpeer, chan);
    
    this->m_sock_chans.remove(sock);
    // this->m_enpeer_chans.remove(enpeer);
    this->m_conid_chans.remove(chan->m_conid);

    delete chan;
    sock->disconnect();
    sock->deleteLater();
    if (repeat_timer != NULL) repeat_timer->deleteLater();
    qDebug()<<"curr chan size:"<<this->m_sock_chans.count()<<this->m_conid_chans.count();

    if (force_closed) {
        return;
    }

    // 延时关闭enet_peer
    QTimer *t = new QTimer();
    auto later_close_timeout = [enpeer, t]() {
        qDebug()<<enpeer<<enpeer->state;
        if (enpeer->state != ENET_PEER_STATE_CONNECTED) {
            qDebug()<<"warning, peer currently not connected:"<<enpeer->incomingPeerID;
        }

        if (! (enet_list_empty (& enpeer -> outgoingReliableCommands) &&
               enet_list_empty (& enpeer -> outgoingUnreliableCommands) && 
               enet_list_empty (& enpeer -> sentReliableCommands))) {
            qDebug()<<"warning, maybe has unsent packet:"<<enpeer->incomingPeerID;
        }

        qDebug()<<"last recv time:"<<enpeer->incomingPeerID
        <<enetx_time_diff(enpeer->lastReceiveTime, enet_time_get());

        qDebug()<<"restore peer timeout, ping interval";
        enet_peer_timeout(enpeer, ENET_PEER_TIMEOUT_LIMIT*2,
                          ENET_PEER_TIMEOUT_MINIMUM*2, ENET_PEER_TIMEOUT_MAXIMUM*2);
        enet_peer_ping_interval(enpeer, ENET_PEER_PING_INTERVAL*2);

        // enet_peer_disconnect_now(enpeer, qrand());
        enet_peer_disconnect_later(enpeer, qrand());
        t->deleteLater();
    };

    qDebug()<<"last recv time:"<<enpeer->incomingPeerID
            <<enetx_time_diff(enpeer->lastReceiveTime, enet_time_get());
    // QTimer::singleShot(5678, later_close_timeout);
    t->setInterval(5678);
    t->setSingleShot(true);
    QObject::connect(t, &QTimer::timeout, later_close_timeout);
    t->start();
}
Exemple #17
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 #18
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 #19
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();
}
Exemple #20
0
bool ZHttpServer::startServer(quint16 port)
{
    if(m_tcpServer->isListening())
        return true;

    if(!m_tcpServer->listen(QHostAddress::Any, port)){
        qWarning() << "HttpServer: error: " << m_tcpServer->errorString();
        return false;
    }else{
        qWarning() << "HttpServer: OK";
    }
    connect(m_tcpServer, &QTcpServer::newConnection, [this]{
        QTcpSocket *socket = m_tcpServer->nextPendingConnection();
        qWarning() << "HttpServer: new connect:" << socket->peerAddress().toString() << socket->peerName() << socket->peerPort();

        connect(socket, &QTcpSocket::readyRead, [socket, this]{
            HttpInfo info(socket->readAll());

            qWarning() << info.url();

            const QByteArray &query = info.url().query().toUtf8();
            QMap<QByteArray, QByteArray> command_map;

            QFileInfo fileInfo(sysroot + info.url().path());

            if (fileInfo.isFile() && fileInfo.isExecutable()) {
                execProcess((fileInfo.fileName() + " " + info.url().query(QUrl::FullyDecoded)).toLatin1(), socket);

                return;
            }

            if(!query.isEmpty()) {
                QByteArrayList commands = query.split('&');

                qWarning() << "HttpServer: command:" << commands;

                for(const QByteArray &comm : commands) {
                    if(comm.isEmpty())
                        continue;

                    const QByteArrayList &tmp_list = comm.split('=');

                    if(tmp_list.count() != 2 || tmp_list.first().isEmpty()) {
                        socket->write(messagePackage("", "text/Html", HttpInfo::BadRequest, QString("Grammatical errors: \"%1\"").arg(QString(comm))));
                        socket->close();
                        return;
                    }

                    command_map[tmp_list.first()] = tmp_list.last();
                }
            }

            if(command_map.value(ACTION) == ACTION_EXEC) {
                execProcess(QUrl::fromPercentEncoding(command_map.value(COMMAND)), socket);
            } else {
                QPointer<QTcpSocket> socket_pointer = socket;

                readFile(info.url(), socket);

                if (socket_pointer)
                    socket->close();
            }
        });
        connect(socket, &QTcpSocket::disconnected, [socket]{
            qWarning() << "HttpServer: disconnected: " << socket->peerAddress().toString() << socket->peerName() << socket->peerPort();
            socket->deleteLater();
        });
    });

    return true;
}
Exemple #21
0
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;

    const int timeout = riOctavePlugin::timeOutMilliSecs;

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

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

    // Create command and send it:

    QString command = QString("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(timeout))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    quint64 byteCount;
    socketStream >> byteCount;

    while (socket.bytesAvailable() < (int)(byteCount))
    {
        if (!socket.waitForReadyRead(timeout))
        {
            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 #22
0
void Widget::tcpProcessPendingDatagrams()
{
    // Find who's sending
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (socket == 0)
        return;

    unsigned nTries = 0;

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

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

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

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

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

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

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

            *tcpReceivedDatas = tcpReceivedDatas->mid(data.size());
        }
    }
}
Exemple #23
0
void Widget::tcpProcessPendingDatagrams()
{
    // Find who's sending
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (socket == nullptr)
        return;

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

    unsigned nTries = 0;

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

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

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

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

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

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

            *recvBuffer = recvBuffer->mid(dataSize);
        }
    }
}
Exemple #24
0
void GroupRequestDlg::slotOkClicked()
{
    if (ui_->rb_allow_->isChecked())
    {
        QString allow_url = "/channel/op_group_join_req?group_uin=" + gid_ + "&req_uin=" + id_ +
                "&msg=&op_type=2&clientid=5412354841&psessionid=" + CaptchaInfo::instance()->psessionid() +"&t=" + QString::number(QDateTime::currentMSecsSinceEpoch());

        Request req;
        req.create(kGet, allow_url);
        req.addHeaderItem("Host", "d.web2.qq.com");
        req.addHeaderItem("Cookie", CaptchaInfo::instance()->cookie());
        req.addHeaderItem("Referer", "http://d.web2.qq.com/proxy.html?v=20110331002&callback=2");
        req.addHeaderItem("Content-Type", "utf-8");

        QTcpSocket fd;
        fd.connectToHost("d.web2.qq.com", 80);
        fd.write(req.toByteArray());

        fd.waitForReadyRead();
        qDebug()<<"allow add group request: "<<fd.readAll();

        accept();
    }
    else
    {
        QString deny_url = "/channel/op_group_join_req?group_uin=" + gid_ + "&req_uin=" + id_ +
                "&msg=" + ui_->le_deny_reason_->text() + "&op_type=3&clientid=5412354841&psessionid=" + CaptchaInfo::instance()->psessionid() +"&t=" + QString::number(QDateTime::currentMSecsSinceEpoch());

        Request req;
        req.create(kGet, deny_url);
        req.addHeaderItem("Host", "d.web2.qq.com");
        req.addHeaderItem("Cookie", CaptchaInfo::instance()->cookie());
        req.addHeaderItem("Referer", "http://d.web2.qq.com/proxy.html?v=20110331002&callback=2");
        req.addHeaderItem("Content-Type", "utf-8");

        QTcpSocket fd;
        fd.connectToHost("d.web2.qq.com", 80);
        fd.write(req.toByteArray());

        fd.waitForReadyRead();
        qDebug()<<"deny add group request"<<fd.readAll();

        fd.close();
        reject();
    }
}
void sJarvisNodeServer::connectNode(QString host, qint16 port)
{
    QTcpSocket* c = new QTcpSocket(this);
    c->connectToHost(host,port);
    validateClient(c);
}
void dtkComposerNodeCommunicatorReceive::run(void)
{

    if (!d->receiver_source.isEmpty()) {


        if (d->receiver_comm.isEmpty() && d->receiver_socket.isEmpty()) {
            dtkError() << "Send node at either a socket or a communicator.";
            return;
        }

        d->source = d->receiver_source.data();

        d->tag = 0;
        if (!d->receiver_tag.isEmpty())
            d->tag = d->receiver_tag.data();

        d->emitter.clearData();
        if (!d->receiver_data.isEmpty()) {
            d->emitter.setData(d->receiver_data.variant());
        }

        if (d->receiver_comm.isEmpty()) {
            QTcpSocket *socket = d->receiver_socket.constData();
            dtkDebug() << "TCP communicator. Parse message from socket, waiting for tag" << d->tag;
            if (d->msg_map.contains(d->tag)) {
                dtkDebug() << "msg already received for tag" << d->tag;
                // d->emitter.setTwinned(false);
                dtkDistributedMessage *msg = d->msg_map.take(d->tag);
                d->emitter.setData(msg->content());
                // d->emitter.setTwinned(true);
                delete msg;
                return;
            } else {
                dtkTrace() << "msg not yet received, wait for data";
            }

            socket->blockSignals(true); // needed ?

            if (!socket->waitForReadyRead(300000)) {
                dtkWarn() << "Data not ready in receive for rank " << d->source;
            } else {
                dtkDistributedMessage msg;
                msg.parse(socket);
                qlonglong msg_tag = msg.header("Tag").toLongLong();
                if (msg_tag == d->tag || d->tag == dtkDistributedCommunicator::ANY_TAG) {
                    dtkTrace() << "OK, this is the expected tag " << d->tag;
                    // d->emitter.setTwinned(false);
                    d->emitter.setData(msg.content());
                    // d->emitter.setTwinned(true);
                    if (d->tag == dtkDistributedCommunicator::ANY_TAG)
                        d->tag = msg_tag;
                } else {
                    //store msg for another call with the right tag
                    dtkInfo() << "Msg received, but wrong tag, store the msg" << d->tag << msg_tag;
                    d->msg_map.insert(msg_tag, &msg);
                    this->run(); // do it again
                }
            }
            socket->blockSignals(false); // needed ?
        } else { // MPI
            QByteArray array;
            dtkDistributedCommunicatorStatus status;
            dtkDistributedCommunicator *communicator = d->receiver_comm.constData();
            //FIXME:[migration] new transmitter requieres a clone method in object, even if dataTransmission is set to reference
            communicator->receive(array, d->source, d->tag, status);

            if (d->tag == dtkDistributedCommunicator::ANY_TAG)
                d->tag = status.tag();
            if (d->source == dtkDistributedCommunicator::ANY_SOURCE)
                d->source = status.source();

            if (!array.isEmpty()) {
                // d->emitter.setTwinned(false);
                d->emitter.setData(array);
                // d->emitter.setTwinned(true);
            } else {
                dtkWarn() << "Empty data in receive";
                d->emitter.clearData();
            }
        }
    } else {
        d->emitter.clearData();
        dtkWarn() << "Inputs not specified in receive. Nothing is done";
        d->tag = 0;
        d->source = 0;
    }

    d->emitter_source.setData(d->source);
    d->emitter_tag.setData(d->tag);

}
/**
 * readClient: signal handler for RAOP client connection
 * Handle initialisation of session
 */
void MythRAOPConnection::readClient(void)
{
    QTcpSocket *socket = (QTcpSocket *)sender();
    if (!socket)
        return;

    QByteArray data = socket->readAll();
    LOG(VB_GENERAL, LOG_DEBUG, LOC + QString("readClient(%1): ")
        .arg(data.size()) + data.constData());

    // For big content, we may be called several times for a single packet
    if (!m_incomingPartial)
    {
        m_incomingHeaders.clear();
        m_incomingContent.clear();
        m_incomingSize = 0;

        QTextStream stream(data);
        QString line;
        do
        {
            line = stream.readLine();
            if (line.size() == 0)
                break;
            LOG(VB_GENERAL, LOG_DEBUG, LOC + QString("Header = %1").arg(line));
            m_incomingHeaders.append(line);
            if (line.contains("Content-Length:"))
            {
                m_incomingSize = line.mid(line.indexOf(" ") + 1).toInt();
            }
        }
        while (!line.isNull());

        if (m_incomingHeaders.size() == 0)
            return;

        if (!stream.atEnd())
        {
            int pos = stream.pos();
            if (pos > 0)
            {
                m_incomingContent.append(data.mid(pos));
            }
        }
    }
    else
    {
        m_incomingContent.append(data);
    }

    // If we haven't received all the content yet, wait (see when receiving
    // coverart
    if (m_incomingContent.size() < m_incomingSize)
    {
        m_incomingPartial = true;
        return;
    }
    else
    {
        m_incomingPartial = false;
    }
    LOG(VB_GENERAL, LOG_DEBUG, LOC + QString("Content(%1) = %2")
        .arg(m_incomingContent.size()).arg(m_incomingContent.constData()));

    ProcessRequest(m_incomingHeaders, m_incomingContent);
}
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;
}
QAbstractSocket* TcpSocketCreation::operator()() const {
	QTcpSocket* socket = new QTcpSocket();
	socket->setSocketDescriptor(socketDescriptor);
	return socket;
}
Exemple #30
-1
  void Server::acceptUser() {
    //to be called every time a new connection is received
    QTcpSocket *socket = m_tcp_server->nextPendingConnection();
    debugInfo("New incoming connection, from IP " +
	      socket->peerAddress().toString() +
	      " and port: " + QString::number(socket->peerPort()));
    //check if ip is registered
    if (!isThisIpRegistered(socket->peerAddress().toString())) {
      //then parse user
      UE new_ue;
      new_ue.name = "";
      new_ue.ip = socket->peerAddress().toString();
      //will change when ue_name() is sent
      new_ue.rx_port = 0;
      m_online_users.append(new_ue);
      debugInfo("New empty UE registered!");
    } else {
      debugInfo("user is transmitting either its name or data");
      socket->waitForReadyRead(1000);
      //parse data
      QDataStream in(socket);
      in.setVersion(QDataStream::Qt_4_0);
      debugInfo("m_block_size: " + QString::number(m_block_size));
      if (m_block_size == 0) {
	if (socket->bytesAvailable() < (int)sizeof(quint16))
	  return;
      
	in >> m_block_size;
      }
      debugInfo("bytes available in socket: " + QString::number(socket->bytesAvailable()));
    
      if (socket->bytesAvailable() < m_block_size)
	return;
    
      QString message;
      in >> message;
    
      debugInfo(">Message: [" + message + "]");

      ProtocolStreamType_UE type;
      QStringList params = m_protocol->parseStream_UE(type, message);

      switch (type) {
      case UE_REGISTER:
	{
	  QString temp_name = params.at(0);
	  quint16 temp_port = (quint16) params.at(1).toInt();
	  DLOG (INFO) << "Parsed port: " << temp_port;
	  if (temp_name.isEmpty()) {
	    m_block_size=0;
	    return;
	  }
	  UE temp;
	  int index;
	  if (!isThisNameRegistered(temp_name)) {
	    //case for same ip, different name
	    debugInfo("New user " + temp_name + " connected from same IP. Registering user.");
	    temp.name = temp_name;
	    temp.ip = socket->peerAddress().toString();
	    //parse ue_rx_port
	    temp.rx_port = temp_port;
	    index = getIndexOfUEIp(socket->peerAddress().toString());
	    if (m_online_users.at(index).name.isEmpty()) {
	      //first time, when username is still empty
	      if (index != -1) {
		temp = m_online_users.at(index);
		temp.name = temp_name;
		temp.rx_port = temp_port;
		m_online_users.replace(index,temp);
	      }
	    } else {
	      //same ip but different username, then append new UE
	      m_online_users.append(temp);
	    }
	  } else {
	    LOG (ERROR) << "User already exists on server. Notifying user...";
	    //inform user of currently online users
	    QByteArray block;
	    QDataStream out(&block, QIODevice::WriteOnly);
	    out.setVersion(QDataStream::Qt_4_0);
	    out << (quint16)0;
	    out << QString("ue_error(Existing user on server. Choose other username);");
	    out.device()->seek(0);
	    out << (quint16)(block.size() - sizeof(quint16));
	    DLOG (INFO) <<"Sending error message to UE ...\n";
	    m_log_label->setText(m_log_label->toPlainText()
			      + "\nError: attempted connection with same "
			      "username from same IP. Sending error to client...");
	    socket->write(block);
	    //reset m_block_size
	    m_block_size = 0;
	    return;
	  }
	  DLOG (INFO) << "New user is online: " << temp;
	  debugInfo("Nr. online users: " + QString::number(m_online_users.size()));
	  if (m_log_label->toPlainText() != "") {
	    m_log_label->setText(m_log_label->toPlainText() + "\n[" + temp.name + "]@" +
			      temp.ip + ":" +
			      QString::number(temp.rx_port) + " is now online.");
	  } else {
	    m_log_label->setText(m_log_label->toPlainText() + "[" + temp.name + "]@" +
			      temp.ip + ":" +
			      QString::number(temp.rx_port) + " is now online.");
	  }
	  //parse online users
	  QString users;
	  for (auto user: m_online_users) {
	    users += user.name + "\n";
	  }
	  users.chop(1);
	  m_online_users_label->setText(users);
	  qobject_cast<QLabel*>(m_main_layout->itemAt(2)->widget())->setText("Currently online users("
									  + QString::number(m_online_users.size()) + "):");
	  //inform user of currently online users
	  QByteArray block;
	  QDataStream out(&block, QIODevice::WriteOnly);
	  out.setVersion(QDataStream::Qt_4_0);
	  out << (quint16)0;
	  QStringList params;
	  for (auto user: m_online_users) {
	    params << user.name;
	  }
	  out << m_protocol->constructStream_Server(params,
						    ProtocolStreamType_Server::SERVER_ALL);
	  out.device()->seek(0);
	  out << (quint16)(block.size() - sizeof(quint16));
	  DLOG (INFO) <<"Sending information about currently online users...\n";
	  /*At this point, this block will be sent to all current users, not only to the
	    user that is currently connected*/
	  for (auto connection: m_online_users) {
	    QTcpSocket *temp_socket = new QTcpSocket(this);
	    temp_socket->connectToHost(QHostAddress(connection.ip), connection.rx_port);
	    if (!temp_socket->waitForConnected(3000)) {
	      LOG (ERROR) << "ERROR: Connection attempt @"
			  << connection.ip.toStdString() << ":"
			  << connection.rx_port << " timed out. Omitting current...";
	    } else {
	      debugInfo("Connection to client @" + connection.ip + ":"
			+ QString::number(connection.rx_port) + " was established. Now sending...");
	      temp_socket->write(block);
	      if (!temp_socket->waitForBytesWritten()) {
		LOG (ERROR) << "ERROR: Connection attempt @"
			    << connection.ip.toStdString() << ":"
			    << connection.rx_port << " timed out. Omitting current...";
	      } else {
		debugInfo("Transmission to client @" + connection.ip + ":"
			  + QString::number(connection.rx_port) + " was successful!");
	      }
	    }
	    temp_socket->disconnectFromHost();
	    if (temp_socket->state() == QAbstractSocket::UnconnectedState ||
		temp_socket->waitForDisconnected(1000)) {
	      debugInfo("Socket disconnected.");
	    }
	  }

	  break;

	  
	}
      case UE_ACK:
	{
	  m_log_label->setText(m_log_label->toPlainText() + "\n" + message);
	  debugInfo("Going to forward user ack to destination");
	  QByteArray block;
	  QDataStream out(&block, QIODevice::WriteOnly);
	  out.setVersion(QDataStream::Qt_4_0);
	  out << (quint16)0;
	  out << m_protocol->constructStream_Server(QStringList(message),
						    ProtocolStreamType_Server::SERVER_FWD_TO_SENDER);
	  out.device()->seek(0);
	  out << (quint16)(block.size() - sizeof(quint16));

	  //and lookup destination details for given user
	  QString dest = params.at(0);
	  QString from = params.at(1);
	  unsigned int message_id = (unsigned int) params.at(2).toInt();

	  //Create temporary socket
	  QTcpSocket* dest_socket = new QTcpSocket(this);
	  QString dest_ip;
	  quint16 dest_port;
	  int index = getIndexOfUEName(dest);
	  if (index != -1) {
	    dest_ip = m_online_users.at(index).ip;
	    dest_port = m_online_users.at(index).rx_port;
	    debugInfo("Going to forward ack to " + dest_ip + ":" + QString::number(dest_port));
	  } else {
	    LOG (ERROR) << "ERROR: name was not found on server. Returning...";
	    m_block_size=0;
	    return;
	  }
	  dest_socket->connectToHost(QHostAddress(dest_ip), dest_port);

	  if (!dest_socket->waitForConnected(2000)) {
	    debugInfo("ERROR: request timed out");
	  } else {
	    debugInfo("Established connection with client. Forwarding user ack...");
	    dest_socket->write(block);
	    if (!dest_socket->waitForBytesWritten(5000)) {
	      debugInfo("ERROR: transmission timed out");
	    } else {
	      debugInfo("Success! ACK was forwarded to destination");
	    }
	    dest_socket->disconnectFromHost();
	  }
	  break;
	}
      case UE_ERROR:
	{
	  debugInfo("Some error encountered by user. Returning ...");
	  m_block_size=0;
	  return;
	}
      case UE_MESSAGE:
	{
	  m_log_label->setText(m_log_label->toPlainText() + "\n" + message);
	  //and send it back to the user
	  debugInfo("Going to resend message to dest client: [" + message + "]");
	  
	  QString content = params.at(0);
	  QString dest = params.at(1);
	  QString from = params.at(2);
	  unsigned int message_id = (unsigned int) params.at(3).toInt();
	  
	  DLOG (INFO) << "Message: " << content.toStdString() << ", from " << from.toStdString()
		      << " and to " << dest.toStdString()
		      << ", with message ID: " << message_id;
	  QByteArray block;
	  QDataStream out(&block, QIODevice::WriteOnly);
	  out.setVersion(QDataStream::Qt_4_0);
	  out << (quint16)0;
	  out << m_protocol->constructStream_Server(QStringList(message),
						    ProtocolStreamType_Server::SERVER_FWD_TO_SENDER);
	  out.device()->seek(0);
	  out << (quint16)(block.size() - sizeof(quint16));
	  if (dest == from) {
	    debugInfo("WARNING: Message intended for self UE. Sending back to user...");
	    socket->write(block);
	    if (!socket->waitForBytesWritten(2000)) {
	      LOG (ERROR) << "ERROR: transmission timeout";
	    } else {
	      debugInfo("Success!");
	    }
	  } else {
	    QTcpSocket *dest_socket = new QTcpSocket(this);
	    QString dest_ip;
	    quint16 dest_port;
	    int index = getIndexOfUEName(dest);
	    if (index != -1) {
	      dest_ip = m_online_users.at(index).ip;
	      dest_port = m_online_users.at(index).rx_port;
	      debugInfo("Going to forward message to " + dest_ip + ":" + QString::number(dest_port));
	    } else {
	      LOG (ERROR) << "ERROR: name was not found on server. Returning...";
	      m_block_size=0;
	      return;
	    }
	    dest_socket->connectToHost(QHostAddress(dest_ip), dest_port);
	    if (!dest_socket->waitForConnected(2000)) {
	      debugInfo("ERROR: request timed out");
	    } else {
	      debugInfo("Established connection with client. Sending...");
	      dest_socket->write(block);
	      if (!dest_socket->waitForBytesWritten(5000)) {
		debugInfo("ERROR: transmission timed out");
	      } else {
		debugInfo("Success! Message was forwarded to destination");
	      }
	      dest_socket->disconnectFromHost();
	      //and send an ack to the user to inform that message was received
	      QByteArray ack_data;
	      QDataStream ack(&ack_data, QIODevice::WriteOnly);
	      ack.setVersion(QDataStream::Qt_4_0);
	      ack << (quint16)0;
	      QStringList params;
	      params << from << QString::number(message_id);
	      ack << m_protocol->constructStream_Server(params,
							ProtocolStreamType_Server::SERVER_ACK);
	      ack.device()->seek(0);
	      debugInfo("Sending ack to user: "******"ERROR: transmission timeout!";
	      } else {
		debugInfo("Success!");
	      }
	    }
	  }
	  break;
	}
      case UE_UNREGISTER:
	{
	  unregisterUser();
	  break;
	}
      case UE_TYPING:
	{
	  debugInfo("User is typing...");
	  m_log_label->setText(m_log_label->toPlainText() + "\n" + message);
	  //no need to parse parameters, going to forward to user
	  
	  QString dest = params.at(0);
	  QString from = params.at(1);

	  debugInfo(dest + "," + from);
	  
	  QByteArray typing_data;
	  QDataStream typing_stream(&typing_data, QIODevice::WriteOnly);
	  typing_stream.setVersion(QDataStream::Qt_4_0);
	  typing_stream << (quint16)0;
	  QStringList typing_params;
	  typing_params << params.at(0) << params.at(1) << params.at(2);
	  typing_stream << m_protocol->constructStream_Server(typing_params,
							      ProtocolStreamType_Server::SERVER_FWD_TYPING);
	  typing_stream.device()->seek(0);

	  DLOG (INFO) << "Sending: " << m_protocol->constructStream_Server(typing_params,
							    ProtocolStreamType_Server::SERVER_FWD_TYPING).toStdString();
	  
	  QTcpSocket *dest_socket = new QTcpSocket(this);
	  QString dest_ip;
	  quint16 dest_port;
	  int index = getIndexOfUEName(dest);
	  if (index != -1) {
	    dest_ip = m_online_users.at(index).ip;
	    dest_port = m_online_users.at(index).rx_port;
	    debugInfo("Going to forward typing info to " +
		      dest_ip + ":" + QString::number(dest_port));
	  } else {
	    LOG (ERROR) << "ERROR: name was not found on server. Returning...";
	    m_block_size=0;
	    return;
	  }
	  dest_socket->connectToHost(QHostAddress(dest_ip), dest_port);
	  if (!dest_socket->waitForConnected(2000)) {
	    debugInfo("ERROR: request timed out");
	  } else {
	    debugInfo("Established connection with client. Sending...");
	    dest_socket->write(typing_data);
	    if (!dest_socket->waitForBytesWritten(5000)) {
	      debugInfo("ERROR: transmission timed out");
	    } else {
	      debugInfo("Success! Typing information was forwarded to destination");
	    }
	    dest_socket->disconnectFromHost();
	  }

	  break;
	}
      default:
	LOG (WARNING) << "Unrecognized stream type";
	break;
      }
    
    }
    //reset m_block_size
    m_block_size=0;
  }