Esempio n. 1
0
void ClientSyncer::connectToCore(const QVariantMap &conn) {
  resetConnection();
  coreConnectionInfo = conn;

  if(conn["Host"].toString().isEmpty()) {
    emit connectionError(tr("No Host to connect to specified."));
    return;
  }

  Q_ASSERT(!_socket);
#ifdef HAVE_SSL
  QSslSocket *sock = new QSslSocket(Client::instance());
#else
  if(conn["useSsl"].toBool()) {
    emit connectionError(tr("<b>This client is built without SSL Support!</b><br />Disable the usage of SSL in the account settings."));
    return;
  }
  QTcpSocket *sock = new QTcpSocket(Client::instance());
#endif

#ifndef QT_NO_NETWORKPROXY
  if(conn.contains("useProxy") && conn["useProxy"].toBool()) {
    QNetworkProxy proxy((QNetworkProxy::ProxyType)conn["proxyType"].toInt(), conn["proxyHost"].toString(), conn["proxyPort"].toUInt(), conn["proxyUser"].toString(), conn["proxyPassword"].toString());
    sock->setProxy(proxy);
  }
#endif

  _socket = sock;
  connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
  connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
  connect(sock, SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
  connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
  connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SIGNAL(socketStateChanged(QAbstractSocket::SocketState)));
  sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
}
void SslTlsSocket::delayedStart()
{
    QSslSocket *sock = qobject_cast<QSslSocket *>(d);
    Q_ASSERT(sock);

    switch (m_proxySettings) {
    case Streams::ProxySettings::RespectSystemProxy:
    {
        QNetworkProxy setting;
        QNetworkProxyQuery query = QNetworkProxyQuery(host, port, m_protocolTag, QNetworkProxyQuery::TcpSocket);

        // set to true if a capable setting is found
        bool capableSettingFound = false;

        // set to true if at least one valid setting is found
        bool settingFound = false;

        // FIXME: this static function works particularly slow in Windows
        QList<QNetworkProxy> proxySettingsList = QNetworkProxyFactory::systemProxyForQuery(query);

        /* Proxy Settings are read from the user's environment variables by the above static method.
         * A peculiar case is with *nix systems, where an undefined environment variable is returned as
         * an empty string. Such entries *might* exist in our proxySettingsList, and shouldn't be processed.
         * One good check is to use hostName() of the QNetworkProxy object, and treat the Proxy Setting as invalid if
         * the host name is empty. */
        Q_FOREACH (setting, proxySettingsList) {
            if (!setting.hostName().isEmpty()) {
                settingFound = true;

                // now check whether setting has capabilities
                if (setting.capabilities().testFlag(QNetworkProxy::TunnelingCapability)) {
                    sock->setProxy(setting);
                    capableSettingFound = true;
                    break;
                }
            }
        }

        if (!settingFound || proxySettingsList.isEmpty()) {
            sock->setProxy(QNetworkProxy::NoProxy);
        } else if (!capableSettingFound) {
            emit disconnected(tr("The underlying socket is having troubles when processing connection to %1:%2: %3")
                              .arg(host, QString::number(port), QStringLiteral("Cannot find proxy setting capable of tunneling")));
        }
        break;
    }
    case Streams::ProxySettings::DirectConnect:
        sock->setProxy(QNetworkProxy::NoProxy);
        break;
    }

    if (startEncrypted)
        sock->connectToHostEncrypted(host, port);
    else
        sock->connectToHost(host, port);
}
//I'm the existing device, a new device is kindly introducing itself.
//I will create a TcpSocket and try to connect. This can result in either connected() or connectError().
void LanLinkProvider::newUdpConnection() //udpBroadcastReceived
{
    while (mUdpSocket.hasPendingDatagrams()) {

        QByteArray datagram;
        datagram.resize(mUdpSocket.pendingDatagramSize());
        QHostAddress sender;

        mUdpSocket.readDatagram(datagram.data(), datagram.size(), &sender);

        if (sender.isLoopback() && !mTestMode)
            continue;

        NetworkPackage* receivedPackage = new NetworkPackage("");
        bool success = NetworkPackage::unserialize(datagram, receivedPackage);

        //qCDebug(KDECONNECT_CORE) << "udp connection from " << receivedPackage->;

        //qCDebug(KDECONNECT_CORE) << "Datagram " << datagram.data() ;

        if (!success || receivedPackage->type() != PACKAGE_TYPE_IDENTITY) {
            delete receivedPackage;
            continue;
        }

        if (receivedPackage->get<QString>("deviceId") == KdeConnectConfig::instance()->deviceId()) {
            //qCDebug(KDECONNECT_CORE) << "Ignoring my own broadcast";
            delete receivedPackage;
            continue;
        }

        int tcpPort = receivedPackage->get<int>("tcpPort", port);

        //qCDebug(KDECONNECT_CORE) << "Received Udp identity package from" << sender << " asking for a tcp connection on port " << tcpPort;

        QSslSocket* socket = new QSslSocket(this);
        receivedIdentityPackages[socket].np = receivedPackage;
        receivedIdentityPackages[socket].sender = sender;
        connect(socket, SIGNAL(connected()), this, SLOT(connected()));
        connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectError()));
        socket->connectToHost(sender, tcpPort);
    }
}
// Test buffered socket being properly closed on remote disconnect
void tst_QAbstractSocket::serverDisconnectWithBuffered()
{
    QTcpServer tcpServer;
#ifndef QT_NO_SSL
    QSslSocket testSocket;
#else
    QTcpSocket testSocket;
#endif

    QVERIFY(tcpServer.listen(QHostAddress::LocalHost));
    testSocket.connectToHost(tcpServer.serverAddress(), tcpServer.serverPort());
    // Accept connection on server side
    QVERIFY(tcpServer.waitForNewConnection(5000));
    QTcpSocket *newConnection = tcpServer.nextPendingConnection();
    // Send one char and drop link
    QVERIFY(newConnection != NULL);
    QVERIFY(newConnection->putChar(0));
    QVERIFY(newConnection->flush());
    delete newConnection;

    QVERIFY(testSocket.waitForConnected(5000)); // ready for write
    QVERIFY(testSocket.state() == QAbstractSocket::ConnectedState);

    QSignalSpy spyStateChanged(&testSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)));
    QSignalSpy spyDisconnected(&testSocket, SIGNAL(disconnected()));

    QVERIFY(testSocket.waitForReadyRead(5000)); // have one char already in internal buffer
    char buf[128];
    QCOMPARE(testSocket.read(buf, sizeof(buf)), Q_INT64_C(1));
    if (testSocket.state() != QAbstractSocket::UnconnectedState) {
        QVERIFY(testSocket.waitForDisconnected(5000));
        QVERIFY(testSocket.state() == QAbstractSocket::UnconnectedState);
    }
    // Test signal emitting
    QVERIFY(spyDisconnected.count() == 1);
    QVERIFY(spyStateChanged.count() > 0);
    QVERIFY(qvariant_cast<QAbstractSocket::SocketState>(spyStateChanged.last().first())
            == QAbstractSocket::UnconnectedState);
}
Esempio n. 5
0
void QwwSmtpClientPrivate::processNextCommand(bool ok) {
    if (inProgress && !commandqueue.isEmpty()) {
        emit q->commandFinished(commandqueue.head().id, !ok);
        commandqueue.dequeue();
    }
    if (commandqueue.isEmpty()) {
        inProgress = false;
        emit q->done(false);
        return;
    }
    const SMTPCommand &cmd = commandqueue.head();
    switch (cmd.type) {
    case SMTPCommand::Connect: {
        QString hostName = cmd.data.toList().at(0).toString();
        uint port = cmd.data.toList().at(1).toUInt();
        bool ssl = cmd.data.toList().at(2).toBool();
        if(ssl){
            qDebug() << "SMTP ** connectToHostEncrypted";
            socket->connectToHostEncrypted(hostName, port);
        } else {
            qDebug() << "SMTP ** connectToHost";
            socket->connectToHost(hostName, port);
        }
        setState(QwwSmtpClient::Connecting);
    }
    break;
    case SMTPCommand::Disconnect: {
        sendQuit();
    }
    break;
    case SMTPCommand::StartTLS: {
        qDebug() << "SMTP >>> STARTTLS";
        socket->write("STARTTLS\r\n");
        setState(QwwSmtpClient::TLSRequested);
    }
    break;
    case SMTPCommand::Authenticate: {
        QwwSmtpClient::AuthMode authmode = (QwwSmtpClient::AuthMode)cmd.data.toList().at(0).toInt();
        switch (authmode) {
        case QwwSmtpClient::AuthPlain:
            qDebug() << "SMTP >>> AUTH PLAIN";
            socket->write("AUTH PLAIN\r\n");
            setState(QwwSmtpClient::Authenticating);
            break;
        case QwwSmtpClient::AuthLogin:
            qDebug() << "SMTP >>> AUTH LOGIN";
            socket->write("AUTH LOGIN\r\n");
            setState(QwwSmtpClient::Authenticating);
            break;
        default:
            qWarning("Unsupported or unknown authentication scheme");
            //processNextCommand(false);
        }
    }
    break;
    case SMTPCommand::Mail:
    case SMTPCommand::MailBurl:
    {
        setState(QwwSmtpClient::Sending);
        QByteArray buf = QByteArray("MAIL FROM:<").append(cmd.data.toList().at(0).toByteArray()).append(">\r\n");
        qDebug() << "SMTP >>>" << buf;
        socket->write(buf);
        break;
    }
    case SMTPCommand::RawCommand: {
	QString cont = cmd.data.toString();
	if(!cont.endsWith("\r\n")) cont.append("\r\n");
    setState(QwwSmtpClient::Sending);
    qDebug() << "SMTP >>>" << cont;
	socket->write(cont.toUtf8());
	} break;
    }
    inProgress = true;
    emit q->commandStarted(cmd.id);
}