void ReceiveThread::send(const char* buffer,int length) {
    if(socket.writeDatagram(buffer,length,QHostAddress(metisip),1024)<0) {
        qDebug()<<"Error: Discovery: writeDatagram failed "<<socket.errorString();
        return;
    }
}
Beispiel #2
0
void GyroDataWidget::on_le_ip_gyro_data_returnPressed()
{
	if(!m_model)
		return;
	m_model->set_address(QHostAddress(ui->le_ip_gyro_data->text()), ui->sb_gyro_data->value());
}
Beispiel #3
0
//----------------------------------------------------------------------------//
// runCmdParser()                                                             //
// 10ms after the application starts this method will parse all commands      //
//----------------------------------------------------------------------------//
void QCanDump::runCmdParser()
{
   //----------------------------------------------------------------
   // setup command line parser
   //
   clCmdParserP.setApplicationDescription(tr("Show messages of CAN interface"));
   clCmdParserP.addHelpOption();
   clCmdParserP.addVersionOption();

   
   //----------------------------------------------------------------
   // argument <interface> is required
   //
   clCmdParserP.addPositionalArgument("interface", 
                                      tr("CAN interface, e.g. can1"));

   //-----------------------------------------------------------
   // command line option: -H <host>
   //
   QCommandLineOption clOptHostT("H", 
         tr("Connect to <host>"),
         tr("host"));
   clCmdParserP.addOption(clOptHostT);

   //-----------------------------------------------------------
   // command line option: -n <count>
   //
   QCommandLineOption clOptCountT("n", 
         tr("Terminate after reception of <count> CAN frames"),
         tr("count"));
   clCmdParserP.addOption(clOptCountT);
   
   //-----------------------------------------------------------
   // command line option: -t 
   //
   QCommandLineOption clOptTimeStampT("t", 
         tr("Show time-stamp"));
   clCmdParserP.addOption(clOptTimeStampT);

   //-----------------------------------------------------------
   // command line option: -T 
   //
   QCommandLineOption clOptTimeOutT("T", 
         tr("Terminate after <msec> without reception"),
         tr("msec"),
         "0");
   clCmdParserP.addOption(clOptTimeOutT);


   //----------------------------------------------------------------
   // Process the actual command line arguments given by the user
   //
   clCmdParserP.process(*pclAppP);
   const QStringList clArgsT = clCmdParserP.positionalArguments();
   if (clArgsT.size() != 1) 
   {
      fprintf(stderr, "%s\n", 
              qPrintable(tr("Error: Must specify CAN interface.\n")));
      clCmdParserP.showHelp(0);
   }

   
   //----------------------------------------------------------------
   // test format of argument <interface>
   //
   QString clInterfaceT = clArgsT.at(0);
   if(!clInterfaceT.startsWith("can"))
   {
      fprintf(stderr, "%s %s\n", 
              qPrintable(tr("Error: Unknown CAN interface ")),
              qPrintable(clInterfaceT));
      clCmdParserP.showHelp(0);
   }
   
   //-----------------------------------------------------------
   // convert CAN channel to uint8_t value
   //
   QString clIfNumT = clInterfaceT.right(clInterfaceT.size() - 3);
   bool btConversionSuccessT;
   int32_t slChannelT = clIfNumT.toInt(&btConversionSuccessT, 10);
   if((btConversionSuccessT == false) ||
      (slChannelT == 0) )
   {
      fprintf(stderr, "%s \n\n", 
              qPrintable(tr("Error: CAN interface out of range")));
      clCmdParserP.showHelp(0);
   }
   
   //-----------------------------------------------------------
   // store CAN interface channel (CAN_Channel_e)
   //
   ubChannelP = (uint8_t) (slChannelT);

   
   //----------------------------------------------------------------
   // check for time-stamp
   //
   btTimeStampP = clCmdParserP.isSet(clOptTimeStampT);

   
   //----------------------------------------------------------------
   // check for termination options
   //
   btQuitNeverP = true;
   ulQuitCountP = clCmdParserP.value(clOptCountT).toInt(Q_NULLPTR, 10);    
   ulQuitTimeP  = clCmdParserP.value(clOptTimeOutT).toInt(Q_NULLPTR, 10);      
   if ((ulQuitCountP > 0) || (ulQuitTimeP > 0))
   {
      btQuitNeverP = false; 
   }
   
   
   //----------------------------------------------------------------
   // set host address for socket
   //
   if(clCmdParserP.isSet(clOptHostT))
   {
      QHostAddress clAddressT = QHostAddress(clCmdParserP.value(clOptHostT));
      clCanSocketP.setHostAddress(clAddressT);
   }
   
   //----------------------------------------------------------------
   // connect to CAN interface
   //
   clCanSocketP.connectNetwork((CAN_Channel_e) ubChannelP);

}
Beispiel #4
0
void Tunnelc::init()
{
    m_toxkit = new QToxKit("toxcli", true);
    QObject::connect(m_toxkit, &QToxKit::selfConnectionStatus, this,
                     &Tunnelc::onToxnetSelfConnectionStatus, Qt::QueuedConnection);
    QObject::connect(m_toxkit, &QToxKit::friendConnectionStatus, this,
                     &Tunnelc::onToxnetFriendConnectionStatus, Qt::QueuedConnection);
    QObject::connect(m_toxkit, &QToxKit::friendMessage, this,
                     &Tunnelc::onToxnetFriendMessage, Qt::QueuedConnection);
    QObject::connect(m_toxkit, &QToxKit::friendLossyPacket, this,
                     &Tunnelc::onToxnetFriendLossyPacket, Qt::QueuedConnection);
    QObject::connect(m_toxkit, &QToxKit::friendLosslessPacket, this,
                     &Tunnelc::onToxnetFriendLosslessPacket, Qt::QueuedConnection);
    m_toxkit->start();

    m_enpoll = new ENetPoll();
    QObject::connect(m_enpoll, &ENetPoll::connected, this, &Tunnelc::onENetPeerConnected, Qt::QueuedConnection);
    QObject::connect(m_enpoll, &ENetPoll::disconnected, this, &Tunnelc::onENetPeerDisconnected, Qt::QueuedConnection);
    QObject::connect(m_enpoll, &ENetPoll::packetReceived, this, &Tunnelc::onENetPeerPacketReceived, Qt::QueuedConnection);
    m_enpoll->start();

    ENetAddress enaddr = {ENET_HOST_ANY, 7766};
    enet_address_set_host(&enaddr, "127.0.0.1");
    enaddr.vaddr = SELF_FRIEND_NUMBER;
    ENetHost *encli = NULL;

    // m_encli = encli = enet_host_create(&enaddr, 932, 2, 0, 0);
    m_encli = encli = enet_host_create_notp(&enaddr, 932, 2, 0, 0);
    // encli->mtu = 1261;  // 在这设置无效 // ENET_HOST_DEFAULT_MTU=1400
    // m_encli = encli = enet_host_create(NULL, 1, 2, 0, 0);
    qDebug()<<encli<<encli->peerCount<<encli->mtu;
    encli->toxkit = this;
    encli->enet_socket_send = toxenet_socket_send;
    encli->enet_socket_receive = toxenet_socket_receive;
    // encli->compressor.context = (void*)0x1;
    // encli->compressor.compress = enet_simple_compress;
    // encli->compressor.decompress = enet_simple_decompress;
    // encli->compressor.destroy = enet_simple_destroy;
    // enet_host_compress(encli, this->createCompressor());

    
    // transport
    const ENetTransport *transport = this->createToxTransport();
    // m_transport.send = toxenet_socket_send;
    // m_transport.recv = toxenet_socket_receive;
    m_transport.enet_transport_send = toxenet_socket_send;
    m_transport.enet_transport_recv = toxenet_socket_receive;
    enet_host_transport(encli, transport);
    
    m_enpoll->addENetHost(encli);

    int idx = 0;
    foreach (const ToxTunRecord &rec, this->m_cfg->m_recs) {
        QTcpServer *tcpsrv = new QTcpServer();
        QObject::connect(tcpsrv, &QTcpServer::newConnection, this, &Tunnelc::onNewTcpConnection, Qt::QueuedConnection);

        tcpsrv->listen(QHostAddress("127.0.0.1"), rec.m_local_port);
        // tcpsrv->listen(QHostAddress::Any, 7766);
        this->m_tcpsrvs[tcpsrv] = idx++;
    }
}
QT_BEGIN_NAMESPACE

