예제 #1
0
void slm_client::readMessagefromBuddy(QString incomingMessage, QHostAddress peerAddress)
{
    QDateTime currentTime;
    QString shownMessage;

    //decrypt the message
    incomingMessage = encryptionObject.dencrypt(incomingMessage, "qweertesdjhfgjhsdfsmg2008xbnxcvbnxvashgdahgdhafdajhfdvsbdcvgsdvf");

    qDebug() << "Decrypted Text :: " << incomingMessage;

    // check if the message gui is open or not and open if it is not.
    if(this->getGuiKey() == 0)
    {
        this->show();
        this->setGuiKey(1);// set the gui key to one to indicate it is opened
    }
    else
    {
        this->activateWindow();// if it is already opened, activate it before writing the message
    }
    //show the message to the user by adding current data and time
    shownMessage =  currentTime.currentDateTime().toString() + " From " + peerAddress.toString() + ": " + "\n" + "\n" + incomingMessage + "\n";
    m_ui->slm_clientIncomingTextArea->append(shownMessage);
}
예제 #2
0
void AdvancedSettings::updateInterfaceAddressCombo()
{
    // Try to get the currently selected interface name
    const QString ifaceName = comboBoxInterface.itemData(comboBoxInterface.currentIndex()).toString(); // Empty string for the first element
    const QString currentAddress = BitTorrent::Session::instance()->networkInterfaceAddress();

    // Clear all items and reinsert them, default to all
    comboBoxInterfaceAddress.clear();
    comboBoxInterfaceAddress.addItem(tr("All addresses"));
    comboBoxInterfaceAddress.setCurrentIndex(0);

    auto populateCombo = [this, &currentAddress](const QString &ip, const QAbstractSocket::NetworkLayerProtocol &protocol)
    {
        Q_ASSERT((protocol == QAbstractSocket::IPv4Protocol) || (protocol == QAbstractSocket::IPv6Protocol));
        // Only take ipv4 for now?
        if ((protocol != QAbstractSocket::IPv4Protocol) && (protocol != QAbstractSocket::IPv6Protocol))
            return;
        comboBoxInterfaceAddress.addItem(ip);
        //Try to select the last added one
        if (ip == currentAddress)
            comboBoxInterfaceAddress.setCurrentIndex(comboBoxInterfaceAddress.count() - 1);
    };

    if (ifaceName.isEmpty()) {
        for (const QHostAddress &ip : asConst(QNetworkInterface::allAddresses()))
            populateCombo(ip.toString(), ip.protocol());
    }
    else {
        const QNetworkInterface iface = QNetworkInterface::interfaceFromName(ifaceName);
        const QList<QNetworkAddressEntry> addresses = iface.addressEntries();
        for (const QNetworkAddressEntry &entry : addresses) {
            const QHostAddress ip = entry.ip();
            populateCombo(ip.toString(), ip.protocol());
        }
    }
}
예제 #3
0
void ServerDiscoveryModel::addService(KDNSSD::RemoteService::Ptr service)
{
	QUrl url;
	url.setScheme("drawpile");
	QHostAddress hostname = KDNSSD::ServiceBrowser::resolveHostName(service->hostName());
	url.setHost(hostname.isNull() ? service->hostName() : hostname.toString());
	if(service->port() != DRAWPILE_PROTO_DEFAULT_PORT)
		url.setPort(service->port());

	QDateTime started = QDateTime::fromString(service->textData()["started"], Qt::ISODate);
	started.setTimeSpec(Qt::UTC);

	DiscoveredServer s {
		url,
		service->serviceName(),
		service->textData()["title"],
		service->textData()["protocol"],
		started
	};

	beginInsertRows(QModelIndex(), _servers.size(), _servers.size());
	_servers.append(s);
	endInsertRows();
}
예제 #4
0
void NetworkMonitor::processPendingDatagrams()
{
  while( socket.hasPendingDatagrams() )
  {
    QByteArray datagram;
    QHostAddress sender;
    datagram.resize( socket.pendingDatagramSize() );
    socket.readDatagram( datagram.data(), datagram.size(), &sender );
		
		if( QString( datagram.data() ) == QString( broadcastPing.data() ) && datagram.size() == broadcastPing.size() )
			break;
		
    QString socketKey = sender.toString( );
    if( !connectedDevices.contains( socketKey ) )
    {
    	PacketUdp* device = new PacketUdp( );
    	connectedDevices.insert( socketKey, device );  // stick it in our own list of boards we know about
    	
    	device->setRemoteHostInfo( &sender, listenPort );
    	device->setKey( socketKey );
    	device->setInterfaces( messageInterface, this );
    	device->open( );
    	
    	// post it to the UI
    	BoardArrivalEvent* event = new BoardArrivalEvent( Board::Udp );
			event->pUdp.append( device );
			application->postEvent( mainWindow, event );
    }
    if( connectedDevices.contains( socketKey ) ) // pass the packet through to the packet interface
    {
    	connectedDevices.value( socketKey )->incomingMessage( datagram );
    	connectedDevices.value( socketKey )->processPacket( );
    	connectedDevices.value( socketKey )->resetTimer( );
    }
  }
}
예제 #5
0
bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &address, quint16 port)
{

#if defined (QNATIVESOCKETENGINE_DEBUG)
    qDebug("QNativeSocketEnginePrivate::nativeConnect() to %s :: %i", address.toString().toLatin1().constData(), port);
#endif

    struct sockaddr_in sockAddrIPv4;
    qt_sockaddr_in6 sockAddrIPv6;
    struct sockaddr *sockAddrPtr = 0;
    QT_SOCKLEN_T sockAddrSize = 0;

    qt_socket_setPortAndAddress(socketDescriptor, &sockAddrIPv4, &sockAddrIPv6, port, address, &sockAddrPtr, &sockAddrSize);

    forever {
        int connectResult = ::WSAConnect(socketDescriptor, sockAddrPtr, sockAddrSize, 0,0,0,0);
        if (connectResult == SOCKET_ERROR) {
            int err = WSAGetLastError();
            WS_ERROR_DEBUG(err);

            switch (err) {
            case WSANOTINITIALISED:
                //###
                break;
            case WSAEISCONN:
                socketState = QAbstractSocket::ConnectedState;
                break;
            case WSAEWOULDBLOCK: {
                // If WSAConnect returns WSAEWOULDBLOCK on the second
                // connection attempt, we have to check SO_ERROR's
                // value to detect ECONNREFUSED. If we don't get
                // ECONNREFUSED, we'll have to treat it as an
                // unfinished operation.
                int value = 0;
                QT_SOCKLEN_T valueSize = sizeof(value);
                if (::getsockopt(socketDescriptor, SOL_SOCKET, SO_ERROR, (char *) &value, &valueSize) == 0) {
                    if (value == WSAECONNREFUSED) {
                        setError(QAbstractSocket::ConnectionRefusedError, ConnectionRefusedErrorString);
                        socketState = QAbstractSocket::UnconnectedState;
                        break;
                    }
                    if (value == WSAETIMEDOUT) {
                        setError(QAbstractSocket::NetworkError, ConnectionTimeOutErrorString);
                        socketState = QAbstractSocket::UnconnectedState;
                        break;
                    }
                    if (value == WSAEHOSTUNREACH) {
                        setError(QAbstractSocket::NetworkError, HostUnreachableErrorString);
                        socketState = QAbstractSocket::UnconnectedState;
                        break;
                    }
                    if (value == WSAEADDRNOTAVAIL) {
                        setError(QAbstractSocket::NetworkError, AddressNotAvailableErrorString);
                        socketState = QAbstractSocket::UnconnectedState;
                        break;
                    }
                }
                // fall through
            }
            case WSAEINPROGRESS:
                setError(QAbstractSocket::UnfinishedSocketOperationError, InvalidSocketErrorString);
                socketState = QAbstractSocket::ConnectingState;
                break;
            case WSAEADDRINUSE:
                setError(QAbstractSocket::NetworkError, AddressInuseErrorString);
                break;
            case WSAECONNREFUSED:
                setError(QAbstractSocket::ConnectionRefusedError, ConnectionRefusedErrorString);
                socketState = QAbstractSocket::UnconnectedState;
                break;
            case WSAETIMEDOUT:
                setError(QAbstractSocket::NetworkError, ConnectionTimeOutErrorString);
                break;
            case WSAEACCES:
                setError(QAbstractSocket::SocketAccessError, AccessErrorString);
                socketState = QAbstractSocket::UnconnectedState;
                break;
            case WSAEHOSTUNREACH:
                setError(QAbstractSocket::NetworkError, HostUnreachableErrorString);
                socketState = QAbstractSocket::UnconnectedState;
                break;
            case WSAENETUNREACH:
                setError(QAbstractSocket::NetworkError, NetworkUnreachableErrorString);
                socketState = QAbstractSocket::UnconnectedState;
                break;
            case WSAEINVAL:
            case WSAEALREADY:
                setError(QAbstractSocket::UnfinishedSocketOperationError, InvalidSocketErrorString);
                break;
            default:
                break;
            }
            if (socketState != QAbstractSocket::ConnectedState) {
#if defined (QNATIVESOCKETENGINE_DEBUG)
                qDebug("QNativeSocketEnginePrivate::nativeConnect(%s, %i) == false (%s)",
                        address.toString().toLatin1().constData(), port,
                        socketState == QAbstractSocket::ConnectingState
                        ? "Connection in progress" : socketErrorString.toLatin1().constData());
#endif
                return false;
            }
        }
        break;
    }

#if defined (QNATIVESOCKETENGINE_DEBUG)
    qDebug("QNativeSocketEnginePrivate::nativeConnect(%s, %i) == true",
           address.toString().toLatin1().constData(), port);
#endif

    socketState = QAbstractSocket::ConnectedState;
    return true;
}
예제 #6
0
void RDStation::setAddress(QHostAddress addr) const
{
  SetRow("IPV4_ADDRESS",addr.toString());
}
예제 #7
0
void RaspberryPiDebugWidget::setIp(QHostAddress ip)
{
    ui->labIp->setText(ip.toString());
}
예제 #8
0
QHostInfo QHostInfoAgent::fromName(const QString &hostName)
{
    QHostInfo results;

#if defined(QHOSTINFO_DEBUG)
    qDebug("QHostInfoAgent::fromName(%s) looking up...",
           hostName.toLatin1().constData());
#endif

    // Load res_init on demand.
    static volatile bool triedResolve = false;
    if (!triedResolve) {
        QMutexLocker locker(QMutexPool::globalInstanceGet(&local_res_init));
        if (!triedResolve) {
            resolveLibrary();
            triedResolve = true;
        }
    }

    // If res_init is available, poll it.
    if (local_res_init)
        local_res_init();

    QHostAddress address;
    if (address.setAddress(hostName)) {
        // Reverse lookup
// Reverse lookups using getnameinfo are broken on darwin, use gethostbyaddr instead.
#if !defined (QT_NO_GETADDRINFO) && !defined (Q_OS_DARWIN)
        sockaddr_in sa4;
#ifndef QT_NO_IPV6
        sockaddr_in6 sa6;
#endif
        sockaddr *sa = 0;
        QT_SOCKLEN_T saSize = 0;
        if (address.protocol() == QAbstractSocket::IPv4Protocol) {
            sa = (sockaddr *)&sa4;
            saSize = sizeof(sa4);
            memset(&sa4, 0, sizeof(sa4));
            sa4.sin_family = AF_INET;
            sa4.sin_addr.s_addr = htonl(address.toIPv4Address());
        }
#ifndef QT_NO_IPV6
        else {
            sa = (sockaddr *)&sa6;
            saSize = sizeof(sa6);
            memset(&sa6, 0, sizeof(sa6));
            sa6.sin6_family = AF_INET6;
            memcpy(sa6.sin6_addr.s6_addr, address.toIPv6Address().c, sizeof(sa6.sin6_addr.s6_addr));
        }
#endif

        char hbuf[NI_MAXHOST];
        if (sa && getnameinfo(sa, saSize, hbuf, sizeof(hbuf), 0, 0, 0) == 0)
            results.setHostName(QString::fromLatin1(hbuf));
#else
        in_addr_t inetaddr = qt_safe_inet_addr(hostName.toLatin1().constData());
        struct hostent *ent = gethostbyaddr((const char *)&inetaddr, sizeof(inetaddr), AF_INET);
        if (ent)
            results.setHostName(QString::fromLatin1(ent->h_name));
#endif

        if (results.hostName().isEmpty())
            results.setHostName(address.toString());
        results.setAddresses(QList<QHostAddress>() << address);
        return results;
    }

    // IDN support
    QByteArray aceHostname = QUrl::toAce(hostName);
    results.setHostName(hostName);
    if (aceHostname.isEmpty()) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(hostName.isEmpty() ?
                               QCoreApplication::translate("QHostInfoAgent", "No host name given") :
                               QCoreApplication::translate("QHostInfoAgent", "Invalid hostname"));
        return results;
    }

