Exemple #1
0
void QSslServer::incomingConnection(qintptr socket)
{
    QSslSocket *pSslSocket = new QSslSocket();

    if (Q_LIKELY(pSslSocket)) {
        pSslSocket->setSslConfiguration(m_sslConfiguration);

        if (Q_LIKELY(pSslSocket->setSocketDescriptor(socket)))
        {
            typedef void (QSslSocket::* sslErrorsSignal)(const QList<QSslError> &);

#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 2)
            connect(pSslSocket, &QSslSocket::peerVerifyError, this, &QSslServer::peerVerifyError);

            connect(pSslSocket, &QSslSocket::encrypted, this, &QSslServer::newEncryptedConnection);

#else
            connect(pSslSocket,SIGNAL(peerVerifyError(QSslError)), this, SIGNAL(peerVerifyError(QSslError)));
            connect(pSslSocket, SIGNAL(sslErrors(QList<QSslError>)), this, SIGNAL(sslErrors(QList<QSslError>)));
            connect(pSslSocket, SIGNAL(encrypted()), this, SIGNAL(newEncryptedConnection()));
#endif
            addPendingConnection(pSslSocket);

            pSslSocket->startServerEncryption();
        }
        else
        {
            delete pSslSocket;
        }
    }
}
void NetInterface::startArrangedConnection(NetConnection *conn)
{
   conn->setConnectionState(NetConnection::SendingPunchPackets);
   addPendingConnection(conn);
   conn->mConnectSendCount = 0;
   conn->mConnectLastSendTime = getCurrentTime();
   sendPunchPackets(conn);
}
void CListenerSocket::incomingConnection(qintptr socketDescriptor)
{
    CServerSocket * pSock = new CServerSocket();
    pSock->setSocketDescriptor(socketDescriptor);
    connect(pSock,SIGNAL(MessageReady(QString)),this,SLOT(OnIncomingMessage(QString)));
    serverSockets.push_back(pSock);
    addPendingConnection(pSock);
    nextPendingConnection();
}
Exemple #4
0
void SslServer::incomingConnection(qintptr handle)
{
	QSslSocket *socket = new QSslSocket(this);
	socket->setSocketDescriptor(handle);
	socket->setLocalCertificate(_cert);
	socket->setPrivateKey(_key);

	addPendingConnection(socket);
}
Exemple #5
0
void QWsServer::incomingConnection( int socketDescriptor )
{
	QTcpSocket * tcpSocket = new QTcpSocket( tcpServer );
	tcpSocket->setSocketDescriptor( socketDescriptor, QAbstractSocket::ConnectedState );
	QWsSocket * wsSocket = new QWsSocket( this, tcpSocket );

	addPendingConnection( wsSocket );
	emit newConnection();
}
void NetInterface::startConnection(NetConnection *conn)
{
   TNLAssert(conn->getConnectionState() == NetConnection::NotConnected, "Cannot start unless it is in the NotConnected state.");

   addPendingConnection(conn);
   conn->mConnectSendCount = 0;
   conn->setConnectionState(NetConnection::AwaitingChallengeResponse);
   sendConnectChallengeRequest(conn);
}
//! [1]
void SslServer::incomingConnection(qintptr socketDescriptor)
{
    QSslSocket *serverSocket = new QSslSocket;
    if (serverSocket->setSocketDescriptor(socketDescriptor)) {
        addPendingConnection(serverSocket);
        connect(serverSocket, &QSslSocket::encrypted, this, &SslServer::ready);
        serverSocket->startServerEncryption();
    } else {
        delete serverSocket;
    }
}
Exemple #8
0
// Intercept new socket connection and enable SSL
void SslServer::incomingConnection(int socketDescriptor)
{
  QSslSocket *serverSocket = new QSslSocket();
  if (serverSocket->setSocketDescriptor(socketDescriptor))
  {
    addPendingConnection (serverSocket);
  }
  else
  {
    delete serverSocket;
  }
}
void NetInterface::startConnection(NetConnection *conn)
{
   addPendingConnection(conn);
   conn->mConnectionSendCount = 0;
   conn->setConnectSequence(Platform::getVirtualMilliseconds());
   conn->setConnectionState(NetConnection::AwaitingChallengeResponse);

   // This is a the client side of the connection, so set the connection to
   // server flag. We need to set this early so that if the connection times
   // out, its onRemove() will handle the cleanup properly.
   conn->setIsConnectionToServer();

   // Everything set, so send off the request.
   sendConnectChallengeRequest(conn);
}
Exemple #10
0
void Server::incomingConnection(int socketDescriptor)
{
    QTcpSocket *socket = new QTcpSocket(this);
    socket->setSocketDescriptor(socketDescriptor);
    addPendingConnection(socket);

#ifdef DEBUG
    qDebug("\nServer::incomingConnection(%i): %s:%i", socketDescriptor,
           qPrintable(socket->peerAddress().toString()), socket->peerPort());
#endif

    connect(socket, SIGNAL(disconnected()), SLOT(client_disconnected()));
    connect(socket, SIGNAL(readyRead()), SLOT(client_readyRead()));

    m_clients.insert(socket, new Client);
    QccPacket(QccPacket::ConnectionAccepted).send(socket); // QccPacket::ConnectionRefused

#ifdef DEBUG
    qDebug("ConnectionAccepted");
#endif
}
Exemple #11
0
/*!
    Called when a new connection is established.

    Converts \a socket to a QSslSocket.

    \internal
*/
void QSslServer::incomingConnection(qintptr socket)
{
    QSslSocket *pSslSocket = new QSslSocket();

    if (Q_LIKELY(pSslSocket)) {
        pSslSocket->setSslConfiguration(m_sslConfiguration);

        if (Q_LIKELY(pSslSocket->setSocketDescriptor(socket))) {
            connect(pSslSocket, &QSslSocket::peerVerifyError, this, &QSslServer::peerVerifyError);

            typedef void (QSslSocket::* sslErrorsSignal)(const QList<QSslError> &);
            connect(pSslSocket, static_cast<sslErrorsSignal>(&QSslSocket::sslErrors),
                    this, &QSslServer::sslErrors);
            connect(pSslSocket, &QSslSocket::encrypted, this, &QSslServer::newEncryptedConnection);

            addPendingConnection(pSslSocket);

            pSslSocket->startServerEncryption();
        } else {
           delete pSslSocket;
        }
    }
}
/*!
    \internal
 */
