コード例 #1
0
ファイル: signalproxy.cpp プロジェクト: hades/quassel
QString SignalProxy::IODevicePeer::address() const {
  QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(_device);
  if(socket)
    return socket->peerAddress().toString();
  else
    return QString();
}
コード例 #2
0
QAbstractSocketEngine *QHttpSocketEngineHandler::createSocketEngine(const QHostAddress &address,
                                                                    QAbstractSocket::SocketType socketType,
                                                                    QObject *parent)
{
    if (socketType != QAbstractSocket::TcpSocket)
        return 0;

    if (address == QHostAddress::LocalHost || address == QHostAddress::LocalHostIPv6)
        return 0;

    // find proxy info
    QAbstractSocket *abstractSocket = qobject_cast<QAbstractSocket *>(parent);
    if (!abstractSocket)
        return 0;

    QNetworkProxy proxy = abstractSocket->proxy();
    if (proxy.type() == QNetworkProxy::DefaultProxy)
        proxy = QNetworkProxy::applicationProxy();

    if (proxy.type() != QNetworkProxy::HttpProxy)
        return 0;

    QHttpSocketEngine *engine = new QHttpSocketEngine(parent);
    engine->setProxy(proxy);
    return engine;
}
コード例 #3
0
uint32_t TQIODeviceTransport::read(uint8_t* buf, uint32_t len)
{
  uint32_t actualSize;
  qint64 readSize;

  if (!dev_->isOpen()) {
    throw TTransportException(TTransportException::NOT_OPEN,
                              "read(): underlying QIODevice is not open");
  }

  actualSize = (uint32_t)std::min((qint64)len, dev_->bytesAvailable());
  readSize = dev_->read(reinterpret_cast<char *>(buf), actualSize);

  if (readSize < 0) {
    QAbstractSocket* socket;
    if ((socket = qobject_cast<QAbstractSocket* >(dev_.get()))) {
      throw TTransportException(TTransportException::UNKNOWN,
                                "Failed to read() from QAbstractSocket",
                                socket->error());
    }
    throw TTransportException(TTransportException::UNKNOWN,
                              "Failed to read from from QIODevice");
  }

  return (uint32_t)readSize;
}
コード例 #4
0
ファイル: SharedDaemon.C プロジェクト: burlen/visit_vtk_7_src
void SharedDaemon::AddNewClient(const std::string &host, const stringVector &args, void *cbdata)
{
    /// Send appropriate message for TCP or WebConnection
    void** data = (void**)cbdata;
    ConnectionType typeOfConnection = *((ConnectionType*)(data[0]));
    QAbstractSocket* socket = static_cast<QAbstractSocket*>(data[1]);
    ViewerState* viewerState = static_cast<ViewerState*>(data[2]);

    JSONNode node;

    QString hostname = typeOfConnection == TcpConnection ? socket->localAddress().toString():
                        dynamic_cast<QWsSocket*>(socket)->internalSocket()->localAddress().toString();

    if(hostMap.contains(hostname)) hostname = hostMap[hostname];

    node["host"] = hostname.toStdString(); //host
    node["port"]  = args[7]; //port
    node["version"] = args[2]; //version
    node["securityKey"] = args[9]; //key
    node["numStates"] = viewerState->GetNumStateObjects(); //number of states

    JSONNode::JSONArray rpc_array = JSONNode::JSONArray();

    for(size_t i = 0; i < ViewerRPC::MaxRPC; ++i) {
        rpc_array.push_back(ViewerRPC::ViewerRPCType_ToString((ViewerRPC::ViewerRPCType)i));
    }
    node["rpc_array"] = rpc_array;

    if(typeOfConnection == TcpConnection)
    {
        QTcpSocket *tsocket = dynamic_cast<QTcpSocket*>(socket);

        std::string message = node.ToString();
        tsocket->write(message.c_str(),message.length());

        if(tsocket->state() != QAbstractSocket::UnconnectedState)
            tsocket->waitForBytesWritten();
        tsocket->disconnectFromHost();
        if(tsocket->state() != QAbstractSocket::UnconnectedState)
            tsocket->waitForDisconnected();
        //HKTODO: Do not delete connection (test fix for ORNL machines)
        //tsocket->deleteLater();
    }
    else
    {
        QWsSocket *wsocket = dynamic_cast<QWsSocket*>(socket);

        wsocket->write(QString(node.ToString().c_str()));
        wsocket->flush();
        if(wsocket->internalSocket()->state() != QAbstractSocket::UnconnectedState)
            wsocket->internalSocket()->waitForBytesWritten();

        wsocket->close("");
        wsocket->internalSocket()->disconnectFromHost();
        if(wsocket->internalSocket()->state() != QAbstractSocket::UnconnectedState)
            wsocket->internalSocket()->waitForDisconnected();
        wsocket->deleteLater();
    }
}
コード例 #5
0
bool HttpServerResponse::flush()
{
    QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(&priv->device);
    if (!socket)
        return false;

    return socket->flush();
}
コード例 #6
0
void SmppClient::onReadyRead()
{
    QAbstractSocket *socket = qobject_cast<QAbstractSocket*>(sender());
    if (socket) {
        stopTimer();
        m_buffer.append(socket->readAll());
        handleIncomingData();
    }
}
コード例 #7
0
void SslTlsSocket::handleSocketError(QAbstractSocket::SocketError err)
{
    Q_UNUSED(err);
    QAbstractSocket *sock = qobject_cast<QAbstractSocket *>(d);
    Q_ASSERT(sock);
    delayedDisconnect->stop();
    emit disconnected(tr("The underlying socket is having troubles when processing connection to %1:%2: %3").arg(
                          host, QString::number(port), sock->errorString()));
}
コード例 #8
0
void SslTlsSocket::handleStateChanged()
{
    /* Qt delivers the stateChanged() signal before the error() one.
    That's a problem because we really want to provide a nice error message
    to the user and QAbstractSocket::error() is not set yet by the time this
    function executes. That's why we have to delay the first disconnected() signal. */

    QAbstractSocket *sock = qobject_cast<QAbstractSocket *>(d);
    Q_ASSERT(sock);
    QString proxyMsg;
    switch (sock->proxy().type()) {
    case QNetworkProxy::NoProxy:
        break;
    case QNetworkProxy::HttpCachingProxy:
        Q_ASSERT_X(false, "proxy detection",
                   "Qt should have returned a proxy capable of tunneling, but we got back an HTTP proxy.");
        break;
    case QNetworkProxy::FtpCachingProxy:
        Q_ASSERT_X(false, "proxy detection",
                   "Qt should have returned a proxy capable of tunneling, but we got back an FTP proxy.");
        break;
    case QNetworkProxy::DefaultProxy:
        proxyMsg = tr(" (via proxy %1)").arg(sock->proxy().hostName());
        break;
    case QNetworkProxy::Socks5Proxy:
        proxyMsg = tr(" (via SOCKS5 proxy %1)").arg(sock->proxy().hostName());
        break;
    case QNetworkProxy::HttpProxy:
        proxyMsg = tr(" (via HTTP proxy %1)").arg(sock->proxy().hostName());
        break;
    }
    switch (sock->state()) {
    case QAbstractSocket::HostLookupState:
        emit stateChanged(Imap::CONN_STATE_HOST_LOOKUP, tr("Looking up %1%2...").arg(host,
                              sock->proxy().capabilities().testFlag(QNetworkProxy::HostNameLookupCapability) ?
                              proxyMsg : QString()));
        break;
    case QAbstractSocket::ConnectingState:
        emit stateChanged(Imap::CONN_STATE_CONNECTING, tr("Connecting to %1:%2%3%4...").arg(
                              host, QString::number(port), startEncrypted ? tr(" (SSL)") : QString(),
                              sock->proxy().capabilities().testFlag(QNetworkProxy::TunnelingCapability) ?
                              proxyMsg : QString()));
        break;
    case QAbstractSocket::BoundState:
    case QAbstractSocket::ListeningState:
        break;
    case QAbstractSocket::ConnectedState:
        if (! startEncrypted) {
            emit stateChanged(Imap::CONN_STATE_CONNECTED_PRETLS_PRECAPS, tr("Connected"));
        } else {
            emit stateChanged(Imap::CONN_STATE_SSL_HANDSHAKE, tr("Negotiating encryption..."));
        }
        break;
    case QAbstractSocket::UnconnectedState:
    case QAbstractSocket::ClosingState:
        disconnectedMessage = tr("Socket is disconnected: %1").arg(sock->errorString());
        delayedDisconnect->start();
        break;
    }
}
コード例 #9
0
ファイル: signalproxy.cpp プロジェクト: hades/quassel
bool SignalProxy::IODevicePeer::isSecure() const {
#ifdef HAVE_SSL
  QSslSocket *sslSocket = qobject_cast<QSslSocket *>(_device);
  if(sslSocket)
    return sslSocket->isEncrypted() || sslSocket->localAddress() == QHostAddress::LocalHost || sslSocket->localAddress() == QHostAddress::LocalHostIPv6;
#endif

  QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(_device);
  if(socket)
    return socket->localAddress() == QHostAddress::LocalHost || socket->localAddress() == QHostAddress::LocalHostIPv6;

  return false;
}
コード例 #10
0
ファイル: worker.cpp プロジェクト: sjinks/repwatch_proxy
qint64 Worker::writeAndFlush(QIODevice* device, const char* buf, int size)
{
	if (device) {
		qint64 res = device->write(buf, size);
		QAbstractSocket* sock = qobject_cast<QAbstractSocket*>(device);
		if (sock) {
			sock->flush();
		}

		return res;
	}

	return -1;
}
コード例 #11
0
QIODevice* EmbraceChunker::newDevice()
{
    QAbstractSocket* lsocket = new QAbstractSocket(QAbstractSocket::UnknownSocketType, 0);

    int sock = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
    if (sock < 0) {
        std::cerr << "socket : %s\n" << strerror(errno) << std::endl;
    }
    if (setsockopt(sock, SOL_SOCKET, SO_RCVBUFFORCE, (char *)&_socketBufferSize, sizeof(unsigned long long)) < 0) {
        std::cerr << "sock opt : %s\n" << strerror(errno) << std::endl;
    }
    lsocket->setSocketDescriptor(sock);
    return lsocket;
}
コード例 #12
0
void TQIODeviceTransport::flush()
{
  if (!dev_->isOpen()) {
    throw TTransportException(TTransportException::NOT_OPEN,
                              "flush(): underlying QIODevice is not open");
  }

  QAbstractSocket* socket;

  if ((socket = qobject_cast<QAbstractSocket*>(dev_.get()))) {
    socket->flush();
  } else {
    dev_->waitForBytesWritten(1);
  }
}
コード例 #13
0
ファイル: worker.cpp プロジェクト: sjinks/repwatch_proxy
/**
 * @see http://tools.ietf.org/html/rfc1929
 *
 * Once the SOCKS V5 server has started, and the client has selected the
 * Username/Password Authentication protocol, the Username/Password
 * subnegotiation begins.  This begins with the client producing a
 * Username/Password request:
 *
 *         +----+------+----------+------+----------+
 *         |VER | ULEN |  UNAME   | PLEN |  PASSWD  |
 *         +----+------+----------+------+----------+
 *         | 1  |  1   | 1 to 255 |  1   | 1 to 255 |
 *         +----+------+----------+------+----------+
 *
 * The VER field contains the current version of the subnegotiation,
 * which is X'01'. The ULEN field contains the length of the UNAME field
 * that follows. The UNAME field contains the username as known to the
 * source operating system. The PLEN field contains the length of the
 * PASSWD field that follows. The PASSWD field contains the password
 * association with the given UNAME.
 */