#if !defined (QT_NO_GETADDRINFO)
    // Call getaddrinfo, and place all IPv4 addresses at the start and
    // the IPv6 addresses at the end of the address list in results.
    addrinfo *res = 0;
    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = PF_UNSPEC;
#ifdef Q_ADDRCONFIG
    hints.ai_flags = Q_ADDRCONFIG;
#endif

    int result = getaddrinfo(aceHostname.constData(), 0, &hints, &res);
# ifdef Q_ADDRCONFIG
    if (result == EAI_BADFLAGS) {
        // if the lookup failed with AI_ADDRCONFIG set, try again without it
        hints.ai_flags = 0;
        result = getaddrinfo(aceHostname.constData(), 0, &hints, &res);
    }
# endif

    if (result == 0) {
        addrinfo *node = res;
        QList<QHostAddress> addresses;
        while (node) {
#ifdef QHOSTINFO_DEBUG
                qDebug() << "getaddrinfo node: flags:" << node->ai_flags << "family:" << node->ai_family << "ai_socktype:" << node->ai_socktype << "ai_protocol:" << node->ai_protocol << "ai_addrlen:" << node->ai_addrlen;
#endif
            if (node->ai_family == AF_INET) {
                QHostAddress addr;
                addr.setAddress(ntohl(((sockaddr_in *) node->ai_addr)->sin_addr.s_addr));
                if (!addresses.contains(addr))
                    addresses.append(addr);
            }
#ifndef QT_NO_IPV6
            else if (node->ai_family == AF_INET6) {
                QHostAddress addr;
                sockaddr_in6 *sa6 = (sockaddr_in6 *) node->ai_addr;
                addr.setAddress(sa6->sin6_addr.s6_addr);
                if (sa6->sin6_scope_id)
                    addr.setScopeId(QString::number(sa6->sin6_scope_id));
                if (!addresses.contains(addr))
                    addresses.append(addr);
            }
#endif
            node = node->ai_next;
        }
        if (addresses.isEmpty() && node == 0) {
            // Reached the end of the list, but no addresses were found; this
            // means the list contains one or more unknown address types.
            results.setError(QHostInfo::UnknownError);
            results.setErrorString(tr("Unknown address type"));
        }

        results.setAddresses(addresses);
        freeaddrinfo(res);
    } else if (result == EAI_NONAME
               || result ==  EAI_FAIL
#ifdef EAI_NODATA
	       // EAI_NODATA is deprecated in RFC 3493
	       || result == EAI_NODATA
#endif
	       ) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(tr("Host not found"));
    } else {
        results.setError(QHostInfo::UnknownError);
        results.setErrorString(QString::fromLocal8Bit(gai_strerror(result)));
    }

#else
    // Fall back to gethostbyname for platforms that don't define
    // getaddrinfo. gethostbyname does not support IPv6, and it's not
    // reentrant on all platforms. For now this is okay since we only
    // use one QHostInfoAgent, but if more agents are introduced, locking
    // must be provided.
    QMutexLocker locker(::getHostByNameMutex());
    hostent *result = gethostbyname(aceHostname.constData());
    if (result) {
        if (result->h_addrtype == AF_INET) {
            QList<QHostAddress> addresses;
            for (char **p = result->h_addr_list; *p != 0; p++) {
                QHostAddress addr;
                addr.setAddress(ntohl(*((quint32 *)*p)));
                if (!addresses.contains(addr))
                    addresses.prepend(addr);
            }
            results.setAddresses(addresses);
        } else {
            results.setError(QHostInfo::UnknownError);
            results.setErrorString(tr("Unknown address type"));
        }
#if !defined(Q_OS_VXWORKS)
    } else if (h_errno == HOST_NOT_FOUND || h_errno == NO_DATA
               || h_errno == NO_ADDRESS) {
        results.setError(QHostInfo::HostNotFound);
        results.setErrorString(tr("Host not found"));
#endif
    } else {
        results.setError(QHostInfo::UnknownError);
        results.setErrorString(tr("Unknown error"));
    }
#endif //  !defined (QT_NO_GETADDRINFO)

#if defined(QHOSTINFO_DEBUG)
    if (results.error() != QHostInfo::NoError) {
        qDebug("QHostInfoAgent::fromName(): error #%d %s",
               h_errno, results.errorString().toLatin1().constData());
    } else {
        QString tmp;
        QList<QHostAddress> addresses = results.addresses();
        for (int i = 0; i < addresses.count(); ++i) {
            if (i != 0) tmp += ", ";
            tmp += addresses.at(i).toString();
        }
        qDebug("QHostInfoAgent::fromName(): found %i entries for \"%s\": {%s}",
               addresses.count(), hostName.toLatin1().constData(),
               tmp.toLatin1().constData());
    }