void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestName, const QHostAddress &nameserver, QDnsLookupReply *reply)
{
    // Perform DNS query.
    PDNS_RECORD dns_records = 0;
    const QString requestNameUtf16 = QString::fromUtf8(requestName.data(), requestName.size());
    IP4_ARRAY srvList;
    memset(&srvList, 0, sizeof(IP4_ARRAY));
    if (!nameserver.isNull()) {
        if (nameserver.protocol() == QAbstractSocket::IPv4Protocol) {
            // The below code is referenced from: http://support.microsoft.com/kb/831226
            srvList.AddrCount = 1;
            srvList.AddrArray[0] = htonl(nameserver.toIPv4Address());
        } else if (nameserver.protocol() == QAbstractSocket::IPv6Protocol) {
            // For supoprting IPv6 nameserver addresses, we'll need to switch
            // from DnsQuey() to DnsQueryEx() as it supports passing an IPv6
            // address in the nameserver list
            qWarning() << Q_FUNC_INFO << "IPv6 addresses for nameservers is currently not supported";
            reply->error = QDnsLookup::ResolverError;
            reply->errorString = tr("IPv6 addresses for nameservers is currently not supported");
            return;
        }
    }
    const DNS_STATUS status = DnsQuery_W(reinterpret_cast<const wchar_t*>(requestNameUtf16.utf16()), requestType, DNS_QUERY_STANDARD, &srvList, &dns_records, NULL);
    switch (status) {
    case ERROR_SUCCESS:
        break;
    case DNS_ERROR_RCODE_FORMAT_ERROR:
        reply->error = QDnsLookup::InvalidRequestError;
        reply->errorString = tr("Server could not process query");
        return;
    case DNS_ERROR_RCODE_SERVER_FAILURE:
        reply->error = QDnsLookup::ServerFailureError;
        reply->errorString = tr("Server failure");
        return;
    case DNS_ERROR_RCODE_NAME_ERROR:
        reply->error = QDnsLookup::NotFoundError;
        reply->errorString = tr("Non existent domain");
        return;
    case DNS_ERROR_RCODE_REFUSED:
        reply->error = QDnsLookup::ServerRefusedError;
        reply->errorString = tr("Server refused to answer");
        return;
    default:
        reply->error = QDnsLookup::InvalidReplyError;
        reply->errorString = QSystemError(status, QSystemError::NativeError).toString();
        return;
    }

    // Extract results.
    for (PDNS_RECORD ptr = dns_records; ptr != NULL; ptr = ptr->pNext) {
        const QString name = QUrl::fromAce( QString::fromWCharArray( ptr->pName ).toLatin1() );
        if (ptr->wType == QDnsLookup::A) {
            QDnsHostAddressRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QHostAddress(ntohl(ptr->Data.A.IpAddress));
            reply->hostAddressRecords.append(record);
        } else if (ptr->wType == QDnsLookup::AAAA) {
            Q_IPV6ADDR addr;
            memcpy(&addr, &ptr->Data.AAAA.Ip6Address, sizeof(Q_IPV6ADDR));

            QDnsHostAddressRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QHostAddress(addr);
            reply->hostAddressRecords.append(record);
        } else if (ptr->wType == QDnsLookup::CNAME) {
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QUrl::fromAce(QString::fromWCharArray(ptr->Data.Cname.pNameHost).toLatin1());
            reply->canonicalNameRecords.append(record);
        } else if (ptr->wType == QDnsLookup::MX) {
            QDnsMailExchangeRecord record;
            record.d->name = name;
            record.d->exchange = QUrl::fromAce(QString::fromWCharArray(ptr->Data.Mx.pNameExchange).toLatin1());
            record.d->preference = ptr->Data.Mx.wPreference;
            record.d->timeToLive = ptr->dwTtl;
            reply->mailExchangeRecords.append(record);
        } else if (ptr->wType == QDnsLookup::NS) {
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QUrl::fromAce(QString::fromWCharArray(ptr->Data.Ns.pNameHost).toLatin1());
            reply->nameServerRecords.append(record);
        } else if (ptr->wType == QDnsLookup::PTR) {
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QUrl::fromAce(QString::fromWCharArray(ptr->Data.Ptr.pNameHost).toLatin1());
            reply->pointerRecords.append(record);
        } else if (ptr->wType == QDnsLookup::SRV) {
            QDnsServiceRecord record;
            record.d->name = name;
            record.d->target = QUrl::fromAce(QString::fromWCharArray(ptr->Data.Srv.pNameTarget).toLatin1());
            record.d->port = ptr->Data.Srv.wPort;
            record.d->priority = ptr->Data.Srv.wPriority;
            record.d->timeToLive = ptr->dwTtl;
            record.d->weight = ptr->Data.Srv.wWeight;
            reply->serviceRecords.append(record);
        } else if (ptr->wType == QDnsLookup::TXT) {
            QDnsTextRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            for (unsigned int i = 0; i < ptr->Data.Txt.dwStringCount; ++i) {
                record.d->values << QString::fromWCharArray((ptr->Data.Txt.pStringArray[i])).toLatin1();;
            }
            reply->textRecords.append(record);
        }
    }

    DnsRecordListFree(dns_records, DnsFreeRecordList);
}
void MainWindow::readyRead()
{

    char data[128];
    QHostAddress addr;
    quint16 port;
    while(_udpSocket->bytesAvailable())
    {
        _udpSocket->readDatagram(data, udpDataSize, &addr, &port);
        char ch = data[4];
        switch(ch)
        {
        case RSP::QUERY_OUTPUT:
        {
            char buff[128];
            RSP::QueryOutput queryOutput(data+5);
            createRowDownloader(QString::fromStdString(queryOutput.getFileName()),
                                QString::fromStdString(queryOutput.getIpAddr()),queryOutput.getPort());
            RSP::AckFromServer ackFromServer(queryOutput.getSeq(),CMD::ACK_CONTENT_FROM_SERVER);
            ackFromServer.dump();
            ackFromServer.serialize(buff);
            qDebug()<<"Bytes written for Query Output Ack:"<<_udpSocket->writeDatagram(buff,udpDataSize,QHostAddress(_serverInfo->getServerIp()),
                                      _serverInfo->getServerPort());
            _udpSocket->waitForBytesWritten();
        }
            break;
        case RSP::ACK_INFORM_AND_UPDATE_SERVER:
        {
            RSP::AckFromServer ackFromServer(data+5);
            if(!_ackSeqList.contains(ackFromServer.getSeq()))
            {
                _ackSeqList.append(ackFromServer.getSeq());
                if(_timerAckMap.contains(ackFromServer.getSeq()))
                {
                 setSampleRtt(_timerAckMap[ackFromServer.getSeq()]->getTimeElapsed());
                _timerAckMap[ackFromServer.getSeq()]->stopTimer();
                }
                qDebug()<<"timer for ACK "+ QString::number(ackFromServer.getSeq()) +" stopped";

            }
        }
            break;
        default:
            qDebug()<<"UNKNOWN COMMAND";
        }
    }
}
Beispiel #7
0
NMVariantMapMap VpncUiPlugin::importConnectionSettings(const QString &fileName)
{
    // qCDebug(PLASMA_NM) << "Importing Cisco VPN connection from " << fileName;

    VpncUiPluginPrivate * decrPlugin = 0;
    NMVariantMapMap result;

    if (!fileName.endsWith(QLatin1String(".pcf"), Qt::CaseInsensitive)) {
        return result;
    }

    mError = VpnUiPlugin::Error;

    // NOTE: Cisco VPN pcf files follow ini style matching KConfig files
    // http://www.cisco.com/en/US/docs/security/vpn_client/cisco_vpn_client/vpn_client46/administration/guide/vcAch2.html#wp1155033
    KSharedConfig::Ptr config = KSharedConfig::openConfig(fileName);
    if (!config) {
        mErrorMessage = i18n("File %1 could not be opened.", fileName);
        return result;
    }

    KConfigGroup cg(config, "main");   // Keys&Values are stored under [main]
    if (cg.exists()) {
        // Setup cisco-decrypt binary to decrypt the passwords
        const QString ciscoDecryptBinary = QStandardPaths::findExecutable("cisco-decrypt");
        if (ciscoDecryptBinary.isEmpty()) {
            mErrorMessage = i18n("Needed executable cisco-decrypt could not be found.");
            return result;
        }

        decrPlugin = new VpncUiPluginPrivate();
        decrPlugin->ciscoDecrypt = new KProcess(decrPlugin);
        decrPlugin->ciscoDecrypt->setOutputChannelMode(KProcess::OnlyStdoutChannel);
        decrPlugin->ciscoDecrypt->setReadChannel(QProcess::StandardOutput);
        connect(decrPlugin->ciscoDecrypt, static_cast<void (KProcess::*)(QProcess::ProcessError)>(&KProcess::error), decrPlugin, &VpncUiPluginPrivate::ciscoDecryptError);
        connect(decrPlugin->ciscoDecrypt, static_cast<void (KProcess::*)(int, QProcess::ExitStatus)>(&KProcess::finished), decrPlugin, &VpncUiPluginPrivate::ciscoDecryptFinished);
        connect(decrPlugin->ciscoDecrypt, &KProcess::readyReadStandardOutput, decrPlugin, &VpncUiPluginPrivate::gotCiscoDecryptOutput);

        NMStringMap data;
        NMStringMap secretData;
        QVariantMap ipv4Data;

        // gateway
        data.insert(NM_VPNC_KEY_GATEWAY, decrPlugin->readStringKeyValue(cg,"Host"));
        // group name
        data.insert(NM_VPNC_KEY_ID, decrPlugin->readStringKeyValue(cg,"GroupName"));
        // user password
        if (!decrPlugin->readStringKeyValue(cg,"UserPassword").isEmpty()) {
            secretData.insert(NM_VPNC_KEY_XAUTH_PASSWORD, decrPlugin->readStringKeyValue(cg,"UserPassword"));
        } else if (!decrPlugin->readStringKeyValue(cg,"enc_UserPassword").isEmpty() && !ciscoDecryptBinary.isEmpty()) {
            // Decrypt the password and insert into map
            decrPlugin->ciscoDecrypt->setProgram(ciscoDecryptBinary);
            decrPlugin->ciscoDecrypt->start();
            decrPlugin->ciscoDecrypt->waitForStarted();
            decrPlugin->ciscoDecrypt->write(decrPlugin->readStringKeyValue(cg,"enc_UserPassword").toUtf8());
            if (decrPlugin->ciscoDecrypt->waitForFinished()) {
                secretData.insert(NM_VPNC_KEY_XAUTH_PASSWORD, decrPlugin->decryptedPasswd);
            }
        }
        // Save user password
        switch (cg.readEntry("SaveUserPassword").toInt()) {
        case 0:
            data.insert(NM_VPNC_KEY_XAUTH_PASSWORD"-flags", QString::number(NetworkManager::Setting::NotSaved));
            break;
        case 1:
            data.insert(NM_VPNC_KEY_XAUTH_PASSWORD"-flags", QString::number(NetworkManager::Setting::AgentOwned));
            break;
        case 2:
            data.insert(NM_VPNC_KEY_XAUTH_PASSWORD"-flags", QString::number(NetworkManager::Setting::NotRequired));
            break;
        }

        // group password
        if (!decrPlugin->readStringKeyValue(cg,"GroupPwd").isEmpty()) {
            secretData.insert(NM_VPNC_KEY_SECRET, decrPlugin->readStringKeyValue(cg,"GroupPwd"));
            data.insert(NM_VPNC_KEY_SECRET"-flags", QString::number(NetworkManager::Setting::AgentOwned));
        } else if (!decrPlugin->readStringKeyValue(cg,"enc_GroupPwd").isEmpty() && !ciscoDecryptBinary.isEmpty()) {
            //Decrypt the password and insert into map
            decrPlugin->ciscoDecrypt->setProgram(ciscoDecryptBinary);
            decrPlugin->ciscoDecrypt->start();
            decrPlugin->ciscoDecrypt->waitForStarted();
            decrPlugin->ciscoDecrypt->write(decrPlugin->readStringKeyValue(cg,"enc_GroupPwd").toUtf8());
            if (decrPlugin->ciscoDecrypt->waitForFinished()) {
                secretData.insert(NM_VPNC_KEY_SECRET, decrPlugin->decryptedPasswd);
                data.insert(NM_VPNC_KEY_SECRET"-flags", QString::number(NetworkManager::Setting::AgentOwned));
            }
        }

        // Auth Type
        if (!cg.readEntry("AuthType").isEmpty() && cg.readEntry("AuthType").toInt() == 5) {
            data.insert(NM_VPNC_KEY_AUTHMODE, QLatin1String("hybrid"));
        }

        // Optional settings
        // username
        if (!decrPlugin->readStringKeyValue(cg,"Username").isEmpty()) {
            data.insert(NM_VPNC_KEY_XAUTH_USER, decrPlugin->readStringKeyValue(cg,"Username"));
        }
        // domain
        if (!decrPlugin->readStringKeyValue(cg,"NTDomain").isEmpty()) {
            data.insert(NM_VPNC_KEY_DOMAIN, decrPlugin->readStringKeyValue(cg,"NTDomain"));
        }
        // encryption
        if (!cg.readEntry("SingleDES").isEmpty() && cg.readEntry("SingleDES").toInt() != 0) {
            data.insert(NM_VPNC_KEY_SINGLE_DES, QLatin1String("yes"));
        }
        /* Disable all NAT Traversal if explicit EnableNat=0 exists, otherwise
         * default to NAT-T which is newer and standardized.  If EnableNat=1, then
         * use Cisco-UDP like always; but if the key "X-NM-Use-NAT-T" is set, then
         * use NAT-T.  If the key "X-NM-Force-NAT-T" is set then force NAT-T always
         * on.  See vpnc documentation for more information on what the different
         * NAT modes are.
         */
        // enable NAT
        if (cg.readEntry("EnableNat").toInt() == 1) {
            data.insert(NM_VPNC_KEY_NAT_TRAVERSAL_MODE, QLatin1String(NM_VPNC_NATT_MODE_CISCO));
            // NAT traversal
            if (!cg.readEntry("X-NM-Use-NAT-T").isEmpty()) {
                if (cg.readEntry("X-NM-Use-NAT-T").toInt() == 1) {
                    data.insert(NM_VPNC_KEY_NAT_TRAVERSAL_MODE, QLatin1String(NM_VPNC_NATT_MODE_NATT));
                }
                if (cg.readEntry("X-NM-Force-NAT-T").toInt() == 1) {
                    data.insert(NM_VPNC_KEY_NAT_TRAVERSAL_MODE, QLatin1String(NM_VPNC_NATT_MODE_NATT_ALWAYS));
                }
            }
        } else {
            data.insert(NM_VPNC_KEY_NAT_TRAVERSAL_MODE, QLatin1String(NM_VPNC_NATT_MODE_NONE));
        }
        // dead peer detection
        data.insert(NM_VPNC_KEY_DPD_IDLE_TIMEOUT, cg.readEntry("PeerTimeout"));
        // UseLegacyIKEPort=0 uses dynamic source IKE port instead of 500.
        if (cg.readEntry("UseLegacyIKEPort").isEmpty() || cg.readEntry("UseLegacyIKEPort").toInt() != 0) {
            data.insert(NM_VPNC_KEY_LOCAL_PORT, QString::number(NM_VPNC_LOCAL_PORT_DEFAULT));
        }
        // DH Group
        data.insert(NM_VPNC_KEY_DHGROUP, decrPlugin->readStringKeyValue(cg,"DHGroup"));
        // Tunneling Mode - not supported by vpnc
        if (cg.readEntry("TunnelingMode").toInt() == 1) {
            KMessageBox::error(0, i18n("The VPN settings file '%1' specifies that VPN traffic should be tunneled through TCP which is currently not supported in the vpnc software.\n\nThe connection can still be created, with TCP tunneling disabled, however it may not work as expected.", fileName), i18n("Not supported"), KMessageBox::Notify);
        }
        // EnableLocalLAN and X-NM-Routes are to be added to IPv4Setting
        if (!cg.readEntry("EnableLocalLAN").isEmpty()) {
            ipv4Data.insert("never-default", cg.readEntry("EnableLocalLAN"));
        }
        if (!decrPlugin->readStringKeyValue(cg,"X-NM-Routes").isEmpty()) {
            QList<NetworkManager::IpRoute> list;
            Q_FOREACH (const QString &route, decrPlugin->readStringKeyValue(cg,"X-NM-Routes").split(' ')) {
                NetworkManager::IpRoute ipRoute;
                ipRoute.setIp(QHostAddress(route.split('/').first()));
                ipRoute.setPrefixLength(route.split('/').at(1).toInt());
                list << ipRoute;
            }
            QList<QList<uint> > dbusRoutes;
            Q_FOREACH (const NetworkManager::IpRoute &route, list) {
                QList<uint> dbusRoute;
                dbusRoute << htonl(route.ip().toIPv4Address())
                        << route.prefixLength()
                        << htonl(route.nextHop().toIPv4Address())
                        << route.metric();
                dbusRoutes << dbusRoute;
            }
            ipv4Data.insert("routes", QVariant::fromValue(dbusRoutes));
        }
Beispiel #8
0
QUrl Core::MakeURL (QString url)
{
    if (url.isEmpty ())
        return QUrl ();

    url = url.trimmed ();
    if (url == "localhost")
        return QUrl ("http://localhost");

    if (url.startsWith ('!'))
    {
        HandleSearchRequest (url);
        return QUrl ();
    }

    if (QHostAddress ().setAddress (url))
    {
        QUrl result;
        result.setHost (url);
        result.setScheme ("http://");
        return result;
    }

    // If the url without percent signs and two following characters is
    // a valid url (it should not be percent-encoded), then treat source
    // url as percent-encoded, otherwise treat as not percent-encoded.
    QString withoutPercent = url;
    withoutPercent.remove (QRegExp ("%%??",
                                    Qt::CaseInsensitive, QRegExp::Wildcard));
    QUrl testUrl (withoutPercent);
    QUrl result;
    if (testUrl.toString () == withoutPercent)
        result = QUrl::fromEncoded (url.toUtf8 ());
    else
        result = QUrl (url);

    if (result.scheme ().isEmpty ())
    {
        if (!url.count (' ') && url.count ('.'))
            result = QUrl (QString ("http://") + url);
        else
        {
            url.replace ('+', "%2B");
            url.replace (' ', '+');
            QString urlStr = QString ("http://www.google.com/search?q=%2"
                                      "&client=leechcraft_poshuku"
                                      "&ie=utf-8"
                                      "&rls=org.leechcraft:%1")
                             .arg (QLocale::system ().name ().replace ('_', '-'))
                             .arg (url);
            result = QUrl::fromEncoded (urlStr.toUtf8 ());
        }
    }
    else if (result.host ().isEmpty ())
    {
        bool isHostNum = false;
        auto num = result.path ().toInt (&isHostNum);
        if (isHostNum)
        {
            QMap<int, QString> port2scheme;
            port2scheme [443] = "https";

            result.setPort (num);
            result.setHost (result.scheme ());
            result.setScheme (port2scheme.value (num, "http"));
            result.setPath (QString ());
        }
    }

    return result;
}
Response::ResponseCode ServerSocketInterface::cmdBanFromServer(const Command_BanFromServer &cmd, ResponseContainer & /*rc*/)
{
    if (!sqlInterface->checkSql())
        return Response::RespInternalError;

    QString userName = QString::fromStdString(cmd.user_name());
    QString address = QString::fromStdString(cmd.address());
    QString trustedSources = settingsCache->value("server/trusted_sources","127.0.0.1,::1").toString();
    int minutes = cmd.minutes();
    if (trustedSources.contains(address,Qt::CaseInsensitive))
        address = "";

    QSqlQuery *query = sqlInterface->prepareQuery("insert into {prefix}_bans (user_name, ip_address, id_admin, time_from, minutes, reason, visible_reason, clientid) values(:user_name, :ip_address, :id_admin, NOW(), :minutes, :reason, :visible_reason, :client_id)");
    query->bindValue(":user_name", userName);
    query->bindValue(":ip_address", address);
    query->bindValue(":id_admin", userInfo->id());
    query->bindValue(":minutes", minutes);
    query->bindValue(":reason", QString::fromStdString(cmd.reason()));
    query->bindValue(":visible_reason", QString::fromStdString(cmd.visible_reason()));
    query->bindValue(":client_id", QString::fromStdString(cmd.clientid()));
    sqlInterface->execSqlQuery(query);

    servatrice->clientsLock.lockForRead();
    QList<ServerSocketInterface *> userList = servatrice->getUsersWithAddressAsList(QHostAddress(address));

    if (!userName.isEmpty()) {
        ServerSocketInterface *user = static_cast<ServerSocketInterface *>(server->getUsers().value(userName));
        userList.append(user);
    }

    if (userName.isEmpty() && address.isEmpty()) {
        QSqlQuery *query = sqlInterface->prepareQuery("select name from {prefix}_users where clientid = :client_id");
        query->bindValue(":client_id", QString::fromStdString(cmd.clientid()));
        sqlInterface->execSqlQuery(query);
        if (!sqlInterface->execSqlQuery(query)){
            qDebug("ClientID username ban lookup failed: SQL Error");
        } else {
            while (query->next()) {
                userName = query->value(0).toString();
                ServerSocketInterface *user = static_cast<ServerSocketInterface *>(server->getUsers().value(userName));
                if (user && !userList.contains(user))
                   userList.append(user);
            }
        }
    }

    if (!userList.isEmpty()) {
        Event_ConnectionClosed event;
        event.set_reason(Event_ConnectionClosed::BANNED);
        if (cmd.has_visible_reason())
            event.set_reason_str(cmd.visible_reason());
        if (minutes)
            event.set_end_time(QDateTime::currentDateTime().addSecs(60 * minutes).toTime_t());
        for (int i = 0; i < userList.size(); ++i) {
            SessionEvent *se = userList[i]->prepareSessionEvent(event);
            userList[i]->sendProtocolItem(*se);
            delete se;
            QMetaObject::invokeMethod(userList[i], "prepareDestroy", Qt::QueuedConnection);
        }
    }
    servatrice->clientsLock.unlock();

    return Response::RespOk;
}
Beispiel #10
0
//当PeopVSPeop tcp监听成功时,触发该槽
//向FindServer发送指令,让其连接TCP
void BuildServer::onListenSuccess()
{
    qDebug() << "BuildServer recieved listenSuccess() signal, command PleaseConnect to FindServer";
    QByteArray datagram = "PleaseConnect" ;
    udpServer->writeDatagram( datagram.data() , datagram.size() , QHostAddress( IP ) , 7758 ) ;
}
Beispiel #11
0
int main(int argc, char *argv[])
{
        QCoreApplication a(argc, argv);

        //help output
        if(a.arguments().contains("help"))
        {
            MSG("### OSCGrabber HELP ###");
            MSG(" ");
            MSG("The following Arguments are available:");
            MSG("   osc-server-address (address to send osc messages to) [default: 127.0.0.1]");
            MSG("   osc-send-port      (port to send osc messages to) [default: 7000]");
            MSG("   osc-listen-port    (port on wich OSCGrabber is listening for incomming osc messages) [default: 9001]");
            MSG("   udp-send-address   (address to send udp converted messages to) [default: 127.0.0.1]");
            MSG("   udp-send-port      (port to send udp converted messages to) [default: 7799]");
            MSG("   udp-listen-port    (port on wich OSCGrabber is listening for incomming udp messages) [default: 7788]");
            MSG(" ");
            MSG("examaple calls:");
            MSG("   OSCGrabber osc-listen-port 7000 osc-server-address 1.2.3.4");
            MSG(" ");
            MSG("Type 'help' for this message.");
            a.exit();
            return a.exec();
        }

        //read command line arguments
        int oscListenPort = 9001;
        if(a.arguments().contains("osc-listen-port"))
            oscListenPort = a.arguments().at(a.arguments().indexOf(QRegExp("osc-listen-port"))+1).toInt();

        QString oscServerAddress = "127.0.0.1";
        if(a.arguments().contains("osc-server-address"))
            oscServerAddress = a.arguments().at(a.arguments().indexOf(QRegExp("osc-server-address"))+1);

        int oscSendPort = 9000;
        if(a.arguments().contains("osc-send-port"))
            oscSendPort = a.arguments().at(a.arguments().indexOf(QRegExp("osc-send-port"))+1).toInt();

        int udpSendPort = 7799;
        if(a.arguments().contains("udp-send-port"))
            udpSendPort = a.arguments().at(a.arguments().indexOf(QRegExp("udp-send-port"))+1).toInt();

        QString udpSendAddress = "127.0.0.1";
        if(a.arguments().contains("udp-send-address"))
            udpSendAddress = a.arguments().at(a.arguments().indexOf(QRegExp("udp-send-address"))+1);

        int udpListenPort = 7788;
        if(a.arguments().contains("udp-listen-port"))
            udpListenPort = a.arguments().at(a.arguments().indexOf(QRegExp("udp-listen-port"))+1).toInt();


        //start creating the services
        MSG("### [Creating] UDP service at Port "<<udpListenPort);
        MSG("### Sending to "<<udpSendAddress.toStdString());
        QUdpSocket *listenSocket = new QUdpSocket(&a);
        listenSocket->bind(QHostAddress::AnyIPv4, udpListenPort);

        if(!listenSocket->isValid())
        {
            MSG("Couldn't creat udp service at port "<<udpSendPort<<" . Port already occupied?");
            a.exit();
            return 0; //a.exec();
        }

        MSG("### [Launching] OSC Bridge to address "<<oscServerAddress.toStdString()<<" "<<oscListenPort)
        lo::ServerThread * server = new lo::ServerThread(oscListenPort);
        server->start();

        if (!server->is_valid()) { //this check isn't working. why?
            MSG("Couldn't creat osc service listening to port "<<oscListenPort<<" . Port already occupied?");
            a.exit();
            return 0; //a.exec();
        }
        MSG("### --> Listening to Port: "<<oscListenPort);

        lo::string_type address(oscServerAddress.toStdString());
        lo::Address * oscSender = new lo::Address(address, oscSendPort);

//        lo::Address * oscSender = new lo::Address("localhost", oscSendPort);
        MSG("### --> Writing on Port: "<<oscSendPort);


        //####################################################################################
        //####################################################################################
        //  OSC to UDP
        //####################################################################################
        //####################################################################################

        QUdpSocket *senderSocket = new QUdpSocket(&a);

        server->add_method(NULL, NULL, [=](const char *path, const lo::Message& msg)
        {
//            msg.print();
            QString type = QString::fromStdString(msg.types());
            QString data(path);
            data.append("%");
            data.append(type);
            data.append("%");

            for (int i = 0; i < msg.argc(); i++) {
                if(type.at(i) == 'i')
                {
                    data.append(QString::number(msg.argv()[i]->i)+"%");
//                    std::cout<<std::bitset<32>()<<std::endl;
                }
                else if(type.at(i) == 'f')
                    data.append(QString::number(msg.argv()[i]->f)+"%");
                else if(type.at(i) == 's')
                    data.append(QString::fromStdString(&msg.argv()[i]->S)+"%");
            }

            if(-1 == senderSocket->writeDatagram(data.toUtf8(), QHostAddress(udpSendAddress), udpSendPort))
            {
                //qDebug()<<"ERROR: "<<senderSocket->errorString()<<" "<<senderSocket->error();
            }
            else
            {
                //qDebug()<<"From live: "<<data;
                //qDebug()<<"NO ERROR?: "<<senderSocket->errorString()<<" "<<senderSocket->error()<<" valid? "<<senderSocket->isValid();
            }
        });

        //####################################################################################
        //####################################################################################
        //  UDP to OSC
        //####################################################################################
        //####################################################################################

        QObject::connect(listenSocket, &QUdpSocket::readyRead, [=]()
        {
            QByteArray datagram;
            datagram.resize(listenSocket->pendingDatagramSize());
            QHostAddress sender;
            quint16 senderPort;

            listenSocket->readDatagram(datagram.data(), datagram.size(),
                                            &sender, &senderPort);

            //qDebug()<<"Message from: "<<sender<<" "<<senderPort<<" "<<QString::fromUtf8(datagram);

            QStringList splittedData = QString::fromUtf8(datagram).split("%");

            if(splittedData.length() > 1)
            {

                lo::string_type path(splittedData.takeFirst().toStdString());
                QString dataTypes = splittedData.takeFirst();
                lo::Message message;

                for(int i = 0; i<dataTypes.length(); i++)
                {
                    //qDebug()<<"type: "<<dataTypes.at(i);
                    if(dataTypes.at(i) == 'i')
                        message.add(splittedData.at(i).toInt());
                    else if(dataTypes.at(i) == 'f')
                        message.add(splittedData.at(i).toFloat());
                    else if(dataTypes.at(i) == 's')
                    {
                        lo::string_type str(splittedData.at(i).toStdString());
                        message.add(str);
                    }
                }
                //qDebug()<<"Stringlist: "<<splittedData;
                /*qDebug()<<"To live: "<<*/
                oscSender->send(path, message);//<<QString::fromStdString(message.types())<<path._s;

            }
            else
            {
                lo::string_type path(splittedData.takeFirst().toStdString());
                /*qDebug()<<"To live: "<<*/
                oscSender->send(path);
            }

        });

        //clean up services
        QObject::connect(&a, &QCoreApplication::destroyed, [=](){
            server->stop();
            delete server;
        });

        return a.exec();
}
Beispiel #12
0
 bool isLoopbackAddress(const QHostAddress &addr)
 {
     return (addr == QHostAddress::LocalHost)
             || (addr == QHostAddress::LocalHostIPv6)
             || (addr == QHostAddress(QLatin1String("::ffff:127.0.0.1")));
 }
Beispiel #13
0
 bool isValidIP(const QString &ip)
 {
     return !QHostAddress(ip).isNull();
 }
Beispiel #14
0
Client::Client(QWidget *parent) : QDialog(parent)
{
    hostLabel = new QLabel(tr("&Server name:"));
    portLabel = new QLabel(tr("S&erver port:"));

    // find out which IP to connect to
    QString ipAddress;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // use the first non-localhost IPv4 address
    for (int i = 0; i < ipAddressesList.size(); ++i) {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
            ipAddressesList.at(i).toIPv4Address()) {
            ipAddress = ipAddressesList.at(i).toString();
            break;
        }
    }
    // if we did not find one, use IPv4 localhost
    if (ipAddress.isEmpty())
        ipAddress = QHostAddress(QHostAddress::LocalHost).toString();

    hostLineEdit = new QLineEdit(ipAddress);
    portLineEdit = new QLineEdit;
    portLineEdit->setValidator(new QIntValidator(1, 65535, this));

    hostLabel->setBuddy(hostLineEdit);
    portLabel->setBuddy(portLineEdit);

    statusLabel = new QLabel(tr("This examples requires that you run the "
                                "Secure Fortune Server example as well."));

    getFortuneButton = new QPushButton(tr("Get Fortune"));
    getFortuneButton->setDefault(true);
    getFortuneButton->setEnabled(false);

    quitButton = new QPushButton(tr("Quit"));

    buttonBox = new QDialogButtonBox;
    buttonBox->addButton(getFortuneButton, QDialogButtonBox::ActionRole);
    buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);

    secureSocket = new QSslSocket(this);

    // special slot to handle errors with the certificates
    // in particular the fact that they are self-signed
    connect(secureSocket, SIGNAL(sslErrors(QList<QSslError>)), this,
            SLOT(handleSSLError(QList<QSslError>)));

    connect(hostLineEdit, SIGNAL(textChanged(QString)),
            this, SLOT(enableGetFortuneButton()));
    connect(portLineEdit, SIGNAL(textChanged(QString)),
            this, SLOT(enableGetFortuneButton()));
    connect(getFortuneButton, SIGNAL(clicked()),
            this, SLOT(requestNewFortune()));
    connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
    connect(secureSocket, SIGNAL(readyRead()), this, SLOT(readFortune()));
    connect(secureSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(displayError(QAbstractSocket::SocketError)));

    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->addWidget(hostLabel, 0, 0);
    mainLayout->addWidget(hostLineEdit, 0, 1);
    mainLayout->addWidget(portLabel, 1, 0);
    mainLayout->addWidget(portLineEdit, 1, 1);
    mainLayout->addWidget(statusLabel, 2, 0, 1, 2);
    mainLayout->addWidget(buttonBox, 3, 0, 1, 2);
    setLayout(mainLayout);

    setWindowTitle(tr("Secure Fortune Client"));
    portLineEdit->setFocus();
}
Beispiel #15
0
So2sdrBandmap::So2sdrBandmap(QStringList args, QWidget *parent) : QMainWindow(parent)
{
    setupUi(this);
    initPointers();
    initVariables();

    // check to see if user directory exists
    initialized = checkUserDirectory();
    settingsFile = userDirectory()+"/so2sdr-bandmap.ini";

    // check for optional command argument giving station config file name
    if (args.size() > 1) {
        settingsFile = args[1].trimmed();
        // Qt doesn't understand that ~/... implies home directory...
        if (settingsFile.left(1)=="~") {
            if (settingsFile.left(2)=="~/") {
                settingsFile=QDir::homePath()+settingsFile.right(settingsFile.size()-1);
            } else {
                // for cases like ~name : no easy way to parse, give up
                QMessageBox msgBox;
                msgBox.setText("Please use the complete path to the settings file.");
                msgBox.setInformativeText(settingsFile);
                msgBox.setStandardButtons(QMessageBox::Ok);
                msgBox.setDefaultButton(QMessageBox::Ok);
                msgBox.exec();
                close();
            }
        }
    }
    QFileInfo fi(settingsFile);
    if (!fi.exists()) {
        QMessageBox msgBox;
        msgBox.setText("The settings file "+settingsFile+" does not exist.");
        msgBox.setInformativeText("Do you want to create it?");
        msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel);
        msgBox.setDefaultButton(QMessageBox::Save);
        if (msgBox.exec()==QMessageBox::Cancel) {
            close();
        }
        firstTime=true;
    }
    settings = new  QSettings(settingsFile,QSettings::IniFormat,this);
    if (settings->status()!=QSettings::NoError) {
        errorBox.showMessage("ERROR: problem starting qsettings");
    }
    // if run the first time with default settings file for second radio,
    // set second radio
    if (firstTime && settingsFile.right(19)=="so2sdr-bandmap2.ini") {
        settings->setValue(s_sdr_nrig,1);
    }
    // restore window size and position
    QString tmp="BandmapWindow";
    settings->beginGroup(tmp);
    resize(settings->value("size", QSize(400, 594)).toSize());
    move(settings->value("pos", QPoint(200, 200)).toPoint());
    settings->endGroup();

    directory.setCurrent(dataDirectory());
    setWindowIcon(QIcon("icon24x24.png"));

    if (settings->value(s_sdr_reverse_scroll,s_sdr_reverse_scroll_def).toBool()) {
        horizontalLayout->removeWidget(CallLabel);
        horizontalLayout->removeWidget(FreqLabel);
        horizontalLayout->removeWidget(display);
        horizontalLayout->insertWidget(0,CallLabel);
        horizontalLayout->insertWidget(1,FreqLabel);
        horizontalLayout->insertWidget(2,display);
    }

    freqPixmap      = QPixmap(FreqLabel->width(), settings->value(s_sdr_fft,s_sdr_fft_def).toInt());
    callPixmap      = QPixmap(CallLabel->width(), settings->value(s_sdr_fft,s_sdr_fft_def).toInt());

    ipAddress= QHostAddress(QHostAddress::LocalHost).toString();
    if (!server.listen(QHostAddress::LocalHost,
                        settings->value(s_sdr_bandmap_tcp_port,s_sdr_bandmap_tcp_port_def).toInt())) {
        qDebug("couldn't start tcp server");
    }
    connect(&server, SIGNAL(newConnection()), this, SLOT(startConnection()));

    setFocusPolicy(Qt::StrongFocus);
    setFocusPolicy(Qt::NoFocus);
    display->setFocusPolicy(Qt::NoFocus);
    CallLabel->setFocusPolicy(Qt::NoFocus);
    FreqLabel->setFocusPolicy(Qt::NoFocus);

    checkBoxMark.setText("Mark");
    checkBoxMark.setToolTip("Enables signal detection.");
    toolBar->setMovable(false);
    QWidget* spacer1 = new QWidget();
    spacer1->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred);
    toolBar->addWidget(spacer1);
    toolBar->addWidget(&checkBoxMark);
    txLabel.clear();
    txLabel.setText("<font color=#000000>TX");
    toolBar->addWidget(&txLabel);
    slider.setToolTip("Gain for signal detection. To the right is LESS sensitive.");
    slider.setOrientation(Qt::Horizontal);
    connect(&slider,SIGNAL(valueChanged(int)),this,SLOT(updateLevel(int)));
    slider.setFixedWidth(60);
    slider.setMaximum(200);
    slider.setMinimum(0);
    slider.setSingleStep(10);
    slider.setPageStep(50);
    slider.setValue(settings->value(s_sdr_level,s_sdr_level_def).toInt());
    toolBar->addWidget(&slider);
    QWidget* spacer2 = new QWidget();
    spacer2->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred);
    toolBar->addWidget(spacer2);
    toolBar->addAction("&Help",this,SLOT(showHelp()));

    iqDialog  = new IQBalance(this, Qt::Window);
    iqDialog->clearPlots();
    showToolBar = new QAction("&toolbar",this);
    scaleX1   = new QAction("Zoom x&1", this);
    scaleX2   = new QAction("Zoom x&2", this);
    deleteAct = new QAction("&Delete Call", this);
    checkBoxMark.setChecked(settings->value(s_sdr_peakdetect,s_sdr_peakdetect_def).toBool());

    iqShowData = new QAction("IQ Balance", this);
    connect(iqShowData, SIGNAL(triggered()), this, SLOT(showIQData()));
    connect(&checkBoxMark, SIGNAL(clicked()), this, SLOT(emitParams()));
    connect(deleteAct, SIGNAL(triggered()), this, SLOT(deleteCallMouse()));
    showToolBar->setCheckable(true);
    showToolBar->setChecked(true);
    connect(showToolBar,SIGNAL(triggered(bool)),this,SLOT(setShowToolbar(bool)));
    scaleX1->setCheckable(true);
    scaleX2->setCheckable(true);
    scaleX2->setChecked(false);
    scaleX1->setChecked(true);
    connect(scaleX1, SIGNAL(triggered()), this, SLOT(setScaleX1()));
    connect(scaleX2, SIGNAL(triggered()), this, SLOT(setScaleX2()));
    connect(actionRun,SIGNAL(triggered()),this,SLOT(start()));

    sdrSetup = new SDRDialog(*settings,this);
    connect(actionSetup,SIGNAL(triggered()),sdrSetup,SLOT(show()));
    connect(actionSetup,SIGNAL(triggered()),this,SLOT(disconnectSignals()));
    connect(sdrSetup,SIGNAL(setupErrors(QString)),&errorBox,SLOT(showMessage(QString)));
    connect(sdrSetup,SIGNAL(update()),this,SLOT(setSdrType()));
    connect(sdrSetup,SIGNAL(restartSdr()),this,SLOT(restartSdr()));
    connect(display, SIGNAL(displayMouseQSY(int)), this, SLOT(mouseQSYDelta(int)));
    toolBarHeight = toolBar->height();

    // select type of SDR, create data source sdrSource
    spectrumProcessor = new Spectrum(this,*settings,userDirectory());
    switch ((SdrType)settings->value(s_sdr_type,s_sdr_type_def).toInt()) {
    case soundcard_t:
        sdrSource = new AudioReaderPortAudio(settingsFile);
        break;
    case afedri_t:
        sdrSource = new Afedri(settingsFile);
        break;
    case network_t:
        sdrSource = new NetworkSDR(settingsFile);
        break;
    }
    setSdrType();
    sdrSource->moveToThread(&sdrThread);
    connect(actionSetup,SIGNAL(triggered()),sdrSource,SLOT(stop()),Qt::DirectConnection);
    connect(&sdrThread,SIGNAL(started()),sdrSource,SLOT(initialize()));
    connect(sdrSource,SIGNAL(stopped()),&sdrThread,SLOT(quit()));
    connect(sdrSource,SIGNAL(stopped()),this,SLOT(disconnectSignals()));
    connect(sdrSource,SIGNAL(error(QString)),&errorBox,SLOT(showMessage(QString)));

    connect(spectrumProcessor, SIGNAL(spectrumReady(unsigned char*, unsigned char)), display,
            SLOT(plotSpectrum(unsigned char*, unsigned char)));
    connect(sdrSource, SIGNAL(ready(unsigned char *, unsigned char)),spectrumProcessor,
            SLOT(processData(unsigned char *, unsigned char)),Qt::QueuedConnection);
    connect(iqDialog, SIGNAL(closed(bool)), spectrumProcessor, SLOT(setPlotPoints(bool)));
    connect(iqDialog, SIGNAL(restart()), spectrumProcessor, SLOT(clearIQ()));
    connect(spectrumProcessor, SIGNAL(qsy(int)), this, SLOT(findQsy(int)));
    connect(spectrumProcessor, SIGNAL(clearPlot()), iqDialog, SLOT(clearPlots()));
    connect(spectrumProcessor, SIGNAL(gainPoint(int, double)), iqDialog, SLOT(plotGainPoint(int, double)));
    connect(spectrumProcessor, SIGNAL(phasePoint(int, double)), iqDialog, SLOT(plotPhasePoint(int, double)));
    connect(spectrumProcessor, SIGNAL(gainScale(double, double)), iqDialog, SLOT(setGainScale(double, double)));
    connect(spectrumProcessor, SIGNAL(phaseScale(double, double)), iqDialog, SLOT(setPhaseScale(double, double)));
    connect(spectrumProcessor, SIGNAL(plotGainFunc(double, double, double, double)), iqDialog,
           SLOT(plotGainFunc(double, double, double, double)));
    connect(spectrumProcessor, SIGNAL(plotPhaseFunc(double, double, double, double)), iqDialog,
           SLOT(plotPhaseFunc(double, double, double, double)));

    // vfoPos is the position of the red line indicating center
    vfoPos          = (height()-toolBarHeight)/ 2;
    dragPos         = vfoPos;
    display->setVfoPos(vfoPos);

    makeFreqScaleAbsolute();
    FreqLabel->setPixmap(freqPixmap);
    FreqLabel->update();

    startTimers();
    show();
}
Client::Client(QWidget *parent)
    : QDialog(parent), networkSession(0)
{
	 // find out which IP to connect to
	QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
	// use the first non-localhost IPv4 address
	for (int i = 0; i < ipAddressesList.size(); ++i) {
		if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
			ipAddressesList.at(i).toIPv4Address()) {
			ipAddress = ipAddressesList.at(i).toString();
			break;
		}
	}
	// if we did not find one, use IPv4 localhost
	if (ipAddress.isEmpty())
		ipAddress = QHostAddress(QHostAddress::LocalHost).toString();

	userLabel = new QLabel("Username: "******"Password: "******"Register");
	loginButton = new QPushButton("Login");
	cancelButton = new QPushButton("Cancel");

	buttonBox = new QDialogButtonBox();
	buttonBox->addButton(registerButton, QDialogButtonBox::ActionRole);
	buttonBox->addButton(loginButton, QDialogButtonBox::ActionRole);
	buttonBox->addButton(cancelButton, QDialogButtonBox::RejectRole);

	mainLayout = new QGridLayout;
	mainLayout->addWidget(userLabel, 0, 0, 1, 2);
	mainLayout->addWidget(userLineEdit, 1, 0, 1, 5);
	mainLayout->addWidget(passLabel, 2, 0, 1, 2);
	mainLayout->addWidget(passLineEdit, 3, 0, 1, 5);
	mainLayout->addWidget(statusLabel, 4, 0, 3, 4);
	mainLayout->addWidget(buttonBox, 7, 1, 1, 2);

	setLayout(mainLayout);

	tcpSocket = new QTcpSocket(this);

	connect(registerButton, SIGNAL(clicked()), this, SLOT(registerWithServer()));
	connect(cancelButton, SIGNAL(clicked()), this, SLOT(close()));
	connect(loginButton, SIGNAL(clicked()), this, SLOT(requestNewConnection()));
	connect(tcpSocket, SIGNAL(connected()), this, SLOT(sendLoginInfo()));
	connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(updateLabels()));
	//connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(connectionClosedByServer()));

	QNetworkConfigurationManager manager;
	if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
		// Get saved network configuration
		QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
		settings.beginGroup(QLatin1String("QtNetwork"));
		const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
		settings.endGroup();

		// If the saved network configuration is not currently discovered use the system default
		QNetworkConfiguration config = manager.configurationFromIdentifier(id);
		if ((config.state() & QNetworkConfiguration::Discovered) !=
			QNetworkConfiguration::Discovered) {
			config = manager.defaultConfiguration();
		}

		networkSession = new QNetworkSession(config, this);
		connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

		statusLabel->setText(tr("Opening network session."));
		networkSession->open();
	}

}
Beispiel #17
0
void QxtMDNSPrivate::avahiRecordBrowserCallback(AvahiRecordBrowser *b, AvahiIfIndex interface, AvahiProtocol protocol, AvahiBrowserEvent event, const char *name, uint16_t clazz, uint16_t type, const void *rdata, size_t size, AvahiLookupResultFlags flags, void *userdata)
{
	///@TODO Support IPv6
	Q_UNUSED(interface);
	Q_UNUSED(protocol);
	Q_UNUSED(name);
	Q_UNUSED(clazz);
	Q_UNUSED(type);
	Q_UNUSED(size);
	Q_UNUSED(flags);
	QxtMDNSPrivate* self = static_cast<QxtMDNSPrivate*>(userdata);
	self->recordbrowser = b;
// 	qDebug() << "Return thing" << md->name << name << size;
	switch (event)
	{
		case AVAHI_BROWSER_NEW:
		{
			//Found an entry!
			uint32_t ip = qFromBigEndian(*static_cast<const uint32_t*>(rdata));
			if (self->sent)
			{
				QHostInfo info(self->info.lookupId());
				info.setAddresses(QList<QHostAddress>() << QHostAddress(ip));
				QMetaObject::invokeMethod(self->receiver, self->member, Q_ARG(QHostInfo, info));
			}
			else
			{
				self->addresses << QHostAddress(ip);
			}
			break;
		}
		case AVAHI_BROWSER_REMOVE:
		{
			uint32_t ip = qFromBigEndian(*static_cast<const uint32_t*>(rdata));
			self->addresses.removeAll(QHostAddress(ip));
			break;
		}
		case AVAHI_BROWSER_CACHE_EXHAUSTED:
			break;
		case AVAHI_BROWSER_ALL_FOR_NOW:
			if (self->addresses.count() == 0)
			{
				self->info.setError(QHostInfo::HostNotFound);
				self->info.setErrorString("The host was not found.");
			}
			else
			{
				self->info.setAddresses(self->addresses);
				self->addresses.clear();
			}
			QMetaObject::invokeMethod(self->receiver, self->member, Q_ARG(QHostInfo, self->info));
			self->sent = true;
			break;
		case AVAHI_BROWSER_FAILURE:

			if (self->sent)
			{
				QHostInfo info(self->info.lookupId());
				info.setError(QHostInfo::UnknownError);
				info.setErrorString(avahi_strerror(avahi_client_errno(self->client)));
				info.setAddresses(self->addresses);
				QMetaObject::invokeMethod(self->receiver, self->member, Q_ARG(QHostInfo, info));
			}
			else
			{
				self->info.setError(QHostInfo::UnknownError);
				self->info.setErrorString(avahi_strerror(avahi_client_errno(self->client)));
				self->info.setAddresses(self->addresses);
				self->addresses.clear();
				QMetaObject::invokeMethod(self->receiver, self->member, Q_ARG(QHostInfo, self->info));
				self->sent = true;
			}
			break;
	}
}
Beispiel #18
0
	bool IsLocalIp(const QString &ip)
	{
		QList<QNetworkInterface> interfaces(QNetworkInterface::allInterfaces());
		return GetNetworkAddressEntry(interfaces, QHostAddress(ip)) != 0;
	}