void QWebSocketServerPrivate::handshakeReceived()
{
    if (Q_UNLIKELY(!currentSender)) {
        return;
    }
    QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(currentSender->sender);
    if (Q_UNLIKELY(!pTcpSocket)) {
        return;
    }
    //When using Google Chrome the handshake in received in two parts.
    //Therefore, the readyRead signal is emitted twice.
    //This is a guard against the BEAST attack.
    //See: https://www.imperialviolet.org/2012/01/15/beastfollowup.html
    //For Safari, the handshake is delivered at once
    //FIXME: For FireFox, the readyRead signal is never emitted
    //This is a bug in FireFox (see https://bugzilla.mozilla.org/show_bug.cgi?id=594502)
    if (!pTcpSocket->canReadLine()) {
        return;
    }
    disconnect(pTcpSocket, &QTcpSocket::readyRead,
               this, &QWebSocketServerPrivate::handshakeReceived);
    Q_Q(QWebSocketServer);
    bool success = false;
    bool isSecure = false;

    if (m_pendingConnections.length() >= maxPendingConnections()) {
        pTcpSocket->close();
        pTcpSocket->deleteLater();
        setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection,
                 QWebSocketServer::tr("Too many pending connections."));
        return;
    }

    QWebSocketHandshakeRequest request(pTcpSocket->peerPort(), isSecure);
    QTextStream textStream(pTcpSocket);
    request.readHandshake(textStream, MAX_HEADERLINE_LENGTH, MAX_HEADERLINES);

    if (request.isValid()) {
        QWebSocketCorsAuthenticator corsAuthenticator(request.origin());
        Q_EMIT q->originAuthenticationRequired(&corsAuthenticator);

        QWebSocketHandshakeResponse response(request,
                                             m_serverName,
                                             corsAuthenticator.allowed(),
                                             supportedVersions(),
                                             supportedProtocols(),
                                             supportedExtensions());

        if (response.isValid()) {
            QTextStream httpStream(pTcpSocket);
            httpStream << response;
            httpStream.flush();

            if (response.canUpgrade()) {
                QWebSocket *pWebSocket = QWebSocketPrivate::upgradeFrom(pTcpSocket,
                                                                        request,
                                                                        response);
                if (pWebSocket) {
                    addPendingConnection(pWebSocket);
                    Q_EMIT q->newConnection();
                    success = true;
                } else {
                    setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection,
                             QWebSocketServer::tr("Upgrade to WebSocket failed."));
                }
            }
            else {
                setError(response.error(), response.errorString());
            }
        } else {
            setError(QWebSocketProtocol::CloseCodeProtocolError,
                     QWebSocketServer::tr("Invalid response received."));
        }
    }
    if (!success) {
        pTcpSocket->close();
    }
}
Exemple #13
0
void QWsServer::dataReceived()
{
	QTcpSocket * tcpSocket = qobject_cast<QTcpSocket*>( sender() );
	if (tcpSocket == 0)
		return;

	bool allHeadersFetched = false;

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

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

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

		headerBuffer[ tcpSocket ].append(line);
	}

	if (!allHeadersFetched)
	    return;

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

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

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

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

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

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

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

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

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

	QWsSocket * wsSocket = new QWsSocket( this, tcpSocket, version );
	wsSocket->setResourceName( resourceName );
	wsSocket->setHost( host );
	wsSocket->setHostAddress( hostAddress );
	wsSocket->setHostPort( hostPort.toInt() );
	wsSocket->setOrigin( origin );
	wsSocket->setProtocol( protocol );
	wsSocket->setExtensions( extensions );
	wsSocket->serverSideSocket = true;
	
	// ORIGINAL CODE
	//int socketDescriptor = tcpSocket->socketDescriptor();
	//incomingConnection( socketDescriptor );
	
	// CHANGED CODE FOR LINUX COMPATIBILITY
	addPendingConnection( wsSocket );
	emit newConnection();
}
void QWsServer::dataReceived()
{
	QTcpSocket * clientSocket = qobject_cast<QTcpSocket*>(sender());
	if (clientSocket == 0)
		return;

	QString request( clientSocket->readAll() );

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

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

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

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

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

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

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

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

	/*
	// ORIGINAL CODE
	int socketDescriptor = clientSocket->socketDescriptor();
	incomingConnection( socketDescriptor );
	*/
}