#endif
    return results;
}
예제 #9
0
void ServerPool::SelectDefaultListen(bool force)
{
    if (!force)
    {
        QReadLocker rlock(&naLock);
        if (!naList_4.isEmpty() || !naList_6.isEmpty())
            // lists are already populated, do nothing
            return;
    }

    QWriteLocker wlock(&naLock);
    naList_4.clear();
    naList_6.clear();

    // populate stored IPv4 and IPv6 addresses
    QHostAddress config_v4(gCoreContext->resolveSettingAddress(
                                           "BackendServerIP",
                                           QString(),
                                           gCoreContext->ResolveIPv4, true));
    bool v4IsSet = config_v4.isNull() ? true : false;
#if !defined(QT_NO_IPV6)
    QHostAddress config_v6(gCoreContext->resolveSettingAddress(
                                           "BackendServerIP6",
                                           QString(),
                                           gCoreContext->ResolveIPv6, true));
    bool v6IsSet = config_v6.isNull() ? true : false;
#endif
    bool allowLinkLocal = gCoreContext->GetNumSetting("AllowLinkLocal", true) > 0;

    // loop through all available interfaces
    QList<QNetworkInterface> IFs = QNetworkInterface::allInterfaces();
    QList<QNetworkInterface>::const_iterator qni;
    for (qni = IFs.begin(); qni != IFs.end(); ++qni)
    {
        if ((qni->flags() & QNetworkInterface::IsRunning) == 0)
            continue;

        QList<QNetworkAddressEntry> IPs = qni->addressEntries();
        QList<QNetworkAddressEntry>::iterator qnai;
        for (qnai = IPs.begin(); qnai != IPs.end(); ++qnai)
        {
            QHostAddress ip = qnai->ip();
#if !defined(QT_NO_IPV6)
            if (ip.protocol() == QAbstractSocket::IPv4Protocol)
            {
#endif
                if (naList_4.contains(*qnai))
                    // already defined, skip
                    continue;

                else if (!config_v4.isNull() && (ip == config_v4))
                {
                    // IPv4 address is defined, add it
                    LOG(VB_GENERAL, LOG_DEBUG,
                        QString("Adding BackendServerIP to address list."));
                    naList_4.append(*qnai);
                    v4IsSet = true;

                }

                else if (ip == QHostAddress::LocalHost)
                {
                    // always listen on LocalHost
                    LOG(VB_GENERAL, LOG_DEBUG,
                        QString("Adding IPv4 loopback to address list."));
                    naList_4.append(*qnai);
                    if (!v4IsSet && (config_v4 == ip))
                        v4IsSet = true;
                }

                else if (ip.isInSubnet(kLinkLocal) && allowLinkLocal)
                {
                    // optionally listen on linklocal
                    // the next clause will enable it anyway if no IP address
                    // has been set
                    LOG(VB_GENERAL, LOG_DEBUG,
                            QString("Adding link-local '%1' to address list.")
                                .arg(PRETTYIP_(ip)));
                    naList_4.append(*qnai);
                }

                else if (config_v4.isNull())
                {
                    // IPv4 address is not defined, populate one
                    // restrict autoconfiguration to RFC1918 private networks
                    static QPair<QHostAddress, int>
                       privNet1 = QHostAddress::parseSubnet("10.0.0.0/8"),
                       privNet2 = QHostAddress::parseSubnet("172.16.0.0/12"),
                       privNet3 = QHostAddress::parseSubnet("192.168.0.0/16");

                    if (ip.isInSubnet(privNet1) || ip.isInSubnet(privNet2) ||
                        ip.isInSubnet(privNet3))
                    {
                        LOG(VB_GENERAL, LOG_DEBUG,
                                QString("Adding '%1' to address list.")
                                    .arg(PRETTYIP_(ip)));
                        naList_4.append(*qnai);
                    }
                    else if (ip.isInSubnet(kLinkLocal))
                    {
                        LOG(VB_GENERAL, LOG_DEBUG,
                            QString("Adding link-local '%1' to address list.")
                                    .arg(PRETTYIP_(ip)));
                        naList_4.append(*qnai);
                    }
                    else
                        LOG(VB_GENERAL, LOG_DEBUG, QString("Skipping "
                           "non-private address during IPv4 autoselection: %1")
                                    .arg(PRETTYIP_(ip)));
                }

                else
                    LOG(VB_GENERAL, LOG_DEBUG, QString("Skipping address: %1")
                                .arg(PRETTYIP_(ip)));

#if !defined(QT_NO_IPV6)
            }
            else
            {
                if (ip.isInSubnet(kLinkLocal6))
                {
                    // set scope id for link local address
                    ip.setScopeId(qni->name());
                    qnai->setIp(ip);
                }

                if (naList_6.contains(*qnai))
                    // already defined, skip
                    continue;

                else if ((!config_v6.isNull()) && (ip == config_v6))
                {
                // IPv6 address is defined, add it
                    LOG(VB_GENERAL, LOG_DEBUG,
                        QString("Adding BackendServerIP6 to address list."));
                    naList_6.append(*qnai);
                    v6IsSet = true;
                }

                else if (ip == QHostAddress::LocalHostIPv6)
                {
                // always listen on LocalHost
                    LOG(VB_GENERAL, LOG_DEBUG,
                            QString("Adding IPv6 loopback to address list."));
                    naList_6.append(*qnai);
                    if (!v6IsSet && (config_v6 == ip))
                        v6IsSet = true;
                }

                else if (ip.isInSubnet(kLinkLocal6) && allowLinkLocal)
                {
                    // optionally listen on linklocal
                    // the next clause will enable it anyway if no IP address
                    // has been set
                    LOG(VB_GENERAL, LOG_DEBUG,
                            QString("Adding link-local '%1' to address list.")
                                .arg(ip.toString()));
                    naList_6.append(*qnai);
                }

                else if (config_v6.isNull())
                {
                    if (ip.isInSubnet(kLinkLocal6))
                        LOG(VB_GENERAL, LOG_DEBUG,
                            QString("Adding link-local '%1' to address list.")
                                .arg(PRETTYIP_(ip)));
                    else
                        LOG(VB_GENERAL, LOG_DEBUG,
                            QString("Adding '%1' to address list.")
                                .arg(PRETTYIP_(ip)));

                    naList_6.append(*qnai);
                }

                else
                    LOG(VB_GENERAL, LOG_DEBUG, QString("Skipping address: %1")
                                .arg(PRETTYIP_(ip)));
            }
#endif
        }
    }

    if (!v4IsSet && (config_v4 != QHostAddress::LocalHost)
                 && !naList_4.isEmpty())
    {
        LOG(VB_GENERAL, LOG_CRIT, LOC + QString("Host is configured to listen "
                "on %1, but address is not used on any local network "
                "interfaces.").arg(config_v4.toString()));
    }

#if !defined(QT_NO_IPV6)
    if (!v6IsSet && (config_v6 != QHostAddress::LocalHostIPv6)
                 && !naList_6.isEmpty())
    {
        LOG(VB_GENERAL, LOG_CRIT, LOC + QString("Host is configured to listen "
                "on %1, but address is not used on any local network "
                "interfaces.").arg(PRETTYIP_(config_v6)));
    }
#endif

    // NOTE: there is no warning for the case where both defined addresses
    //       are localhost, and neither are found. however this would also
    //       mean there is no configured network at all, and should be
    //       sufficiently rare a case as to not worry about it.
}
void VisionReceiver::run() {
    QUdpSocket socket;

    // Create vision socket
    if (simulation) {
        // The simulator doesn't multicast its vision.  Instead, it sends to two
        // different ports.
        // Try to bind to the first one and, if that fails, use the second one.
        if (!socket.bind(SimVisionPort)) {
            if (!socket.bind(SimVisionPort + 1)) {
                throw runtime_error(
                    "Can't bind to either simulated vision port");
            }
        }
    } else {
        // Receive multicast packets from shared vision.
        if (!socket.bind(port, QUdpSocket::ShareAddress)) {
            throw runtime_error("Can't bind to shared vision port");
        }

        multicast_add(&socket, SharedVisionAddress);
    }

    // There should be at most four packets: one for each camera on each of two
    // frames, assuming some clock skew between this
    // computer and the vision computer.
    _packets.reserve(4);

    _running = true;
    while (_running) {
        char buf[65536];

        // Wait for a UDP packet
        if (!socket.waitForReadyRead(500)) {
            // Time out once in a while so the thread has a chance to exit
            continue;
        }

        QHostAddress host;
        quint16 portNumber = 0;
        qint64 size = socket.readDatagram(buf, sizeof(buf), &host, &portNumber);
        if (size < 1) {
            fprintf(stderr, "VisionReceiver: %s\n",
                    (const char*)socket.errorString().toLatin1());
            // See Processor for why we can't use QThread::msleep()
            ::usleep(100 * 1000);
            continue;
        }

        // FIXME - Verify that it is from the right host, in case there are
        // multiple visions on the network

        // Parse the protobuf message
        VisionPacket* packet = new VisionPacket;
        packet->receivedTime = timestamp();
        if (!packet->wrapper.ParseFromArray(buf, size)) {
            fprintf(stderr,
                    "VisionReceiver: got bad packet of %d bytes from %s:%d\n",
                    (int)size, (const char*)host.toString().toLatin1(),
                    portNumber);
            continue;
        }

        // Add to the vector of packets
        _mutex.lock();
        _packets.push_back(packet);
        _mutex.unlock();
    }
}
예제 #11
0
bool JDnsShared::addInterface(const QHostAddress &addr)
{
	if(shutting_down)
		return false;

	QString str;
	int index = instances.count();

	str = QString("attempting to use interface %1").arg(addr.toString());
	if(db)
		db->addDebug(dbname + QString::number(index), QStringList() << str);

	QJDns *jdns;

	if(mode == UnicastInternet || mode == UnicastLocal)
	{
		jdns = new QJDns(this);
		jdns_link(jdns);
		if(!jdns->init(QJDns::Unicast, addr))
		{
			doDebug(jdns, index);
			delete jdns;
			return false;
		}

		if(mode == UnicastLocal)
		{
			QJDns::NameServer host;
			host.address = QHostAddress("224.0.0.251");
			host.port = 5353;
			jdns->setNameServers(QList<QJDns::NameServer>() << host);
		}
	}
	else
	{
		// only one instance supported for now (see more in the
		//   comment below)
		if(!instances.isEmpty())
			return false;

		jdns = new QJDns(this);
		jdns_link(jdns);

		// instead of binding to the requested address, we'll bind
		//   to "Any".  this is because QJDns doesn't support
		//   multiple interfaces.  however, if that ever changes,
		//   we can update the code here and things should be mostly
		//   transparent to the user of JDnsShared.
		//if(!jdns->init(QJDns::Multicast, addr))
		if(!jdns->init(QJDns::Multicast, QHostAddress::Any))
		{
			doDebug(jdns, index);
			delete jdns;
			return false;
		}
	}

	Instance *i = new Instance;
	i->jdns = jdns;
	i->addr = addr;
	instances += i;

	if(mode == UnicastInternet)
		applyNameServers(i);

	str = QString("interface ready");
	if(db)
		db->addDebug(dbname + QString::number(index), QStringList() << str);

	return true;
}
예제 #12
0
void Widget::udpProcessPendingDatagrams()
{
    while (udpSocket->hasPendingDatagrams())
    {
        QHostAddress rAddr;
        quint16 rPort;
        QByteArray datagram;
        qint64 dataRead = 0;
        int datagramSize = udpSocket->pendingDatagramSize();
        datagram.resize(datagramSize);

        while(dataRead < datagram.size())
        {
            qint64 readNow = udpSocket->readDatagram(datagram.data()+dataRead, datagramSize, &rAddr, &rPort); // le +dataRead sur un tableau, ça décale le pointeur d'un offset de taille dataRead !
            if(readNow != -1)
            {
                dataRead += readNow; // Remember the total number of bytes read, so we know when to stop
                if (datagramSize > (datagram.size() - dataRead)) // Make sure we don't overflow
                    datagramSize = (datagram.size() - dataRead);
            }
            else
            {
                logStatusMessage(QString("Socket error : ").arg(udpSocket->errorString()));
                return;
            }
        }

        // Add player on connection
        if ((unsigned char)datagram[0]==MsgConnect && (unsigned char)datagram[1]==0
                && (unsigned char)datagram[2]==0 && datagram.size()>=22)
        {
            QString name = dataToString(datagram.right(datagram.size()-22));
            int nameFullSize = getVUint32Size(datagram.right(datagram.size()-22))+name.size();
            QString sesskey = dataToString(datagram.right(datagram.size()-22-nameFullSize));
            //logMessage(QString("UDP: Connect detected with name : ")+name);
            //logMessage(QString("UDP: Connect detected with sesskey : ")+sesskey);
            //logMessage(QString("UDP: Datagram was : ")+datagram.toHex());

            bool is_sesskey_valid = true;

            if (enableSessKeyValidation) {
                is_sesskey_valid = QCryptographicHash::hash(QString(sesskey.right(40) + saltPassword).toLatin1(),
                                                            QCryptographicHash::Md5).toHex() == sesskey.left(32);
            }

            if (is_sesskey_valid)
            {
                //logMessage("Sesskey token accepted");

                // Create new player if needed, else just update player
                Player* newPlayer = Player::findPlayer(udpPlayers, rAddr.toString(),rPort);
                if (newPlayer->IP != rAddr.toString()) // IP:Port not found in player list
                {
                    newPlayer->resetNetwork();
                    //newPlayer->connected = true; // Not really connected until we finish the handshake
                    newPlayer->name = name;
                    newPlayer->IP = rAddr.toString();
                    newPlayer->port = rPort;

                    // Check if we have too many players connected
                    int n=0;
                    for (int i=0;i<udpPlayers.size();i++)
                        if (udpPlayers[i]->connected)
                            n++;
                    if (n>=maxConnected)
                    {
                        sendMessage(newPlayer, MsgDisconnect, "Error : Too many players connected. Try again later.");
                    }
                    else
                        // If not add the player
                        udpPlayers << newPlayer;
                }
                else  // IP:Port found in player list
                {
                    if (newPlayer->connected) // TODO: Error, player already connected
                    {
                        sendMessage(newPlayer, MsgDisconnect, "Error : Player already connected.");
                        return;
                    }

                    // Check if we have too many players connected
                    int n=0;
                    for (int i=0;i<udpPlayers.size();i++)
                        if (udpPlayers[i]->connected)
                            n++;
                    if (n>=maxConnected)
                    {
                        sendMessage(newPlayer, MsgDisconnect, "Error : Too many players connected. Try again later.");
                    }

                    newPlayer->resetNetwork();
                    newPlayer->name = name;
                    newPlayer->IP = rAddr.toString();
                    newPlayer->port = rPort;
                    //newPlayer->connected = true; // We're not really connected until we finish the handshake
                }
            }
            else
            {
                QString badHash = QCryptographicHash::hash((QString(sesskey.right(40))
                                +saltPassword).toLatin1(), QCryptographicHash::Md5).toHex();
                logMessage("UDP: Sesskey rejected: got '"+badHash+"' instead of '"+sesskey.left(32)
                           +"', passhash was '"+QString(sesskey.right(40)));
                Player* newPlayer = new Player;
                newPlayer->IP = rAddr.toString();
                newPlayer->port = rPort;
                sendMessage(newPlayer, MsgDisconnect, "Error : Wrong sesskey hash.");
                return;
            }
        }

        Player* player = Player::findPlayer(udpPlayers, rAddr.toString(), rPort);
        if (player->IP == rAddr.toString() && player->port == rPort)
        {
            // Acquire datas
            player->receivedDatas->append(datagram);

            // Process data
            receiveMessage(player);
        }
        else // You need to connect with TCP first
        {
            logMessage("UDP: Request from unknown peer rejected : "+rAddr.toString()+":"+QString().setNum(rPort));
            // Send disconnect message manually
            QString data("You're not connected, please login first. (aka the server has no idea who the hell you are)");
            QByteArray msg(6,0);
            msg[0] = MsgDisconnect;
            msg[3] = (quint8)(((data.size()+1)*8)&0xFF);
            msg[4] = (quint8)((((data.size()+1)*8)>>8)&0xFF);
            msg[5] = (quint8)data.size();
            msg += data;
            win.udpSocket->writeDatagram(msg,rAddr,rPort);
        }
    }
}
예제 #13
0
#include "DdeFaceTracker.h"
#include "FaceshiftConstants.h"
#include "InterfaceLogging.h"
#include "Menu.h"