Beispiel #19
0
void Connector::setPeerAddressNone()
{
	haveaddr = false;
	addr = QHostAddress();
	port = 0;
}
Beispiel #20
0
	bool IsSameLocalSubNet(const QString &ip1, const QString &ip2)
	{
		return 	IsSameLocalSubNet(QHostAddress(ip1), QHostAddress(ip2)); 
	}
Beispiel #21
0
void Server::setHostAdress(QString adress)
{
    host_adress = QHostAddress(adress);
}
bool ESURegistrationTableManager::removeRecordByAddress(const QString &address)
{
    return removeRecordByAddress(QHostAddress(address));
}
void IPTVStreamHandler::run(void)
{
    RunProlog();

    LOG(VB_GENERAL, LOG_INFO, LOC + "run()");

    SetRunning(true, false, false);

    // TODO Error handling..

    // Setup
    CetonRTSP *rtsp = NULL;
    IPTVTuningData tuning = m_tuning;
    if (m_tuning.GetURL(0).scheme().toLower() == "rtsp")
    {
        rtsp = new CetonRTSP(m_tuning.GetURL(0));

        // Check RTSP capabilities
        QStringList options;
        if (!(rtsp->GetOptions(options)     && options.contains("OPTIONS")  &&
              options.contains("DESCRIBE")  && options.contains("SETUP")    &&
              options.contains("PLAY")      && options.contains("TEARDOWN")))
        {
            LOG(VB_RECORD, LOG_ERR, LOC +
                "RTSP interface did not support the necessary options");
            delete rtsp;
            SetRunning(false, false, false);
            RunEpilog();
            return;
        }

        if (!rtsp->Describe())
        {
            LOG(VB_RECORD, LOG_ERR, LOC +
                "RTSP Describe command failed");
            delete rtsp;
            SetRunning(false, false, false);
            RunEpilog();
            return;
        }

        tuning = IPTVTuningData(
            QString("rtp://%1@%2:0")
            .arg(m_tuning.GetURL(0).host())
            .arg(QHostAddress(QHostAddress::Any).toString()), 0,
            IPTVTuningData::kNone,
            QString("rtp://%1@%2:0")
            .arg(m_tuning.GetURL(0).host())
            .arg(QHostAddress(QHostAddress::Any).toString()), 0,
            "", 0);
    }

    for (uint i = 0; i < IPTV_SOCKET_COUNT; i++)
    {
        QUrl url = tuning.GetURL(i);
        if (url.port() < 0)
            continue;

        m_sockets[i] = new QUdpSocket();
        m_read_helpers[i] = new IPTVStreamHandlerReadHelper(
            this, m_sockets[i], i);

        // we need to open the descriptor ourselves so we
        // can set some socket options
        int fd = socket(AF_INET, SOCK_DGRAM, 0); // create IPv4 socket
        if (fd < 0)
        {
            LOG(VB_GENERAL, LOG_ERR, LOC +
                "Unable to create socket " + ENO);
            continue;
        }
        int buf_size = 2 * 1024 * max(tuning.GetBitrate(i)/1000, 500U);
        if (!tuning.GetBitrate(i))
            buf_size = 2 * 1024 * 1024;
        int ok = setsockopt(fd, SOL_SOCKET, SO_RCVBUF,
                            (char *)&buf_size, sizeof(buf_size));
        if (ok)
        {
            LOG(VB_GENERAL, LOG_INFO, LOC +
                QString("Increasing buffer size to %1 failed")
                .arg(buf_size) + ENO);
        }
        /*
          int broadcast = 1;
          ok = setsockopt(fd, SOL_SOCKET, SO_BROADCAST,
          (char *)&broadcast, sizeof(broadcast));
          if (ok)
          {
          LOG(VB_GENERAL, LOG_INFO, LOC +
          QString("Enabling broadcast failed") + ENO);
          }
        */
        m_sockets[i]->setSocketDescriptor(
            fd, QAbstractSocket::UnconnectedState, QIODevice::ReadOnly);

        m_sockets[i]->bind(QHostAddress::Any, url.port());

        QHostAddress dest_addr(tuning.GetURL(i).host());

        if (dest_addr != QHostAddress::Any)
        {
            //m_sockets[i]->joinMulticastGroup(dest_addr); // needs Qt 4.8
            LOG(VB_GENERAL, LOG_INFO, LOC + QString("Joining %1")
                .arg(dest_addr.toString()));
            struct ip_mreq imr;
            memset(&imr, 0, sizeof(struct ip_mreq));
            imr.imr_multiaddr.s_addr = inet_addr(
                dest_addr.toString().toLatin1().constData());
            imr.imr_interface.s_addr = htonl(INADDR_ANY);
            if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
				(const char *)&imr, sizeof(imr)) < 0)
            {
                LOG(VB_GENERAL, LOG_ERR, LOC +
                    "setsockopt - IP_ADD_MEMBERSHIP " + ENO);
            }
        }

        if (!url.userInfo().isEmpty())
            m_sender[i] = QHostAddress(url.userInfo());
    }
    if (m_use_rtp_streaming)
        m_buffer = new RTPPacketBuffer(tuning.GetBitrate(0));
    else
        m_buffer = new UDPPacketBuffer(tuning.GetBitrate(0));
    m_write_helper = new IPTVStreamHandlerWriteHelper(this);
    m_write_helper->Start();

    bool error = false;
    if (rtsp)
    {
        // Start Streaming
        if (!rtsp->Setup(m_sockets[0]->localPort(),
                         m_sockets[1]->localPort()) ||
            !rtsp->Play())
        {
            LOG(VB_RECORD, LOG_ERR, LOC +
                "Starting recording (RTP initialization failed). Aborting.");
            error = true;
        }
    }

    if (!error)
    {
        // Enter event loop
        exec();
    }

    // Clean up
    for (uint i = 0; i < IPTV_SOCKET_COUNT; i++)
    {
        if (m_sockets[i])
        {
            delete m_sockets[i];
            m_sockets[i] = NULL;
            delete m_read_helpers[i];
            m_read_helpers[i] = NULL;
        }
    }
    delete m_buffer;
    m_buffer = NULL;
    delete m_write_helper;
    m_write_helper = NULL;

    if (rtsp)
    {
        rtsp->Teardown();
        delete rtsp;
    }

    SetRunning(false, false, false);
    RunEpilog();
}
Beispiel #24
0
void Connection::slot_connectToHost(QString addr, quint16 port)
{
    qDebug() << "Connection::slot_connectToHost()";
    this->connectToHost(QHostAddress(addr), port);
}
void MythSocket::ConnectToHostReal(QHostAddress addr, quint16 port, bool *ret)
{
    if (m_tcpSocket->state() == QAbstractSocket::ConnectedState)
    {
        LOG(VB_SOCKET, LOG_ERR, LOC +
            "connect() called with already open socket, closing");
        m_tcpSocket->close();
    }

    s_loopbackCacheLock.lock();
    bool usingLoopback = s_loopbackCache.contains(addr.toString());
    s_loopbackCacheLock.unlock();

    if (usingLoopback)
    {
        addr = QHostAddress(s_loopbackCache.value(addr.toString()));
    }
    else
    {
        QList<QHostAddress> localIPs = QNetworkInterface::allAddresses();
        for (int i = 0; i < localIPs.count() && !usingLoopback; ++i)
        {
            if (addr == localIPs[i])
            {
                QHostAddress::SpecialAddress loopback = QHostAddress::LocalHost;
                if (addr.protocol() == QAbstractSocket::IPv6Protocol)
                    loopback = QHostAddress::LocalHostIPv6;

                QMutexLocker locker(&s_loopbackCacheLock);
                s_loopbackCache[addr.toString()] = loopback;
                addr = QHostAddress(loopback);
                usingLoopback = true;
            }
        }
    }

    if (usingLoopback)
    {
        LOG(VB_SOCKET, LOG_INFO, LOC +
            "IP is local, using loopback address instead");
    }

    LOG(VB_SOCKET, LOG_INFO, LOC + QString("attempting connect() to (%1:%2)")
        .arg(addr.toString()).arg(port));

    m_tcpSocket->connectToHost(addr, port, QAbstractSocket::ReadWrite);

    bool ok = m_tcpSocket->waitForConnected();

    if (ok)
    {
        LOG(VB_SOCKET, LOG_INFO, LOC + QString("Connected to (%1:%2)")
            .arg(addr.toString()).arg(port));
    }
    else
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("Failed to connect to (%1:%2) %3")
            .arg(addr.toString()).arg(port)
            .arg(m_tcpSocket->errorString()));
    }

    *ret = ok;
}
QT_BEGIN_NAMESPACE

