/*!
    Attempts to make a connection to the service identified by \a uuid on the device with address
    \a address.

    The socket is opened in the given \a openMode.

    For BlueZ, the socket first enters the \l ServiceLookupState and queries the connection parameters for
    \a uuid. If the service parameters are successfully retrieved the socket enters
    ConnectingState, and attempts to connect to \a address. If a connection is established,
    QBluetoothSocket enters Connected State and emits connected().

    On BlackBerry and Android, the service connection can directly be established
    using the UUID of the remote service. Therefore these platforms do not require
    the \l ServiceLookupState and \l socketType() is always set to
    \l QBluetoothServiceInfo::RfcommProtocol.

    At any point, the socket can emit error() to signal that an error occurred.

    Note that most platforms require a pairing prior to connecting to the remote device. Otherwise
    the connection process may fail.

    \sa state(), disconnectFromService()
*/
void QBluetoothSocket::connectToService(const QBluetoothAddress &address, const QBluetoothUuid &uuid, OpenMode openMode)
{
    Q_D(QBluetoothSocket);

    if (state() != QBluetoothSocket::UnconnectedState) {
        qCWarning(QT_BT)  << "QBluetoothSocket::connectToService called on busy socket";
        d->errorString = QBluetoothSocket::tr("Trying to connect while connection is in progress");
        setSocketError(QBluetoothSocket::OperationError);
        return;
    }

#if defined(QT_QNX_BLUETOOTH) || defined(QT_ANDROID_BLUETOOTH)
    if (!d->ensureNativeSocket(QBluetoothServiceInfo::RfcommProtocol)) {
        d->errorString = tr("Socket type not supported");
        setSocketError(QBluetoothSocket::UnsupportedProtocolError);
        return;
    }
    d->connectToService(address, uuid, openMode);
#else
    QBluetoothServiceInfo service;
    QBluetoothDeviceInfo device(address, QString(), QBluetoothDeviceInfo::MiscellaneousDevice);
    service.setDevice(device);
    service.setServiceUuid(uuid);
    doDeviceDiscovery(service, openMode);
#endif
}
void
NewNet::TcpClientSocket::connect(const std::string & host, unsigned int port)
{
  assert((descriptor() == -1) || (socketState() == SocketUninitialized));

  setSocketState(SocketConnecting);

  NNLOG("newnet.net.debug", "Resolving host '%s'.", host.c_str());
  struct hostent *h = gethostbyname(host.c_str());
  if(! h)
  {
    NNLOG("newnet.net.warn", "Cannot resolve host '%s'.", host.c_str());
    setSocketError(ErrorCannotResolve);
    cannotConnectEvent(this);
    return;
  }

  struct sockaddr_in address;
  memset(&address, 0, sizeof(address));
  address.sin_family = AF_INET;
  memcpy(&(address.sin_addr.s_addr), *(h->h_addr_list), sizeof(address.sin_addr.s_addr));
  address.sin_port = htons(port);

  NNLOG("newnet.net.debug", "Connecting to host '%s:%u'.", host.c_str(), port);

  int s = socket(PF_INET, SOCK_STREAM, 0);
  if (!setnonblocking(s))
    NNLOG("newnet.net.warn", "Couldn't set socket %i to non blocking (errno: %i)", s, errno);
  setDescriptor(s);

  if(s < 0)
    {
      NNLOG("newnet.net.warn", "Cannot connect to host '%s:%u', error: %i.", host.c_str(), port, WSAGetLastError());
      setSocketError(ErrorCannotConnect);
      cannotConnectEvent(this);
      return;
    }

  // Add a connection timeout
  if (reactor()) {
    m_ConnectionTimeout = reactor()->addTimeout(120000, this, &TcpClientSocket::onConnectionTimeout);
  }

  connectedEvent.connect(this, &TcpClientSocket::onConnected);

  if(::connect(s, (struct sockaddr *)&address, sizeof(struct sockaddr_in)) == 0)
  {
    // When using non blocking socket (most of the time), we don't get here.
    NNLOG("newnet.net.debug", "Connected to host '%s:%u'.", host.c_str(), port);
    setSocketState(SocketConnected);
    connectedEvent(this);
  }
  else if(WSAGetLastError() != WSAEWOULDBLOCK)
  {
    // When using non blocking socket (most of the time), we don't get here.
    NNLOG("newnet.net.warn", "Cannot connect to host '%s:%u', error: %i.", host.c_str(), port, WSAGetLastError());
    setSocketError(ErrorCannotConnect);
    cannotConnectEvent(this);
  }
}
Beispiel #3
0
void
NewNet::UnixServerSocket::listen(const std::string & path)
{
    if(path.length() >= UNIX_PATH_MAX)
    {
        NNLOG("newnet.net.warn", "Unix socket path too long: '%s'.", path.c_str());
        setSocketError(ErrorInvalidPath);
        cannotListenEvent(this);
    }

    unlink(path.c_str());

    struct sockaddr_un address;
    memset(&address, 0, sizeof(address));

    address.sun_family = AF_UNIX;
    memcpy(address.sun_path, path.c_str(), path.length());

    int sock = socket(PF_UNIX, SOCK_STREAM, 0);
    fcntl(sock, F_SETFL, O_NONBLOCK);

    mode_t old_umask = umask(0177);
    int ret = bind(sock, (struct sockaddr *)&address, sizeof(struct sockaddr_un));
    umask(old_umask);
    if(ret != 0)
    {
        NNLOG("newnet.net.warn", "Cannot bind unix socket to '%s', error: %i.", path.c_str(), errno);
        closesocket(sock);
        setSocketError(ErrorCannotBind);
        cannotListenEvent(this);
        return;
    }

    if (::listen(sock, 3) != 0)
    {
        NNLOG("newnet.net.warn", "Cannot listen on unix socket '%s', error: %i.", path.c_str(), errno);
        closesocket(sock);
        setSocketError(ErrorCannotListen);
        cannotListenEvent(this);
        return;
    }

    m_Path = path;
    setDescriptor(sock);
    setSocketState(SocketListening);
    listeningEvent(this);

    NNLOG("newnet.net.debug", "Listening on unix socket '%s'.", path.c_str());
}
/*!
    Attempts to connect to the service described by \a service.

    The socket is opened in the given \a openMode. The \l socketType() may change
    depending on the protocol required by \a service.

    The socket first enters ConnectingState and attempts to connect to the device providing
    \a service. If a connection is established, QBluetoothSocket enters ConnectedState and
    emits connected().

    At any point, the socket can emit error() to signal that an error occurred.

    Note that most platforms require a pairing prior to connecting to the remote device. Otherwise
    the connection process may fail.

    \sa state(), disconnectFromService()
*/
void QBluetoothSocket::connectToService(const QBluetoothServiceInfo &service, OpenMode openMode)
{
    Q_D(QBluetoothSocket);

    if (state() != QBluetoothSocket::UnconnectedState && state() != QBluetoothSocket::ServiceLookupState) {
        qCWarning(QT_BT)  << "QBluetoothSocket::connectToService called on busy socket";
        d->errorString = QBluetoothSocket::tr("Trying to connect while connection is in progress");
        setSocketError(QBluetoothSocket::OperationError);
        return;
    }
#if defined(QT_QNX_BLUETOOTH) || defined(QT_ANDROID_BLUETOOTH)
    if (!d->ensureNativeSocket(service.socketProtocol())) {
        d->errorString = tr("Socket type not supported");
        setSocketError(QBluetoothSocket::UnsupportedProtocolError);
        return;
    }
    d->connectToService(service.device().address(), service.serviceUuid(), openMode);
#else
    if (service.protocolServiceMultiplexer() > 0) {
        if (!d->ensureNativeSocket(QBluetoothServiceInfo::L2capProtocol)) {
            d->errorString = tr("Unknown socket error");
            setSocketError(UnknownSocketError);
            return;
        }
        d->connectToService(service.device().address(), service.protocolServiceMultiplexer(), openMode);
    } else if (service.serverChannel() > 0) {
        if (!d->ensureNativeSocket(QBluetoothServiceInfo::RfcommProtocol)) {
            d->errorString = tr("Unknown socket error");
            setSocketError(UnknownSocketError);
            return;
        }
        d->connectToService(service.device().address(), service.serverChannel(), openMode);
    } else {
        // try doing service discovery to see if we can find the socket
        if(service.serviceUuid().isNull()){
            qCWarning(QT_BT) << "No port, no PSM, and no UUID provided, unable to connect";
            return;
        }
        qCDebug(QT_BT) << "Need a port/psm, doing discovery";
        doDeviceDiscovery(service, openMode);
    }
#endif
}
qint64 QBluetoothSocket::writeData(const char *data, qint64 maxSize)
{
    Q_D(QBluetoothSocket);

    if (!data || maxSize <= 0) {
        d_ptr->errorString = tr("Invalid data/data size");
        setSocketError(QBluetoothSocket::OperationError);
        return -1;
    }

    return d->writeData(data, maxSize);
}
void QBluetoothSocket::discoveryFinished()
{
    qCDebug(QT_BT) << "Socket discovery finished";
    Q_D(QBluetoothSocket);
    if (d->discoveryAgent){
        qCDebug(QT_BT) << "Didn't find any";
        d->errorString = tr("Service cannot be found");
        setSocketError(ServiceNotFoundError);
        setSocketState(QBluetoothSocket::UnconnectedState);
        d->discoveryAgent->deleteLater();
        d->discoveryAgent = 0;
    }
}
/*!
    Attempts to make a connection with \a address on the given \a port.

    The socket is opened in the given \a openMode.

    The socket first enters ConnectingState, and attempts to connect to \a address. If a
    connection is established, QBluetoothSocket enters ConnectedState and emits connected().

    At any point, the socket can emit error() to signal that an error occurred.

    On BlackBerry and Android, a connection to a service can not be established using a port. Calling this function
    will emit a \l {QBluetoothSocket::ServiceNotFoundError}{ServiceNotFoundError}

    Note that most platforms require a pairing prior to connecting to the remote device. Otherwise
    the connection process may fail.

    \sa state(), disconnectFromService()
*/
void QBluetoothSocket::connectToService(const QBluetoothAddress &address, quint16 port, OpenMode openMode)
{
    Q_D(QBluetoothSocket);
#if defined(QT_QNX_BLUETOOTH) || defined(QT_ANDROID_BLUETOOTH)
    Q_UNUSED(port);
    Q_UNUSED(openMode);
    Q_UNUSED(address);
    d->errorString = tr("Connecting to port is not supported");
    setSocketError(QBluetoothSocket::ServiceNotFoundError);
    qCWarning(QT_BT) << "Connecting to port is not supported";
#else
    if (state() != QBluetoothSocket::UnconnectedState) {
        qCWarning(QT_BT)  << "QBluetoothSocket::connectToService called on busy socket";
        d->errorString = QBluetoothSocket::tr("Trying to connect while connection is in progress");
        setSocketError(QBluetoothSocket::OperationError);
        return;
    }

    setOpenMode(openMode);
    d->connectToService(address, port, openMode);
#endif
}
void DhQAbstractSocket::DvhsetSocketError(long x1) {
  return setSocketError((QAbstractSocket::SocketError)x1);
}
void OftSocket::onReadyRead()
{
	if (m_state & Proxy) {
		DataUnit data;
		if (m_len == 0) {
			if (bytesAvailable() <= 4)
				return;
			data.setData(read(4));
			m_len = data.read<quint16>() - 2;
			if (data.read<quint16>() != 0x044A)
				debug() << "Unknown proxy protocol version";
		}
		if (bytesAvailable() <= m_len) {
			data.setData(read(m_len));
			m_len = 0;
		} else {
			return;
		}
		quint16 type = data.read<quint16>();
		data.skipData(4); // unknown
		quint16 flags = data.read<quint16>();
		Q_UNUSED(flags);
		debug() << "Rendezvous proxy packet. Type" << type;
		switch (type) {
		case 0x0001 : { // error
			quint16 code = data.read<quint16>();
			QString str;
			if (code == 0x000d || code == 0x000e)
				str = "Bad Request";
			else if (code == 0x0010)
				str = "Initial Request Timed Out";
			else if (code == 0x001a)
				str = "Accept Period Timed Out";
			else
				str = QString("Unknown rendezvous proxy error: %1").arg(code);
			debug() << "Rendezvous proxy error:" << str;
			setSocketError(QAbstractSocket::ProxyProtocolError);
			setErrorString(str);
			emit error(QAbstractSocket::ProxyProtocolError);
			break;
		}
		case 0x0003 : { // Acknowledge
			if (m_state != ProxyInit) {
				setSocketError(QAbstractSocket::ProxyProtocolError);
				setErrorString("Rendezvous proxy acknowledge packets are forbidden");
				emit error(QAbstractSocket::ProxyProtocolError);
				break;
			}
			m_proxyPort = data.read<quint16>();
			m_proxyIP.setAddress(data.read<quint32>());
			emit proxyInitialized();
			break;
		}
		case 0x0005 : { // Ready
			m_state = ReadHeader;
			emit initialized();
			break;
		}
		default:
			setSocketError(QAbstractSocket::ProxyProtocolError);
			setErrorString(QString("Unknown rendezvous proxy request").arg(type));
			emit error(QAbstractSocket::ProxyProtocolError);
		}
	} else {
		if (m_state == ReadHeader) {
			m_lastHeader.readData(this, m_client->asciiCodec());
			if (m_lastHeader.isFinished()) {
				m_state = ReadData;
				emit headerReaded(m_lastHeader);
			}
		}
		if (m_state == ReadData && bytesAvailable() > 0)
			emit newData();
	}
}