static const QHostAddress DDE_SERVER_ADDR("127.0.0.1");
static const quint16 DDE_SERVER_PORT = 64204;
static const quint16 DDE_CONTROL_PORT = 64205;
#if defined(Q_OS_WIN)
static const QString DDE_PROGRAM_PATH = "/dde/dde.exe";
#elif defined(Q_OS_MAC)
static const QString DDE_PROGRAM_PATH = "/dde.app/Contents/MacOS/dde";
#endif
static const QStringList DDE_ARGUMENTS = QStringList() 
    << "--udp=" + DDE_SERVER_ADDR.toString() + ":" + QString::number(DDE_SERVER_PORT) 
    << "--receiver=" + QString::number(DDE_CONTROL_PORT)
    << "--headless";

static const int NUM_EXPRESSIONS = 46;
static const int MIN_PACKET_SIZE = (8 + NUM_EXPRESSIONS) * sizeof(float) + sizeof(int);
static const int MAX_NAME_SIZE = 31;

// There's almost but not quite a 1-1 correspondence between DDE's 46 and Faceshift 1.3's 48 packets.
// The best guess at mapping is to:
// - Swap L and R values
// - Skip two Faceshift values: JawChew (22) and LipsLowerDown (37)
static const int DDE_TO_FACESHIFT_MAPPING[] = {
    1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14,
    16,
    18, 17,
예제 #14
0
파일: main.cpp 프로젝트: microe/mythtv
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QHostAddress address = QHostAddress::Broadcast;
    unsigned short port = 6948;

    QString message = kMessage;

    bool verbose = false;

    if (a.argc() == 0)
    {
        printHelp();
        return GENERIC_EXIT_OK;
    }

    for (int argpos = 1; argpos < a.argc(); ++argpos)
    {
        QString arg = a.argv()[argpos];

        if (arg.startsWith("-h") || arg.startsWith("--help"))
        {
            printHelp();
            return GENERIC_EXIT_OK;
        }
    }

    for (int argpos = 1; argpos < a.argc(); ++argpos)
    {
        QString arg = a.argv()[argpos];

        if (arg.startsWith("--help") || arg.startsWith("--template"))
            continue;

        if (arg.startsWith("--verbose"))
        {
            verbose = true;
            continue;
        }

        if (arg.startsWith("--udpport"))
        {
            port = arg.section("=", 1).toUShort();
            if (port == 0)
                port = 6948;
            continue;
        }

        if (arg.startsWith("--bcastaddr"))
        {
            QString newaddr = arg.section("=", 1);
            if (!newaddr.isEmpty())
                address.setAddress(newaddr);
            continue;
        }

        QString name = arg.section("=", 0, 0);
        name.replace("--", "");

        QString value = QString::fromLocal8Bit(
            arg.section("=", 1).toLocal8Bit());
        if (verbose)
        {
            QByteArray tmp_name  = name.toLocal8Bit();
            QByteArray tmp_value = value.toLocal8Bit();
            cerr << "name: " << tmp_name.constData()
                 << " -- value: " << tmp_value.constData() << endl;
        }

        name.append("%");
        name.prepend("%");

        message.replace(name, value);
    }

    if (verbose)
    {
        QByteArray tmp_message  = message.toLocal8Bit();
        cout << "output:\n" << tmp_message.constData() << endl;
    }

    QUdpSocket *sock = new QUdpSocket();
    QByteArray utf8 = message.toUtf8();
    int size = utf8.length();

    if (sock->writeDatagram(utf8.constData(), size, address, port) < 0)
    {
        VERBOSE(VB_IMPORTANT, "Failed to send UDP/XML packet");
    }
    else
    {
        cout << "Sent UDP/XML packet to IP "
             << address.toString().toLocal8Bit().constData()
             << " and port: " << port << endl;
    }

    sock->deleteLater();
   
    return GENERIC_EXIT_OK;
}
예제 #15
0
const QByteArray Auth::calculateAuthKey()
{
    QSqlDatabase db = QSqlDatabase::database ( m_db );

    bool ok = false;
    QSqlQuery query(db);

    ok = query.exec( QString("SELECT Value from Config where Name = 'ZM_AUTH_HASH_SECRET'") );
    if (!ok || !query.next()) {
        qDebug("Hash Error: error getting zm_auth_hash_secret from db %s", qPrintable(query.lastError().text()));
        return QByteArray();
    }

    QString auth_key = query.value(0).toString(); // HASH Secret

    ok = query.exec( QString("SELECT Value from Config where Name = 'ZM_AUTH_HASH_IPS'") );
    if (!ok || !query.next()) {
        qDebug("Hash Error: error getting zm_auth_hash_ips from db %s", qPrintable(query.lastError().text()));
        return QByteArray();
    }

    bool use_remote_addr = query.value(0).toBool(); // Include remote addr?

    ok = query.exec( QString("SELECT now()") );
    if (!ok || !query.next()) {
        qDebug("Hash Error: Can not read Server Time. now() function doesn't work %s",
               qPrintable(query.lastError().text()));
        return QByteArray();
    }

    QDateTime dateTime = query.value(0).toDateTime();

    auth_key += m_userName;
    auth_key += m_hashPassword;

    if ( use_remote_addr )
    {
        QTcpSocket socket;
        socket.connectToHost( db.hostName(), ConnectionManager::connectionWebPort( m_db ), QIODevice::ReadOnly );
        //if we can get ip address from the socket in 3000 ms
        if ( socket.waitForConnected( 3000 ) ){
            auth_key += socket.localAddress().toString();
        } else {
            //else try with HostInfo
            QHostInfo hinfo = QHostInfo::fromName ( QHostInfo::localHostName()  );
            QHostInfo checkLocalHost = QHostInfo::fromName ( db.hostName()  );
            if ( ! checkLocalHost.addresses().isEmpty() )
                if ( checkLocalHost.addresses().first().toString() == "127.0.0.1" ) hinfo = checkLocalHost;

            if ( !hinfo.addresses().isEmpty() )
            {
                //TODO: fix this. Use the correct interface address and not the first
                QHostAddress address = hinfo.addresses().first();
                auth_key += address.toString();
            }
        }
    }

    dateTime = dateTime.toTimeSpec( Qt::LocalTime );
    auth_key += QString::number( dateTime.time().hour() ); //hour
    auth_key += QString::number( dateTime.date().day() ); //day of month
    auth_key += QString::number( dateTime.date().month() -1 ); //month
    auth_key += QString::number( dateTime.date().year() - 1900 ); //years since 1900

    qDebug ( qPrintable("authkey: " + auth_key) );

    QByteArray ret = QCryptographicHash::hash( auth_key.toUtf8(), QCryptographicHash::Md5 );
    //qDebug ( qPrintable(QString (auth_key.toUtf8())) );
    qDebug ( qPrintable("authkey hex: " + ret.toHex()) );

    m_authKey = ret.toHex();
    return m_authKey;
}
예제 #16
0
bool
Servent::startListening( QHostAddress ha, bool upnp, int port, Tomahawk::Network::ExternalAddress::Mode mode, int defaultPort, bool autoDetectExternalIp, const QString& externalHost, int externalPort )
{
    Q_D( Servent );

    d->externalAddresses = QList<QHostAddress>();
    d->port = port;

    // Listen on both the selected port and, if not the same, the default port -- the latter sometimes necessary for zeroconf
    // TODO: only listen on both when zeroconf sip is enabled
    // TODO: use a real zeroconf system instead of a simple UDP broadcast?
    if ( !listen( ha, d->port ) )
    {
        if ( d->port != defaultPort )
        {
            if ( !listen( ha, defaultPort ) )
            {
                tLog() << Q_FUNC_INFO << "Failed to listen on both port" << d->port << "and port" << defaultPort;
                tLog() << Q_FUNC_INFO << "Error string is:" << errorString();
                return false;
            }
            else
                d->port = defaultPort;
        }
    }

    d->externalListenAll = false;

    if ( ha == QHostAddress::Any || ha == QHostAddress::AnyIPv6 )
    {
        // We are listening on all available addresses, so we should send a SipInfo for all of them.
        d->externalAddresses = QNetworkInterface::allAddresses();
        cleanAddresses( d->externalAddresses );
        tLog( LOGVERBOSE ) << Q_FUNC_INFO << "Listening to" << d->externalAddresses;
        d->externalListenAll = true;
    }
    else if ( ( ha.toString() != "127.0.0.1" ) && ( ha.toString() != "::1" ) && ( ha.toString() != "::7F00:1" ) )
    {
        // We listen only to one specific Address, only announce this.
        d->externalAddresses.append( ha );
    }
    // If we only accept connections via localhost, we'll announce nothing.

    tLog( LOGVERBOSE ) << Q_FUNC_INFO << "Servent listening on port" << d->port
                       << "using address" << ha.toString()
                       << "- servent thread:" << thread()
                       << "- address mode:" << (int)( mode );

    switch ( mode )
    {
        case Tomahawk::Network::ExternalAddress::Static:
            d->externalPort = externalPort;
            if ( autoDetectExternalIp )
            {
                QNetworkReply* reply = Tomahawk::Utils::nam()->get( QNetworkRequest( QUrl( "http://toma.hk/?stat=1" ) ) );
                connect( reply, SIGNAL( finished() ), SLOT( ipDetected() ) );
                // Not emitting ready here as we are not done.
            }
            else
            {
                d->externalHostname = externalHost;
                d->ready = true;
                // All setup is made, were done.
                emit ready();
            }
            break;

        case Tomahawk::Network::ExternalAddress::Lan:
            // Nothing has to be done here.
            d->ready = true;
            emit ready();
            break;

        case Tomahawk::Network::ExternalAddress::Upnp:
            if ( upnp )
            {
                // upnp could be turned off on the cli with --noupnp
                tLog( LOGVERBOSE ) << Q_FUNC_INFO << "External address mode set to upnp...";
                d->portfwd = QPointer< PortFwdThread >( new PortFwdThread( d->port ) );
                Q_ASSERT( d->portfwd );
                connect( d->portfwd.data(), SIGNAL( externalAddressDetected( QHostAddress, unsigned int ) ),
                                      SLOT( setExternalAddress( QHostAddress, unsigned int ) ) );
                d->portfwd.data()->start();
            }
            else
            {
                d->ready = true;
                emit ready();
            }
            break;
    }
예제 #17
0
bool Myth::SendNotification( bool  bError,
                             const QString &Type,
                             const QString &sMessage,
                             const QString &sOrigin,
                             const QString &sDecription,
                             const QString &sImage,
                             const QString &sExtra,
                             const QString &sProgressText,
                             float fProgress,
                             int   Duration,
                             bool  bFullscreen,
                             uint  Visibility,
                             uint  Priority,
                             const QString &sAddress,
                             int   udpPort )
{
    bool bResult = false;

    if (sMessage.isEmpty())
        return bResult;

    if (Duration < 0 || Duration > 999)
        Duration = -1;

    QString xmlMessage =
        "<mythnotification version=\"1\">\n"
        "  <text>" + sMessage + "</text>\n"
        "  <origin>" + (sOrigin.isNull() ? tr("MythServices") : sOrigin) + "</origin>\n"
        "  <description>" + sDecription + "</description>\n"
        "  <timeout>" + QString::number(Duration) + "</timeout>\n"
        "  <image>" + sImage + "</image>\n"
        "  <extra>" + sExtra + "</extra>\n"
        "  <progress_text>" + sProgressText + "</progress_text>\n"
        "  <progress>" + QString::number(fProgress) + "</progress>\n"
        "  <fullscreen>" + (bFullscreen ? "true" : "false") + "</fullscreen>\n"
        "  <visibility>" + QString::number(Visibility) + "</visibility>\n"
        "  <priority>" + QString::number(Priority) + "</priority>\n"
        "  <type>" + (bError ? "error" : Type) + "</type>\n"
        "</mythnotification>";

    QHostAddress address = QHostAddress::Broadcast;
    unsigned short port = 6948;

    if (!sAddress.isEmpty())
        address.setAddress(sAddress);

    if (udpPort != 0)
        port = udpPort;

    QUdpSocket *sock = new QUdpSocket();
    QByteArray utf8 = xmlMessage.toUtf8();
    int size = utf8.length();

    if (sock->writeDatagram(utf8.constData(), size, address, port) < 0)
    {
        LOG(VB_GENERAL, LOG_ERR,
            QString("Failed to send UDP/XML packet (Notification: %1 "
                    "Address: %2 Port: %3")
                .arg(sMessage).arg(sAddress).arg(port));
    }
    else
    {
        LOG(VB_GENERAL, LOG_DEBUG,
            QString("UDP/XML packet sent! (Notification: %1 Address: %2 Port: %3")
                .arg(sMessage)
                .arg(address.toString().toLocal8Bit().constData()).arg(port));
        bResult = true;
    }

    sock->deleteLater();

    return bResult;
}
예제 #18
0
파일: main.cpp 프로젝트: StefanRoss/mythtv
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QCoreApplication::setApplicationName("mythmessage");

    QHostAddress address = QHostAddress::Broadcast;
    unsigned short port = 6948;

    QString message = kMessage;

    bool verbose = false;

    MythMessageCommandLineParser cmdline;
    if (!cmdline.Parse(argc, argv))
    {
        cmdline.PrintHelp();
        return GENERIC_EXIT_INVALID_CMDLINE;
    }

    if (cmdline.toBool("showhelp"))
    {
        cmdline.PrintHelp();
        return GENERIC_EXIT_OK;
    }

    if (cmdline.toBool("showversion"))
    {
        cmdline.PrintVersion();
        return GENERIC_EXIT_OK;
    }

    if (cmdline.toBool("printtemplate"))
    {
        cerr << kMessage.toLocal8Bit().constData() << endl;
        return GENERIC_EXIT_OK;
    }

    if (cmdline.toBool("verbose"))
        verbose = true;
    if (cmdline.toBool("port"))
        port = (unsigned short)cmdline.toUInt("port");
    if (cmdline.toBool("addr"))
        address.setAddress(cmdline.toString("addr"));

    QMap<QString,QString>::const_iterator i;
    QMap<QString,QString> extras = cmdline.GetExtra();
    for (i = extras.begin(); i != extras.end(); ++i)
    {
        QString name = i.key();
        QString value = i.value();

        name.replace("--", "");
        if (verbose)
            cerr << "name: " << name.toLocal8Bit().constData()
                 << " -- value: " << value.toLocal8Bit().constData() << endl;

        name.append("%");
        name.prepend("%");
        message.replace(name, value);
    }

    if (verbose)
        cout << "output:\n" << message.toLocal8Bit().constData() << endl;

    QUdpSocket *sock = new QUdpSocket();
    QByteArray utf8 = message.toUtf8();

    if (sock->writeDatagram(utf8, address, port) < 0)
    {
        cout << "Failed to send UDP/XML packet" << endl;
    }
    else
    {
        cout << "Sent UDP/XML packet to IP "
             << address.toString().toLocal8Bit().constData()
             << " and port: " << port << endl;
    }

    sock->deleteLater();
   
    return GENERIC_EXIT_OK;
}
예제 #19
0
bool QtUdpSocket::init(QtUdpSocketType type, const QHostAddress  &address)
{
    struct in_addr iface_addr;
    struct ip_mreq mreq;
    bool boolean = true;
    quint8 ttl = 4;
    int res;

    /* Enable broadcasting */
    res = setsockopt(socketDescriptor(),
                     SOL_SOCKET,
                     SO_BROADCAST,
                     &boolean,
                     sizeof(boolean));
    if(res == -1)
        return false;

    /* TTL */
    res = setsockopt(socketDescriptor(),
                     IPPROTO_IP,
                     IP_MULTICAST_TTL,
                     &ttl,
                     sizeof(ttl));
    if(res == -1)
        return false;

    res = inet_aton(address.toString().toAscii().data(), &iface_addr);
    if(res == 0)
        return false;

    /* Set up additional things according to the type of socket desired */
    if(type == Multicast) {
        /* Enable multicast loopback */
        res = setsockopt(socketDescriptor(),
                         IPPROTO_IP,
                         IP_MULTICAST_LOOP,
                         &boolean,
                         sizeof(boolean));
        if(res == -1)
            return false;

        /* Set the interface */
        res = setsockopt(socketDescriptor(),
                         IPPROTO_IP,
                         IP_MULTICAST_IF,
                         &iface_addr,
                         sizeof(struct in_addr));
        if(res == -1)
            return false;

        /* Subscribe to multicast channel */
        res = inet_aton(SSDP_ADDR, &(mreq.imr_multiaddr));
        if(res == 0)
            return false;

        memcpy(&(mreq.imr_interface),
               &iface_addr,
               sizeof(struct in_addr));

        res = setsockopt(socketDescriptor(),
                         IPPROTO_IP,
                         IP_ADD_MEMBERSHIP,
                         &mreq,
                         sizeof(mreq));
        if(res == -1)
            return false;

        /* Bind to SSDP multicast port and address */
        /* Allow multiple sockets to use the same PORT number */
        if(!(bind(QHostAddress(SSDP_ADDR), SSDP_PORT, QUdpSocket::ShareAddress)))
            return false;
    } else {
        /* Bind to selected host address, system allocates the port number*/
        if(!(bind(address, 0)))
            return false;
    }

    return true;
}
예제 #20
0
void ARControlConnection::onReadyRead()
{
    Q_D(ARControlConnection);

    while(d->d2c->hasPendingDatagrams())
    {
        QHostAddress remoteAddr;
        quint16      remotePort;

        // If we've not received enough data, then return and wait for more.
        if(d->d2c->pendingDatagramSize() < ARNETWORK_FRAME_HEADER_SIZE) break;

        QByteArray datagram(d->d2c->pendingDatagramSize(), 0x00);
        quint32 offset = 0;

        d->d2c->readDatagram(datagram.data(), datagram.size(), &remoteAddr, &remotePort);

        while(offset < datagram.size())
        {
            ARControlFrame frame;
            frame.type = static_cast<quint8>(datagram[offset + 0]);
            frame.id = static_cast<quint8>(datagram[offset + 1]);
            frame.seq = static_cast<quint8>(datagram[offset + 2]);
            frame.size = qFromLittleEndian(*((quint32*)(datagram.constData() + offset + 3)));

            // Copy datagram data to frame if the frame size is larger than just the header.
            if(frame.size > ARNETWORK_FRAME_HEADER_SIZE)
            {
                const char *data = datagram.constData();
                frame.payload.insert(0, data + offset + ARNETWORK_FRAME_HEADER_SIZE, frame.size - ARNETWORK_FRAME_HEADER_SIZE);
            }

            // Output comms debug info (if it's not a video data frame).
            if(frame.id != ARNET_D2C_VIDEO_DATA_ID)
            {
                DEBUG_T(QString("<< %1:%2 [%3]")
                        .arg(remoteAddr.toString())
                        .arg(remotePort)
                        .arg(QString(datagram.toHex())));
            }

            // Process frame depending on buffer id.
            if(frame.id == ARNET_D2C_PING_ID)
            {
                onPing(frame);
            }
            else if(frame.id == ARNET_D2C_EVENT_ID || frame.id == ARNET_D2C_NAVDATA_ID)
            {
                onNavdata(frame);
            }
            else if(frame.id == ARNET_D2C_VIDEO_DATA_ID)
            {
                onVideoData(frame);
            }
            else
            {
                WARNING_T(QString("Unhandled frame id: %1").arg(frame.id));
            }

            // Increment datagram offset to continue processing next frame.
            offset += frame.size;
        }
    }
}
예제 #21
0
        bool UPnPRouter::forward(const QHostAddress & host, quint16 port, QAbstractSocket::SocketType proto)
        {
            qDebug() << "Forwarding port " << host.toString() << port << " (" << (proto == QAbstractSocket::TcpSocket ? "TCP" : "UDP") << ")" << endl;

            if (service.ready)
            {
                // add all the arguments for the command
                QList<SOAP::Arg> args;
                SOAP::Arg a;
                a.element = "NewRemoteHost";
                args.append(a);

                // the external port
                a.element = "NewExternalPort";
                a.value = QString::number(port);
                args.append(a);

                // the protocol
                a.element = "NewProtocol";
                a.value = proto == QAbstractSocket::TcpSocket ? "TCP" : "UDP";
                args.append(a);

                // the local port
                a.element = "NewInternalPort";
                a.value = QString::number(port);
                args.append(a);

                // the local IP address
                a.element = "NewInternalClient";
                a.value = host.toString();
                args.append(a);

                a.element = "NewEnabled";
                a.value = '1';
                args.append(a);

                a.element = "NewPortMappingDescription";
                a.value = QString("Konversation UPNP");
                args.append(a);

                a.element = "NewLeaseDuration";
                a.value = '0';
                args.append(a);

                QString action = "AddPortMapping";
                QString comm = SOAP::createCommand(action,service.servicetype,args);

                Forwarding *forward = new Forwarding;

                forward->port = port;
                forward->host = host;
                forward->proto = proto;

                if (KJob *req = sendSoapQuery(comm,service.servicetype + '#' + action,service.controlurl))
                {
                    // erase old forwarding if one exists
                    // The UPnP spec states if an IGD receives a forward request that matches an existing request that it must accept it.
                    QListIterator<Forwarding*> itr(forwards);
                    while (itr.hasNext())
                    {
                        Forwarding *check = itr.next();

                        if (check->port == forward->port && check->host == forward->host && check->proto == forward->proto)
                        {
                            forwards.removeAll(check);
                            delete check;
                        }
                    }

                    forwards.append(forward);
                    pending_forwards[req] = forward;

                    return true;
                }

                qDebug() << "Forwarding Failed: Failed to send SOAP query.";
                delete forward;
            }

            qDebug() << "Forwarding Failed: No UPnP Service.";
            return false;
        }