void QDnsLookupRunnable::query(const int requestType, const QByteArray &requestName, QDnsLookupReply *reply)
{
    // Perform DNS query.
    PDNS_RECORD dns_records = 0;
    const QString requestNameUtf16 = QString::fromUtf8(requestName.data(), requestName.size());
    const DNS_STATUS status = DnsQuery_W(reinterpret_cast<const wchar_t*>(requestNameUtf16.utf16()), requestType, DNS_QUERY_STANDARD, NULL, &dns_records, NULL);
    switch (status) {
    case ERROR_SUCCESS:
        break;
    case DNS_ERROR_RCODE_FORMAT_ERROR:
        reply->error = QDnsLookup::InvalidRequestError;
        reply->errorString = tr("Server could not process query");
        return;
    case DNS_ERROR_RCODE_SERVER_FAILURE:
        reply->error = QDnsLookup::ServerFailureError;
        reply->errorString = tr("Server failure");
        return;
    case DNS_ERROR_RCODE_NAME_ERROR:
        reply->error = QDnsLookup::NotFoundError;
        reply->errorString = tr("Non existent domain");
        return;
    case DNS_ERROR_RCODE_REFUSED:
        reply->error = QDnsLookup::ServerRefusedError;
        reply->errorString = tr("Server refused to answer");
        return;
    default:
        reply->error = QDnsLookup::InvalidReplyError;
        reply->errorString = QSystemError(status, QSystemError::NativeError).toString();
        return;
    }

    // Extract results.
    for (PDNS_RECORD ptr = dns_records; ptr != NULL; ptr = ptr->pNext) {
        const QString name = QUrl::fromAce( QString::fromWCharArray( ptr->pName ).toLatin1() );
        if (ptr->wType == QDnsLookup::A) {
            QDnsHostAddressRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QHostAddress(ntohl(ptr->Data.A.IpAddress));
            reply->hostAddressRecords.append(record);
        } else if (ptr->wType == QDnsLookup::AAAA) {
            Q_IPV6ADDR addr;
            memcpy(&addr, &ptr->Data.AAAA.Ip6Address, sizeof(Q_IPV6ADDR));

            QDnsHostAddressRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QHostAddress(addr);
            reply->hostAddressRecords.append(record);
        } else if (ptr->wType == QDnsLookup::CNAME) {
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QUrl::fromAce(QString::fromWCharArray(ptr->Data.Cname.pNameHost).toLatin1());
            reply->canonicalNameRecords.append(record);
        } else if (ptr->wType == QDnsLookup::MX) {
            QDnsMailExchangeRecord record;
            record.d->name = name;
            record.d->exchange = QUrl::fromAce(QString::fromWCharArray(ptr->Data.Mx.pNameExchange).toLatin1());
            record.d->preference = ptr->Data.Mx.wPreference;
            record.d->timeToLive = ptr->dwTtl;
            reply->mailExchangeRecords.append(record);
        } else if (ptr->wType == QDnsLookup::NS) {
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QUrl::fromAce(QString::fromWCharArray(ptr->Data.Ns.pNameHost).toLatin1());
            reply->nameServerRecords.append(record);
        } else if (ptr->wType == QDnsLookup::PTR) {
            QDnsDomainNameRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            record.d->value = QUrl::fromAce(QString::fromWCharArray(ptr->Data.Ptr.pNameHost).toLatin1());
            reply->pointerRecords.append(record);
        } else if (ptr->wType == QDnsLookup::SRV) {
            QDnsServiceRecord record;
            record.d->name = name;
            record.d->target = QUrl::fromAce(QString::fromWCharArray(ptr->Data.Srv.pNameTarget).toLatin1());
            record.d->port = ptr->Data.Srv.wPort;
            record.d->priority = ptr->Data.Srv.wPriority;
            record.d->timeToLive = ptr->dwTtl;
            record.d->weight = ptr->Data.Srv.wWeight;
            reply->serviceRecords.append(record);
        } else if (ptr->wType == QDnsLookup::TXT) {
            QDnsTextRecord record;
            record.d->name = name;
            record.d->timeToLive = ptr->dwTtl;
            for (unsigned int i = 0; i < ptr->Data.Txt.dwStringCount; ++i) {
                record.d->values << QString::fromWCharArray((ptr->Data.Txt.pStringArray[i])).toLatin1();;
            }
            reply->textRecords.append(record);
        }
    }

    DnsRecordListFree(dns_records, DnsFreeRecordList);
}
Beispiel #27
0
void GyroDataWidget::on_sb_gyro_data_valueChanged(int arg1)
{
	if(!m_model)
		return;
	m_model->set_address(QHostAddress(ui->le_ip_gyro_data->text()), ui->sb_gyro_data->value());
}
Beispiel #28
0
/*!
    \internal
*/
void QInterProcessChannel::init()
{
    while ( isRunning() )
        quit();
    
    if ( pServerTimer )
    {
        pServerTimer->stop();
        delete pServerTimer;
        pServerTimer = 0;
    }
    
    bool ok = true;
    
    m_port = 0;
    m_addr = QHostAddress::LocalHost;
    
    pServer = new QTcpServer(this);
    pServer->listen(m_addr, m_port);
    
    connect(pServer , SIGNAL( newConnection() ),
            this    , SLOT  ( connection() ) );
    
    if ( QFile::exists(rcFile) )
    {
        /*
            found a server config file, let us assume it is from a running server
        */
        //qDebug("checking old server...");
        
        QSettings conf(rcFile, QSettings::IniFormat);
        
        m_port = conf.value("port").toUInt();
        m_addr = QHostAddress(conf.value("address").toString());
        
        QTcpSocket *pSocket = new QTcpSocket(this);
        
        if ( !m_addr.isNull() && m_port )
        {
            pSocket->connectToHost(m_addr, m_port);
            ok = pSocket->waitForConnected(WAIT_TIMEOUT);
            
            if ( ok ) ok &= (bool)pSocket->write("--check");
            if ( ok ) ok &= (bool)pSocket->waitForBytesWritten(WAIT_TIMEOUT);
            if ( ok ) ok &= (bool)pSocket->waitForReadyRead(WAIT_TIMEOUT);
            if ( ok ) ok &= (pSocket->readAll() == "[ALIVE]");
            
        } else {
            ok = false;
        }
        
        if ( !ok )
        {
            QFile::remove(rcFile);
        }
        
        pSocket->disconnectFromHost();
        delete pSocket;
    }
    
    if ( !QFile::exists(rcFile) )
    {
        // no server found... Create one
        //qDebug("setting up new server...");
        
        m_port = pServer->serverPort();
        m_addr = pServer->serverAddress();
        
        QSettings conf(rcFile, QSettings::IniFormat);
        conf.setValue("port", m_port);
        conf.setValue("address", m_addr.toString());
        
        emit gotServerRole();
        emit serverRoleChanged(true);
    } else {
        // server found we'll hook on it later on...
        pServer->close();
        pServer = 0;
        
        emit serverRoleChanged(false);
    }
    
    start();
}
void tst_QNetworkAddressEntry::prefixAndNetmask_data()
{
    QTest::addColumn<QHostAddress>("ip");
    QTest::addColumn<QHostAddress>("netmask");
    QTest::addColumn<int>("prefix");

    // IPv4 set:
    QHostAddress ipv4(QHostAddress::LocalHost);
    QTest::newRow("v4/0") << ipv4 << QHostAddress(QHostAddress::AnyIPv4) << 0;
    QTest::newRow("v4/32") << ipv4 << QHostAddress("255.255.255.255") << 32;
    QTest::newRow("v4/24") << ipv4 << QHostAddress("255.255.255.0") << 24;
    QTest::newRow("v4/23") << ipv4 << QHostAddress("255.255.254.0") << 23;
    QTest::newRow("v4/20") << ipv4 << QHostAddress("255.255.240.0") << 20;
    QTest::newRow("v4/invalid1") << ipv4 << QHostAddress(QHostAddress::LocalHost) << -1;
    QTest::newRow("v4/invalid2") << ipv4 << QHostAddress(QHostAddress::AnyIPv6) << -1;
    QTest::newRow("v4/invalid3") << ipv4 << QHostAddress("255.255.253.0") << -1;
    QTest::newRow("v4/invalid4") << ipv4 << QHostAddress() << -2;
    QTest::newRow("v4/invalid5") << ipv4 << QHostAddress() << 33;

    // IPv6 set:
    QHostAddress ipv6(QHostAddress::LocalHostIPv6);
    QTest::newRow("v6/0") << ipv6 << QHostAddress(QHostAddress::AnyIPv6) << 0;
    QTest::newRow("v6/128") << ipv6 << QHostAddress("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") << 128;
    QTest::newRow("v6/64") << ipv6 << QHostAddress("ffff:ffff:ffff:ffff::") << 64;
    QTest::newRow("v6/63") << ipv6 << QHostAddress("ffff:ffff:ffff:fffe::") << 63;
    QTest::newRow("v6/60") << ipv6 << QHostAddress("ffff:ffff:ffff:fff0::") << 60;
    QTest::newRow("v6/48") << ipv6 << QHostAddress("ffff:ffff:ffff::") << 48;
    QTest::newRow("v6/3") << ipv6 << QHostAddress("e000::") << 3;
    QTest::newRow("v6/invalid1") << ipv6 << QHostAddress(QHostAddress::LocalHostIPv6) << -1;
    QTest::newRow("v6/invalid2") << ipv6 << QHostAddress(QHostAddress::Any) << -1;
    QTest::newRow("v6/invalid3") << ipv6 << QHostAddress("fffd::") << -1;
    QTest::newRow("v6/invalid4") << ipv6 << QHostAddress() << -2;
    QTest::newRow("v6/invalid5") << ipv6 << QHostAddress() << 129;
}
Beispiel #30
0
void Servatrice::updateServerList()
{
    qDebug() << "Updating server list...";

    serverListMutex.lock();
    serverList.clear();

    QSqlQuery *query = servatriceDatabaseInterface->prepareQuery("select id, ssl_cert, hostname, address, game_port, control_port from {prefix}_servers order by id asc");
    servatriceDatabaseInterface->execSqlQuery(query);
    while (query->next()) {
        ServerProperties prop(query->value(0).toInt(), QSslCertificate(query->value(1).toString().toUtf8()), query->value(2).toString(), QHostAddress(query->value(3).toString()), query->value(4).toInt(), query->value(5).toInt());
        serverList.append(prop);
        qDebug() << QString("#%1 CERT=%2 NAME=%3 IP=%4:%5 CPORT=%6").arg(prop.id).arg(QString(prop.cert.digest().toHex())).arg(prop.hostname).arg(prop.address.toString()).arg(prop.gamePort).arg(prop.controlPort);
    }

    serverListMutex.unlock();
}