Beispiel #1
0
void ServerSktTcp::newConnection()
{
	QTcpServer* server = qobject_cast<QTcpServer*>(sender());
	if (!server) return;

	QTcpSocket* client = server->nextPendingConnection();
	while (client)
	{
		Conn* conn = new Conn;
		if (!conn)
		{
			client->deleteLater();
		}
		else
		{
			client->setProperty(PROP_CONN, qVariantFromValue((void*)conn));

			conn->client = client;
			conn->key = TK::ipstr(client->peerAddress(),client->peerPort(), true);

			connect(client, SIGNAL(readyRead()), this, SLOT(newData()));
			connect(client, SIGNAL(destroyed(QObject*)), this, SLOT(close(QObject*)));
			connect(client, SIGNAL(disconnected()), client, SLOT(deleteLater()));
			connect(client, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error()));

			setCookie(conn->key, conn);
		}
		client = server->nextPendingConnection();
	}
}
Beispiel #2
0
    void 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);

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

        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);
        }
    }
Beispiel #3
0
void CGalconServer::slotNewConnection()
{
   QTcpSocket* pClientSocket = m_tcpServer->nextPendingConnection();
   pClientSocket->setProperty(socketID, ++m_currentClientID);
   m_connectedSockets.insert(SocketIDPair(m_currentClientID, pClientSocket));

   connect(pClientSocket,SIGNAL(disconnected()), this, SLOT(removeSocket()));
   connect(pClientSocket, SIGNAL(disconnected()), pClientSocket, SLOT(deleteLater()));
   connect(pClientSocket, SIGNAL(readyRead()), this, SLOT(slotReadClient()));
}
Beispiel #4
0
void KCToolServer::onSocketReadyRead()
{
	QTcpSocket *socket = qobject_cast<QTcpSocket*>(QObject::sender());

	// Parse the first line
	if(!socket->property("firstLineRead").toBool())
	{
		QString line(socket->readLine());
		int sepPos1(line.indexOf(" "));
		int sepPos2(line.indexOf(" ", sepPos1+1));
		QString method(line.left(sepPos1));
		QString path(line.mid(sepPos1+1, sepPos2 - sepPos1 - 1));
		socket->setProperty("method", method);
		socket->setProperty("path", path);
		socket->setProperty("firstLineRead", true);
	}

	// Parse Headers!
	if(!socket->property("headerRead").toBool()) {
		QVariantMap headers(socket->property("headers").toMap());

		while(socket->canReadLine()) {
			QString line = QString(socket->readLine()).trimmed();

			// The header section is terminated by an empty line
			if(line == "") {
				socket->setProperty("headerRead", true);
				break;
			}

			// Split it up
			int sepPos(line.indexOf(":"));
			QString key(line.left(sepPos).trimmed());
			QString val(line.mid(sepPos+1).trimmed());
			headers.insertMulti(key, val);
		}

		socket->setProperty("headers", headers);
	}

	qint64 contentLength = socket->property("headers").toMap().value("Content-Length").toLongLong();
	// Read the body into a buffer
	if(socket->bytesAvailable()) {
		QByteArray buffer(socket->property("buffer").toByteArray());
		qint64 toRead = contentLength - buffer.size();
		buffer.append(socket->read(toRead));
		socket->setProperty("buffer", buffer);
		socket->setProperty("toRead", contentLength - buffer.size());

		// If we have a Content-Length (toLong() fails with 0)
		if(contentLength > 0 && buffer.size() >= contentLength)
			this->handleRequest(socket);
	} else if(contentLength == -1 || contentLength == 0) {
		this->handleRequest(socket);
	}
}
Beispiel #5
0
void Server::onReadyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    Q_ASSERT(socket);
    QVariant variant = socket->property("pending");
    qint32 pending;
    if (variant.isNull()) {
        if (socket->bytesAvailable() < int(sizeof(qint32))) {
            return;
        }
        QDataStream ds(socket);
        ds >> pending;
        if (socket->bytesAvailable() < pending) {
            socket->setProperty("pending", pending);
            return;
        }
    } else {
void HttpProxy::onSocketReadyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    QTcpSocket *proxySocket = nullptr;

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

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

    QString host;
    quint16 port;
    QString key;

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

    proxySocket = new QTcpSocket(socket);
    proxySocket->setProxy(upstreamProxy);
    if (method != "CONNECT") {
        proxySocket->setObjectName(key);
        proxySocket->setProperty("reqData", reqData);
        connect (proxySocket, &QTcpSocket::connected, this, &HttpProxy::onProxySocketConnected);
        connect (proxySocket, &QTcpSocket::readyRead, this, &HttpProxy::onProxySocketReadyRead);
    } else {
        connect (proxySocket, &QTcpSocket::connected, this, &HttpProxy::onProxySocketConnectedHttps);
    }
    connect (proxySocket, &QTcpSocket::disconnected, proxySocket, &QTcpSocket::deleteLater);
    connect (proxySocket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QTcpSocket::error), this, &HttpProxy::onSocketError);
    proxySocket->connectToHost(host, port);
}
Beispiel #7
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