예제 #22
0
void E131Controller::processPendingPackets()
{
    while (m_UdpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        QHostAddress senderAddress;
        datagram.resize(m_UdpSocket->pendingDatagramSize());
        m_UdpSocket->readDatagram(datagram.data(), datagram.size(), &senderAddress);
        if (senderAddress != m_ipAddr)
        {
            qDebug() << "Received packet with size: " << datagram.size() << ", host: " << senderAddress.toString();
            if (m_packetizer->checkPacket(datagram) == true)
            {
                QByteArray dmxData;
                quint32 universe;
                if (this->type() == Input)
                {
                    m_packetReceived++;
                    if (m_packetizer->fillDMXdata(datagram, dmxData, universe) == true)
                    {
                        if (universe >= (quint32)m_inputRefCount)
                            break;

                        quint32 uniAddr = universe << 9;
                        for (quint32 i = 0; i < (quint32)dmxData.length(); i++)
                        {
                            if (m_dmxValues.at(uniAddr + i) != dmxData.at(i))
                            {
                                m_dmxValues[uniAddr + i] =  dmxData[i];
                                emit valueChanged(universe, m_line, i, (uchar)dmxData.at(i));
                            }
                        }
                    }
                }
            }
        }
    }
}
예제 #23
0
void Settings::ShowIP(QHostAddress IP)
{
    ui->lbIP->setText(QString("Ваш IP: %1").arg(IP.toString()));
}
QString CreateUdpDataReceiverMapKey(const QHostAddress &address, quint16 port)
{
	return address.toString() + QString(":") + QString::number(port);
}
예제 #25
0
파일: udp_server.cpp 프로젝트: lgosha/ssd
void UDPServer::sendAnswer( pAnswer & _pa, QHostAddress src_host, uint id )
{
	char data[65536];
	int len;
	_pa.getDatagram(data, &len);

	QByteArray datagram(data, len);
	m_pobjUDPOutSocket->writeDatagram(datagram.data(), datagram.size(), src_host, m_mapClientsInfo[id].m_mapAddrs[ src_host.toString() ] );
}
예제 #26
0
bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &addr, quint16 port)
{
    struct sockaddr_in sockAddrIPv4;
    struct sockaddr *sockAddrPtr = 0;
    QT_SOCKLEN_T sockAddrSize = 0;

#if !defined(QT_NO_IPV6)
    struct sockaddr_in6 sockAddrIPv6;

    if (addr.protocol() == QAbstractSocket::IPv6Protocol) {
        memset(&sockAddrIPv6, 0, sizeof(sockAddrIPv6));
        sockAddrIPv6.sin6_family = AF_INET6;
        sockAddrIPv6.sin6_port = htons(port);
#ifndef QT_NO_IPV6IFNAME
        sockAddrIPv6.sin6_scope_id = ::if_nametoindex(addr.scopeId().toLatin1().data());
#else
        sockAddrIPv6.sin6_scope_id = addr.scopeId().toInt();
#endif
        Q_IPV6ADDR ip6 = addr.toIPv6Address();
        memcpy(&sockAddrIPv6.sin6_addr.s6_addr, &ip6, sizeof(ip6));

        sockAddrSize = sizeof(sockAddrIPv6);
        sockAddrPtr = (struct sockaddr *) &sockAddrIPv6;
    } else
#if 0
    {}
#endif
#endif
    if (addr.protocol() == QAbstractSocket::IPv4Protocol) {
        memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4));
        sockAddrIPv4.sin_family = AF_INET;
        sockAddrIPv4.sin_port = htons(port);
        sockAddrIPv4.sin_addr.s_addr = htonl(addr.toIPv4Address());

        sockAddrSize = sizeof(sockAddrIPv4);
        sockAddrPtr = (struct sockaddr *) &sockAddrIPv4;
    } else {
        // unreachable
    }

    int connectResult = QT_SOCKET_CONNECT(socketDescriptor, sockAddrPtr, sockAddrSize);
    if (connectResult == -1) {
        switch (errno) {
        case EISCONN:
            socketState = QAbstractSocket::ConnectedState;
            break;
        case ECONNREFUSED:
        case EINVAL:
            setError(QAbstractSocket::ConnectionRefusedError, ConnectionRefusedErrorString);
            socketState = QAbstractSocket::UnconnectedState;
            break;
        case ETIMEDOUT:
            setError(QAbstractSocket::NetworkError, ConnectionTimeOutErrorString);
            break;
        case EHOSTUNREACH:
            setError(QAbstractSocket::NetworkError, HostUnreachableErrorString);
            socketState = QAbstractSocket::UnconnectedState;
            break;
        case ENETUNREACH:
            setError(QAbstractSocket::NetworkError, NetworkUnreachableErrorString);
            socketState = QAbstractSocket::UnconnectedState;
            break;
        case EADDRINUSE:
            setError(QAbstractSocket::NetworkError, AddressInuseErrorString);
            break;
        case EINPROGRESS:
        case EALREADY:
            setError(QAbstractSocket::UnfinishedSocketOperationError, InvalidSocketErrorString);
            socketState = QAbstractSocket::ConnectingState;
            break;
        case EAGAIN:
            setError(QAbstractSocket::UnfinishedSocketOperationError, InvalidSocketErrorString);
            setError(QAbstractSocket::SocketResourceError, ResourceErrorString);
            break;
        case EACCES:
        case EPERM:
            setError(QAbstractSocket::SocketAccessError, AccessErrorString);
            socketState = QAbstractSocket::UnconnectedState;
            break;
        case EAFNOSUPPORT:
        case EBADF:
        case EFAULT:
        case ENOTSOCK:
            socketState = QAbstractSocket::UnconnectedState;
        default:
            break;
        }

        if (socketState != QAbstractSocket::ConnectedState) {
#if defined (QNATIVESOCKETENGINE_DEBUG)
            qDebug("QNativeSocketEnginePrivate::nativeConnect(%s, %i) == false (%s)",
                   addr.toString().toLatin1().constData(), port,
                   socketState == QAbstractSocket::ConnectingState
                   ? "Connection in progress" : socketErrorString.toLatin1().constData());
#endif
            return false;
        }
    }