void Worker::authenticate(void)
{
	int size = this->m_buf.size();
	if (-1 == this->m_expected_length) {
		if (size > 1) {
			quint8 ver = static_cast<quint8>(this->m_buf.at(0));
			int ulen   = static_cast<quint8>(this->m_buf.at(1));
			if (size > 2 + ulen) {
				int plen = static_cast<quint8>(this->m_buf.at(ulen + 2));
				this->m_expected_length = ulen + plen + 3;
			}

			if (ver != 1) {
				this->m_state = Worker::FatalErrorState;
				Q_EMIT this->error(Worker::ProtocolVersionMismatch);
				return;
			}
		}
	}

	if (this->m_expected_length != -1 && size > this->m_expected_length) {
		this->m_state = Worker::FatalErrorState;
		Q_EMIT this->error(Worker::TooMuchData);
		return;
	}

	if (size == this->m_expected_length) {
		int ulen = static_cast<quint8>(this->m_buf.at(1));
		int plen = static_cast<quint8>(this->m_buf.at(ulen + 2));
		QByteArray username = ulen ? QByteArray(this->m_buf.constData() + 2, ulen) : QByteArray();
		QByteArray password = plen ? QByteArray(this->m_buf.constData() + 2 + ulen + 1, plen) : QByteArray();
		QByteArray hostname;
		this->m_expected_length = -1;
		this->m_buf.clear();

		QAbstractSocket* sock = qobject_cast<QAbstractSocket*>(this->m_peer);
		if (sock) {
			hostname = sock->peerAddress().toString().toLocal8Bit();
		}

		if (this->m_noauth_allowed && username.isEmpty() && password.isEmpty()) {
			this->acceptAuthentication();
		}
		else {
			Q_EMIT this->authenticateRequest(username, password, hostname);
		}
	}
}
コード例 #14
0
QXmlStreamReader::TokenType Parser::Private::blockingReadNext()
{
    QXmlStreamReader::TokenType token = QXmlStreamReader::Invalid;

    forever {
        token = reader.readNext();

        if (reader.error() == QXmlStreamReader::PrematureEndOfDocumentError) {
            if (reader.device()->waitForReadyRead(1000)) {
                // let's try again
                continue;
            } else {
                // device error, e.g. remote host closed connection, or timeout
                // ### we have no way to know if waitForReadyRead() timed out or failed with a real
                //     error, and sensible heuristics based on QIODevice fail.
                //     - error strings are translated and in any case not guaranteed to stay the same,
                //       so we can't use them.
                //     - errorString().isEmpty() does not work because errorString() is
                //       "network timeout error" if the waitFor... timed out.
                //     - isSequential() [for socket] && isOpen() doesn't work because isOpen()
                //       returns true if the remote host closed the connection.
                // ...so we fall back to knowing it might be a QAbstractSocket.

                QIODevice *dev = reader.device();
                QAbstractSocket *sock = qobject_cast<QAbstractSocket *>(dev);

                if (!sock || sock->state() != QAbstractSocket::ConnectedState) {
                    throw ParserException(dev->errorString());
                }
            }
        } else if (reader.hasError()) {
            throw ParserException(reader.errorString()); //TODO add line, column?
            break;
        } else {
            // read a valid next token
            break;
        }
    }

    return token;
}
コード例 #15
0
void EmbraceChunker::next(QIODevice* device)
{
    QAbstractSocket* socket = static_cast<QAbstractSocket*>(device);
    WritableData writableData = getDataStorage(_sizeOfFrame);
    int readTotal = 0;
    if (writableData.isValid() ) {
        do {
            int read = socket->read((char*)writableData.ptr() + readTotal*sizeof(char) , _sizeOfFrame);
            if( read == -1 ) { 
                std::cerr << "read error";  
                // TODO - clean up and annul writableData
            }
            readTotal += read;
        } while ( readTotal < _sizeOfFrame );
    }
    else {
        // TODO dump the data here
        std::cerr << "EmbraceChunker: "
                "WritableData is not valid!" << std::endl;
    }
}
コード例 #16
0
ファイル: xmlrpcserver.cpp プロジェクト: yohe/qtxmlrpc-fork
void XmlRpcServer::incomingConnection( int socketDescriptor )
{
#ifdef DEBUG_XMLRPC
    qDebug() << this << "new incoming connection";
#endif

    QAbstractSocket * s = NULL;
#ifndef QT_NO_OPENSSL
    if ( sslParams != NULL && !sslParams->certificate.isNull() )
        {
            s = new QSslSocket( this );
            s->setSocketDescriptor( socketDescriptor );

            ((QSslSocket *)s)->setLocalCertificate( sslParams->certificate );
            ((QSslSocket *)s)->setPrivateKey( sslParams->privateKey );
            ((QSslSocket *)s)->setCaCertificates( sslParams->ca );
        }
    else
        {
            s = new QTcpSocket( this );
            s->setSocketDescriptor( socketDescriptor );
        }
#else
      s = new QTcpSocket( this );
      s->setSocketDescriptor( socketDescriptor );
#endif

      Q_ASSERT( s->state() == QAbstractSocket::ConnectedState );
      connect( s, SIGNAL(disconnected()), this, SLOT(slotSocketDisconnected()) );

      HttpServer * p = new HttpServer( s );
      connect( p, SIGNAL(protocolTimeout(Protocol*)),
               this, SLOT(slotProtocolTimeout(Protocol*)) );
      connect( p, SIGNAL(parseError(HttpServer*)),
               this, SLOT(slotParseError(HttpServer*)) );
      connect( p, SIGNAL(requestReceived(HttpServer*, const QHttpRequestHeader&, const QByteArray&)),
               this, SLOT(slotRequestReceived(HttpServer*, const QHttpRequestHeader&, const QByteArray&)) );
      connect( p, SIGNAL(replySent(HttpServer*)),
               this, SLOT(slotReplySent(HttpServer*)) );
}
コード例 #17
0
uint32_t TQIODeviceTransport::write_partial(const uint8_t* buf, uint32_t len)
{
  qint64 written;

  if (!dev_->isOpen()) {
    throw TTransportException(TTransportException::NOT_OPEN,
                              "write_partial(): underlying QIODevice is not open");
  }

  written = dev_->write(reinterpret_cast<const char*>(buf), len);
  if (written < 0) {
    QAbstractSocket* socket;
    if ((socket = qobject_cast<QAbstractSocket*>(dev_.get()))) {
      throw TTransportException(TTransportException::UNKNOWN,
                                "write_partial(): failed to write to QAbstractSocket", socket->error());
    }

    throw TTransportException(TTransportException::UNKNOWN,
                              "write_partial(): failed to write to underlying QIODevice");
  }

  return (uint32_t)written;
}
コード例 #18
0
ファイル: controler.cpp プロジェクト: 1KoT1/Labs_networktech
void Controler::newConection(){
	QAbstractSocket * socket = tcpServer->nextPendingConnection();
	qDebug()<<trUtf8("Получено соединение: %1:%2").arg(socket->peerAddress().toString()).arg(socket->peerPort());
}
コード例 #19
0
void Graph::onSocketError(QAbstractSocket::SocketError)
{
    QAbstractSocket *socket = (QAbstractSocket *)sender();
    qDebug() << " socket error: " << socket->errorString();
    socket->deleteLater();
}
コード例 #20
0
bool SslTlsSocket::isDead()
{
    QAbstractSocket *sock = qobject_cast<QAbstractSocket *>(d);
    Q_ASSERT(sock);
    return sock->state() != QAbstractSocket::ConnectedState;
}