#if defined (QNATIVESOCKETENGINE_DEBUG)
    qDebug("QNativeSocketEnginePrivate::nativeConnect(%s, %i) == true",
           addr.toString().toLatin1().constData(), port);
#endif

    socketState = QAbstractSocket::ConnectedState;
    return true;
}
예제 #27
0
파일: UDTTest.cpp 프로젝트: cozza13/hifi
UDTTest::UDTTest(int& argc, char** argv) :
    QCoreApplication(argc, argv)
{
    qInstallMessageHandler(LogHandler::verboseMessageHandler);
    
    parseArguments();
    
    // randomize the seed for packet size randomization
    srand(time(NULL));

    _socket.bind(QHostAddress::AnyIPv4, _argumentParser.value(PORT_OPTION).toUInt());
    qDebug() << "Test socket is listening on" << _socket.localPort();
    
    if (_argumentParser.isSet(TARGET_OPTION)) {
        // parse the IP and port combination for this target
        QString hostnamePortString = _argumentParser.value(TARGET_OPTION);
        
        QHostAddress address { hostnamePortString.left(hostnamePortString.indexOf(':')) };
        quint16 port { (quint16) hostnamePortString.mid(hostnamePortString.indexOf(':') + 1).toUInt() };
        
        if (address.isNull() || port == 0) {
            qCritical() << "Could not parse an IP address and port combination from" << hostnamePortString << "-" <<
                "The parsed IP was" << address.toString() << "and the parsed port was" << port;
            
            QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection);
        } else {
            _target = HifiSockAddr(address, port);
            qDebug() << "Packets will be sent to" << _target;
        }
    }
    
    if (_argumentParser.isSet(PACKET_SIZE)) {
        // parse the desired packet size
        _minPacketSize = _maxPacketSize = _argumentParser.value(PACKET_SIZE).toInt();
        
        if (_argumentParser.isSet(MIN_PACKET_SIZE) || _argumentParser.isSet(MAX_PACKET_SIZE)) {
            qCritical() << "Cannot set a min packet size or max packet size AND a specific packet size.";
            QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection);
        }
    } else {
        
        bool customMinSize = false;
        
        if (_argumentParser.isSet(MIN_PACKET_SIZE)) {
            _minPacketSize = _argumentParser.value(MIN_PACKET_SIZE).toInt();
            customMinSize = true;
        }
        
        if (_argumentParser.isSet(MAX_PACKET_SIZE)) {
            _maxPacketSize = _argumentParser.value(MAX_PACKET_SIZE).toInt();
            
            // if we don't have a min packet size we should make it 1, because we have a max
            if (customMinSize) {
                _minPacketSize = 1;
            }
        }
        
        if (_maxPacketSize < _minPacketSize) {
            qCritical() << "Cannot set a max packet size that is smaller than the min packet size.";
            QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection);
        }
    }
    
    if (_argumentParser.isSet(MAX_SEND_BYTES)) {
        _maxSendBytes = _argumentParser.value(MAX_SEND_BYTES).toInt();
    }
    
    if (_argumentParser.isSet(MAX_SEND_PACKETS)) {
        _maxSendPackets = _argumentParser.value(MAX_SEND_PACKETS).toInt();
    }
    
    if (_argumentParser.isSet(UNRELIABLE_PACKETS)) {
        _sendReliable = false;
    }

    if (_argumentParser.isSet(ORDERED_PACKETS)) {
        _sendOrdered = true;
    }
    
    if (_argumentParser.isSet(MESSAGE_SIZE)) {
        if (_argumentParser.isSet(ORDERED_PACKETS)) {
            static const double BYTES_PER_MEGABYTE = 1000000;
            _messageSize = (int) _argumentParser.value(MESSAGE_SIZE).toInt() * BYTES_PER_MEGABYTE;
            
            qDebug() << "Message size for ordered packet sending is" << QString("%1MB").arg(_messageSize / BYTES_PER_MEGABYTE);
        } else {
            qWarning() << "message-size has no effect if not sending ordered - it will be ignored";
        }
    }
    
    
    // in case we're an ordered sender or receiver setup our random number generator now
    static const int FIRST_MESSAGE_SEED = 742272;
    
    int messageSeed = FIRST_MESSAGE_SEED;
    
    if (_argumentParser.isSet(MESSAGE_SEED)) {
        messageSeed = _argumentParser.value(MESSAGE_SEED).toInt();
    }
    
    // seed the generator with a value that the receiver will also use when verifying the ordered message
    _generator.seed(messageSeed);
    
    if (!_target.isNull()) {
        sendInitialPackets();
    } else {
        // this is a receiver - in case there are ordered packets (messages) being sent to us make sure that we handle them
        // so that they can be verified
        _socket.setMessageHandler(
            [this](std::unique_ptr<udt::Packet> packet) {
                auto messageNumber = packet->getMessageNumber();
                auto it = _pendingMessages.find(messageNumber);

                if (it == _pendingMessages.end()) {
                    auto message = std::unique_ptr<Message>(new Message { messageNumber, packet->readAll() });
                    message->data.reserve(_messageSize);
                    if (packet->getPacketPosition() == udt::Packet::ONLY) {
                        handleMessage(std::move(message));
                    } else {
                        _pendingMessages[messageNumber] = std::move(message);
                    }
                } else {
                    auto& message = it->second;
                    message->data.append(packet->readAll());

                    if (packet->getPacketPosition() == udt::Packet::LAST) {
                        handleMessage(std::move(message));
                        _pendingMessages.erase(it);
                    }
                }

        });
    }
    _socket.setMessageFailureHandler(
        [this](HifiSockAddr from, udt::Packet::MessageNumber messageNumber) {
            _pendingMessages.erase(messageNumber);
        }
    );
    
    // the sender reports stats every 100 milliseconds, unless passed a custom value
    
    if (_argumentParser.isSet(STATS_INTERVAL)) {
        _statsInterval = _argumentParser.value(STATS_INTERVAL).toInt();
    }
    
    QTimer* statsTimer = new QTimer(this);
    connect(statsTimer, &QTimer::timeout, this, &UDTTest::sampleStats);
    statsTimer->start(_statsInterval);
}
예제 #28
0
bool QNativeSocketEnginePrivate::nativeBind(const QHostAddress &address, quint16 port)
{
    struct sockaddr_in sockAddrIPv4;
    struct sockaddr *sockAddrPtr = 0;
    QT_SOCKLEN_T sockAddrSize = 0;

#if !defined(QT_NO_IPV6)
    struct sockaddr_in6 sockAddrIPv6;

    if (address.protocol() == QAbstractSocket::IPv6Protocol) {
        memset(&sockAddrIPv6, 0, sizeof(sockAddrIPv6));
        sockAddrIPv6.sin6_family = AF_INET6;
        sockAddrIPv6.sin6_port = htons(port);
#ifndef QT_NO_IPV6IFNAME
        sockAddrIPv6.sin6_scope_id = ::if_nametoindex(address.scopeId().toLatin1().data());
#else
        sockAddrIPv6.sin6_scope_id = address.scopeId().toInt();
#endif
        Q_IPV6ADDR tmp = address.toIPv6Address();
        memcpy(&sockAddrIPv6.sin6_addr.s6_addr, &tmp, sizeof(tmp));
        sockAddrSize = sizeof(sockAddrIPv6);
        sockAddrPtr = (struct sockaddr *) &sockAddrIPv6;
    } else
#endif
        if (address.protocol() == QAbstractSocket::IPv4Protocol) {
            memset(&sockAddrIPv4, 0, sizeof(sockAddrIPv4));
            sockAddrIPv4.sin_family = AF_INET;
            sockAddrIPv4.sin_port = htons(port);
            sockAddrIPv4.sin_addr.s_addr = htonl(address.toIPv4Address());
            sockAddrSize = sizeof(sockAddrIPv4);
            sockAddrPtr = (struct sockaddr *) &sockAddrIPv4;
        } else {
            // unreachable
        }

    int bindResult = QT_SOCKET_BIND(socketDescriptor, sockAddrPtr, sockAddrSize);
    if (bindResult < 0) {
        switch(errno) {
        case EADDRINUSE:
            setError(QAbstractSocket::AddressInUseError, AddressInuseErrorString);
            break;
        case EACCES:
            setError(QAbstractSocket::SocketAccessError, AddressProtectedErrorString);
            break;
        case EINVAL:
            setError(QAbstractSocket::UnsupportedSocketOperationError, OperationUnsupportedErrorString);
            break;
        case EADDRNOTAVAIL:
            setError(QAbstractSocket::SocketAddressNotAvailableError, AddressNotAvailableErrorString);
            break;
        default:
            break;
        }

#if defined (QNATIVESOCKETENGINE_DEBUG)
        qDebug("QNativeSocketEnginePrivate::nativeBind(%s, %i) == false (%s)",
               address.toString().toLatin1().constData(), port, socketErrorString.toLatin1().constData());
#endif

        return false;
    }

#if defined (QNATIVESOCKETENGINE_DEBUG)
    qDebug("QNativeSocketEnginePrivate::nativeBind(%s, %i) == true",
           address.toString().toLatin1().constData(), port);
#endif
    socketState = QAbstractSocket::BoundState;
    return true;
}
예제 #29
0
bool QNativeSocketEnginePrivate::nativeBind(const QHostAddress &a, quint16 port)
{
    QHostAddress address = a;
    switch (address.protocol()) {
    case QAbstractSocket::IPv6Protocol:
        if (address.toIPv6Address()[0] == 0xff) {
            // binding to a multicast address
            address = QHostAddress(QHostAddress::AnyIPv6);
        }
        break;
    case QAbstractSocket::IPv4Protocol:
        if ((address.toIPv4Address() & 0xffff0000) == 0xefff0000) {
            // binding to a multicast address
            address = QHostAddress(QHostAddress::Any);
        }
        break;
    default:
        break;
    }

    struct sockaddr_in sockAddrIPv4;
    qt_sockaddr_in6 sockAddrIPv6;
    struct sockaddr *sockAddrPtr = 0;
    QT_SOCKLEN_T sockAddrSize = 0;

    qt_socket_setPortAndAddress(socketDescriptor, &sockAddrIPv4, &sockAddrIPv6, port, address, &sockAddrPtr, &sockAddrSize);


    int bindResult = ::bind(socketDescriptor, sockAddrPtr, sockAddrSize);
    if (bindResult == SOCKET_ERROR) {
        int err = WSAGetLastError();
        WS_ERROR_DEBUG(err);
        switch (err) {
        case WSANOTINITIALISED:
            //###
            break;
        case WSAEADDRINUSE:
        case WSAEINVAL:
            setError(QAbstractSocket::AddressInUseError, AddressInuseErrorString);
            break;
        case WSAEACCES:
            setError(QAbstractSocket::SocketAccessError, AddressProtectedErrorString);
            break;
        case WSAEADDRNOTAVAIL:
            setError(QAbstractSocket::SocketAddressNotAvailableError, AddressNotAvailableErrorString);
            break;
        default:
            break;
        }

#if defined (QNATIVESOCKETENGINE_DEBUG)
        qDebug("QNativeSocketEnginePrivate::nativeBind(%s, %i) == false (%s)",
               address.toString().toLatin1().constData(), port, socketErrorString.toLatin1().constData());
#endif

        return false;
    }

#if defined (QNATIVESOCKETENGINE_DEBUG)
    qDebug("QNativeSocketEnginePrivate::nativeBind(%s, %i) == true",
           address.toString().toLatin1().constData(), port);
#endif
    socketState = QAbstractSocket::BoundState;
    return true;
}
예제 #30
0
/**
  * @brief Add a dns entry to the system's list of DNS resolvers.
  * @param resolver The IP address of teh resolver to add to the system
  * @param index resolver sequence (1..n)
  */
int OpenNICSystem::updateResolver(QHostAddress& resolver,int index,QString& output)
{
    int rc;
    QEventLoop loop;
    QString program = "netsh";
    QStringList arguments;
    if ( ++index == 1 ) /* on windows(tm) index starts at 1 */
    {
        arguments << "interface" << "ip" << "set" << "dns" << "Local Area Connection" << "static" << resolver.toString();
    }
    else
    {
        arguments << "interface" << "ip" << "add" << "dns" << "Local Area Connection" << resolver.toString() << "index="+QString::number(index);
    }
    QProcess* process = new QProcess();
    process->start(program, arguments);
    while (process->waitForFinished(10000))
    {
        loop.processEvents();
    }
    output = process->readAllStandardOutput().trimmed() + "\n";
    rc = process->exitCode();
    delete process;
    return rc;
}