QT_BEGIN_NAMESPACE //#define QHOSTINFO_DEBUG QHostInfo QHostInfoAgent::fromName(const QString &hostName) { QHostInfo results; QHostAddress address; if (address.setAddress(hostName)) { // Reverse lookup // TODO: is there a replacement for getnameinfo for winrt? Q_UNIMPLEMENTED(); return results; } QByteArray aceHostname = QUrl::toAce(hostName); results.setHostName(hostName); if (aceHostname.isEmpty()) { results.setError(QHostInfo::HostNotFound); results.setErrorString(hostName.isEmpty() ? tr("No host name given") : tr("Invalid hostname")); return results; } ComPtr<IHostNameFactory> hostnameFactory; HRESULT hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(), IID_PPV_ARGS(&hostnameFactory)); Q_ASSERT_X(SUCCEEDED(hr), Q_FUNC_INFO, qPrintable(qt_error_string(hr))); ComPtr<IHostName> host; HStringReference hostNameRef((const wchar_t*)hostName.utf16()); hostnameFactory->CreateHostName(hostNameRef.Get(), &host); ComPtr<IDatagramSocketStatics> datagramSocketStatics; GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(), &datagramSocketStatics); ComPtr<IAsyncOperation<IVectorView<EndpointPair *> *>> op; datagramSocketStatics->GetEndpointPairsAsync(host.Get(), HString::MakeReference(L"0").Get(), &op); ComPtr<IVectorView<EndpointPair *>> endpointPairs; hr = op->GetResults(&endpointPairs); int waitCount = 0; while (hr == E_ILLEGAL_METHOD_CALL) { WaitForSingleObjectEx(GetCurrentThread(), 50, FALSE); hr = op->GetResults(&endpointPairs); if (++waitCount > 1200) // Wait for 1 minute max return results; } if (!endpointPairs) return results; unsigned int size; endpointPairs->get_Size(&size); QList<QHostAddress> addresses; for (unsigned int i = 0; i < size; ++i) { ComPtr<IEndpointPair> endpointpair; endpointPairs->GetAt(i, &endpointpair); ComPtr<IHostName> remoteHost; endpointpair->get_RemoteHostName(&remoteHost); if (!remoteHost) continue; HostNameType type; remoteHost->get_Type(&type); if (type == HostNameType_DomainName) continue; HString name; remoteHost->get_CanonicalName(name.GetAddressOf()); UINT32 length; PCWSTR rawString = name.GetRawBuffer(&length); QHostAddress addr; addr.setAddress(QString::fromWCharArray(rawString, length)); if (!addresses.contains(addr)) addresses.append(addr); } results.setAddresses(addresses); return results; }
std::vector<ServerList_st>& cConfig::serverList() { static unsigned int lastIpCheck = 0; static bool dynamicIP = false; if ( serverList_.empty() || ( dynamicIP && lastIpCheck <= Server::instance()->time() ) ) // Empty? Try to load { serverList_.clear(); bool bKeepLooping = true; unsigned int i = 1; do { QString tmp = getString( "LoginServer", QString( "Shard %1" ).arg( i++ ), QString::null, false ).simplifyWhiteSpace(); bKeepLooping = !tmp.isEmpty(); if ( bKeepLooping ) // valid data. { QStringList strList = QStringList::split( "=", tmp ); if ( strList.size() == 2 ) { ServerList_st server; server.sServer = strList[0]; QStringList strList2 = QStringList::split( ",", strList[1].stripWhiteSpace() ); QHostAddress host; host.setAddress( strList2[0] ); server.sIP = strList2[0]; server.ip = resolveName( server.sIP ); bool ok = false; server.uiPort = strList2[1].toUShort( &ok ); if ( !ok ) server.uiPort = 2593; // Unspecified defaults to 2593 // This code will retrieve the first // valid Internet IP it finds // and replace a 0.0.0.0 with it if ( ( ( server.ip == 0 ) && ( lastIpCheck <= Server::instance()->time() ) ) ) { dynamicIP = true; hostent* hostinfo; char name[256]; // We check for a new IP max. every 30 minutes // So we have a max. of 30 minutes downtime lastIpCheck = Server::instance()->time() + ( MY_CLOCKS_PER_SEC * 30 * 60 ); // WSA Is needed for this :/ if ( !gethostname( name, sizeof( name ) ) ) { hostinfo = gethostbyname( name ); if ( hostinfo ) { Q_UINT32 i = 0; while ( hostinfo->h_addr_list[i] ) { // Check if it's an INTERNET ADDRESS char* hIp = inet_ntoa( *( struct in_addr* ) hostinfo->h_addr_list[i++] ); host.setAddress( hIp ); Q_UINT32 ip = host.ip4Addr(); Q_UINT8 part1 = ( ip & 0xFF000000 ) >> 24; Q_UINT8 part2 = ( ip & 0x00FF0000 ) >> 16; if ( ( part1 == 127 ) || //this one is class A too. ( part1 == 10 ) || ( ( part1 == 192 ) && ( part2 == 168 ) ) || ( ( part1 == 172 ) && ( part2 >= 16 ) && ( part2 <= 31 ) ) || ( ( part1 == 169 ) && ( part2 == 254 ) ) // DHCP Space Stuff ) { continue; } // We are now certain that it's a valid INET ip server.ip = ip; break; } } } // Fall back to localhost if ( !server.ip ) { server.ip = 0x7F000001; server.sIP = "127.0.0.1"; } } serverList_.push_back( server ); }
bool TcpServerBalancer::listen(const QString &line, Protocol *protocol, bool secure) { m_protocol = protocol; int commaPos = line.indexOf(QLatin1Char(',')); const QString addressPortString = line.mid(0, commaPos); QString addressString; int closeBracketPos = addressPortString.indexOf(QLatin1Char(']')); if (closeBracketPos != -1) { if (!line.startsWith(QLatin1Char('['))) { std::cerr << "Failed to parse address: " << qPrintable(addressPortString) << std::endl; exit(1); } addressString = addressPortString.mid(1, closeBracketPos - 1); } else { addressString = addressPortString.section(QLatin1Char(':'), 0, -2); } const QString portString = addressPortString.section(QLatin1Char(':'), -1); QHostAddress address; if (addressString.isEmpty()) { address = QHostAddress(QHostAddress::Any); } else { address.setAddress(addressString); } bool ok; quint16 port = portString.toUInt(&ok); if (!ok || (port < 1 || port > 35554)) { port = 80; } #ifndef QT_NO_SSL if (secure) { if (commaPos == -1) { std::cerr << "No SSL certificate specified" << std::endl; exit(1); } const QString sslString = line.mid(commaPos + 1); const QString certPath = sslString.section(QLatin1Char(','), 0, 0); QFile certFile(certPath); if (!certFile.open(QFile::ReadOnly)) { std::cerr << "Failed to open SSL certificate" << qPrintable(certPath) << qPrintable(certFile.errorString()) << std::endl; exit(1); } QSslCertificate cert(&certFile); if (cert.isNull()) { std::cerr << "Failed to parse SSL certificate" << std::endl; exit(1); } const QString keyPath = sslString.section(QLatin1Char(','), 1, 1); QFile keyFile(keyPath); if (!keyFile.open(QFile::ReadOnly)) { std::cerr << "Failed to open SSL private key" << qPrintable(keyPath) << qPrintable(keyFile.errorString()) << std::endl; exit(1); } QSslKey key(&keyFile, QSsl::Rsa); if (key.isNull()) { std::cerr << "Failed to parse SSL private key" << std::endl; exit(1); } m_sslConfiguration = new QSslConfiguration; m_sslConfiguration->setLocalCertificate(cert); m_sslConfiguration->setPrivateKey(key); m_sslConfiguration->setPeerVerifyMode(QSslSocket::VerifyNone); // prevent asking for client certificate if (m_wsgi->httpsH2()) { m_sslConfiguration->setAllowedNextProtocols({ QByteArrayLiteral("h2") }); } } #endif // QT_NO_SSL m_address = address; m_port = port; #ifdef Q_OS_LINUX if (m_wsgi->reusePort()) { int socket = listenReuse(address, port, false); if (socket > 0) { setSocketDescriptor(socket); pauseAccepting(); } else { std::cerr << "Failed to listen on TCP: " << qPrintable(line) << " : " << qPrintable(errorString()) << std::endl; exit(1); } } else { #endif bool ret = QTcpServer::listen(address, port); if (ret) { pauseAccepting(); } else { std::cerr << "Failed to listen on TCP: " << qPrintable(line) << " : " << qPrintable(errorString()) << std::endl; exit(1); } #ifdef Q_OS_LINUX } #endif m_serverName = serverAddress().toString() + QLatin1Char(':') + QString::number(port); return true; }
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; }
int main(int argc, char *argv[]) { QApplication a(argc, argv); QCommandLineParser cmdline_parser; // cmdline_parser.addHelpOption(); // create commandline options // QCommandLineOption serverOption(QStringList() << "h" << "host", "NewtonCam server address", "host name or IP", "127.0.0.1"); QString str; str.setNum(NETPROTOCOL_DEFAULT_PORT); QCommandLineOption portOption(QStringList() << "p" << "port", "NewtonCam server port", "numeric value", str); str.setNum(SERVERGUI_DEFAULT_FONTSIZE); QCommandLineOption fontOption(QStringList() << "f" << "fontsize", "GUI font size", "numeric value", str); str.setNum(SERVERGUI_DEFAULT_FONTSIZE-2); QCommandLineOption statusfontOption(QStringList() << "s" << "statusfontsize", "GUI status font size", "numeric value", str); str.setNum(SERVERGUI_DEFAULT_FONTSIZE); QCommandLineOption logfontOption(QStringList() << "l" << "logfontsize", "GUI log window font size", "numeric value", str); QCommandLineOption xcoordOption(QStringList() << "x" << "xpos", "GUI window x-coordinate position", "numeric vlue", str); QCommandLineOption ycoordOption(QStringList() << "y" << "ypos", "GUI window x-coordinate position", "numeric vlue", str); cmdline_parser.addOption(portOption); cmdline_parser.addOption(fontOption); cmdline_parser.addOption(statusfontOption); cmdline_parser.addOption(logfontOption); cmdline_parser.addOption(xcoordOption); cmdline_parser.addOption(ycoordOption); cmdline_parser.addPositionalArgument("IP-address", "NewtonCam server address (default 127.0.0.1)"); cmdline_parser.process(a); quint16 port; bool ok; port = cmdline_parser.value(portOption).toUInt(&ok); if ( !ok ) { // QMessageBox::StandardButton bt = QMessageBox::critical(0,"Error","Invalid port value!"); exit(NEWTONGUI_ERROR_INVALID_PORT); } int fontsize = cmdline_parser.value(fontOption).toInt(&ok); if ( !ok ) { // QMessageBox::StandardButton bt = QMessageBox::critical(0,"Error","Invalid GUI fontsize value!"); exit(NEWTONGUI_ERROR_INVALID_FONTSIZE); } int statusFontsize = cmdline_parser.value(statusfontOption).toInt(&ok); if ( !ok ) { QMessageBox::critical(0,"Error","Invalid GUI status fontsize value!"); exit(NEWTONGUI_ERROR_INVALID_FONTSIZE); } int logFontsize = cmdline_parser.value(logfontOption).toInt(&ok); if ( !ok ) { QMessageBox::critical(0,"Error","Invalid GUI log window fontsize value!"); exit(NEWTONGUI_ERROR_INVALID_FONTSIZE); } int xcoord; bool isX = false; if ( !cmdline_parser.value(xcoordOption).isEmpty() ) { xcoord = cmdline_parser.value(xcoordOption).toInt(&ok); if ( !ok ) { QMessageBox::critical(0,"Error","Invalid x-coordinate of GUI window!"); exit(NEWTONGUI_ERROR_INVALID_COORDINATE); } isX = true; } int ycoord; bool isY = false; if ( !cmdline_parser.value(ycoordOption).isEmpty() ) { ycoord = cmdline_parser.value(ycoordOption).toInt(&ok); if ( !ok ) { QMessageBox::critical(0,"Error","Invalid y-coordinate of GUI window!"); exit(NEWTONGUI_ERROR_INVALID_COORDINATE); } isY = true; } QHostAddress addr; QStringList pos_arg = cmdline_parser.positionalArguments(); if ( pos_arg.length() == 0 ) { str = "127.0.0.1"; addr.setAddress(str); } else { str = pos_arg[0]; QRegExp rx("\\s*\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\s*"); if ( !rx.exactMatch(str) ) { // do DNS look-up QHostInfo info = QHostInfo::fromName(str.trimmed()); if ( info.addresses().isEmpty() ) { QMessageBox::critical(0,"Error","Invalid server hostname!"); exit(NEWTONGUI_ERROR_INVALID_HOSTNAME); } addr = info.addresses().first(); } else { addr.setAddress(str); } } NewtonGui ng(fontsize); ng.SetFonts(fontsize,statusFontsize,logFontsize); QPoint gui_pos = ng.pos(); if ( isX ) gui_pos.setX(xcoord); if ( isY ) gui_pos.setY(ycoord); if ( isX || isY ) ng.move(gui_pos); ng.show(); // QObject::connect(&ng,&NewtonGui::Error,[=](int err){exit(err);}); str = QDateTime::currentDateTime().toString(" dd-MM-yyyy hh:mm:ss"); ng.LogMessage("<b> " + str + ":</b> Trying to connect to NewtonCam server at " + addr.toString() + " ..."); a.processEvents(); // to draw the main window and show start message ng.Connect(addr,port); return a.exec(); }
std::vector<ServerList_st>& cSrvParams::serverList() { // We need a way to get this stuff for linux too #ifndef __unix__ static UINT32 lastIpCheck = 0; static UINT32 inetIp = 0; #endif if ( serverList_.empty() ) // Empty? Try to load { setGroup("LoginServer"); bool bKeepLooping = true; unsigned int i = 1; do { QString tmp = getString(QString("Shard %1").arg(i++), "").simplifyWhiteSpace(); bKeepLooping = ( tmp != "" ); if ( bKeepLooping ) // valid data. { QStringList strList = QStringList::split("=", tmp); if ( strList.size() == 2 ) { ServerList_st server; server.sServer = strList[0]; QStringList strList2 = QStringList::split(",", strList[1].stripWhiteSpace()); QHostAddress host; host.setAddress( strList2[0] ); server.sIP = strList2[0]; server.ip = resolveName( server.sIP ); bool ok = false; server.uiPort = strList2[1].toUShort(&ok); if ( !ok ) server.uiPort = 2593; // Unspecified defaults to 2593 // This code will retrieve the first // valid Internet IP it finds // and replace a 0.0.0.0 with it #ifndef __unix__ if( ( server.ip == 0 ) && ( lastIpCheck <= uiCurrentTime ) ) { hostent *hostinfo; char name[256]; // We check for a new IP max. every 30 minutes // So we have a max. of 30 minutes downtime lastIpCheck = uiCurrentTime + (MY_CLOCKS_PER_SEC*30*60); // WSA Is needed for this :/ if( !gethostname( name, sizeof( name ) ) ) { hostinfo = gethostbyname( name ); if( hostinfo ) { UINT32 i = 0; while( hostinfo->h_addr_list[i] ) { // Check if it's an INTERNET ADDRESS char *hIp = inet_ntoa( *(struct in_addr *)hostinfo->h_addr_list[i++] ); host.setAddress( hIp ); UINT32 ip = host.ip4Addr(); UINT8 part1 = ( ip & 0xFF000000 ) >> 24; UINT8 part2 = ( ip & 0x00FF0000 ) >> 16; if ( ( part1 == 127 ) || //this one is class A too. ( part1 == 10 ) || ( ( part1 == 192 ) && ( part2 == 168 ) ) || ( ( part1 == 172 ) && ( part2 == 16 ) ) ) continue; // We are now certain that it's a valid INET ip server.ip = ip; inetIp = ip; } } } else if( inetIp ) server.sIP = inetIp; }
bool CSearchManager::OnQueryAcknowledge(G2Packet* pPacket, CEndPoint& addr, QUuid& oGUID) { if(!pPacket->m_bCompound) { return false; } pPacket->SkipCompound(); // skip children to get search GUID if(pPacket->GetRemaining() < 16) // must be at least 16 bytes for GUID { return false; } oGUID = pPacket->ReadGUID(); // Read search GUID QMutexLocker l(&m_pSection); if(CManagedSearch* pSearch = Find(oGUID)) // is it our Query Ack? { // YES, this is ours, let's parse the packet and process it CEndPoint oFromIp = addr; QList<QHostAddress> lDone; quint32 nRetryAfter = 0; qint64 tAdjust = 0; quint32 tNow = time(0); quint32 nHubs = 0, nLeaves = 0, nSuggestedHubs = 0; pPacket->m_nPosition = 0; // reset position char szType[9]; quint32 nLength = 0, nNext = 0; while(pPacket->ReadPacket(&szType[0], nLength)) { nNext = pPacket->m_nPosition + nLength; if(strcmp("D", szType) == 0 && nLength >= 4) { QHostAddress ha; if( nLength >= 16 ) { // IPv6 Q_IPV6ADDR nIP; pPacket->Read(&nIP, 16); ha.setAddress(nIP); if( nLength >= 18 ) { quint16 nPort = pPacket->ReadIntLE<quint16>(); CEndPoint a(nIP, nPort); HostCache.Add(a, tNow); } if(nLength >= 20) { nLeaves += pPacket->ReadIntLE<quint16>(); } } else { // IPv4 quint32 nIP = pPacket->ReadIntBE<quint32>(); ha.setAddress(nIP); if(nLength >= 6) { quint16 nPort = pPacket->ReadIntLE<quint16>(); CEndPoint a(nIP, nPort); HostCache.Add(a, tNow); } if(nLength >= 8) { nLeaves += pPacket->ReadIntLE<quint16>(); } } lDone.append(ha); nHubs++; } else if(strcmp("S", szType) == 0 && nLength >= 6) { CEndPoint a; pPacket->ReadHostAddress(&a, !(nLength >= 18)); quint32 tSeen = (nLength >= (a.protocol() == 0 ? 10 : 22)) ? pPacket->ReadIntLE<quint32>() + tAdjust : tNow; HostCache.Add(a, tSeen); nSuggestedHubs++; } else if(strcmp("TS", szType) == 0 && nLength >= 4) { tAdjust = tNow - pPacket->ReadIntLE<quint32>(); } else if(strcmp("RA", szType) == 0 && nLength >= 2) { if(nLength >= 4) { nRetryAfter = pPacket->ReadIntLE<quint32>(); } else if(nLength >= 2) { nRetryAfter = pPacket->ReadIntLE<quint16>(); } CHostCacheHost* pHost = HostCache.Find(oFromIp); if(pHost) { pHost->m_tRetryAfter = tNow + nRetryAfter; } } else if(strcmp("FR", szType) == 0 && nLength >= 4) { if( nLength >= 16 ) { Q_IPV6ADDR ip; pPacket->Read(&ip, 16); oFromIp.setAddress(ip); } else { quint32 nFromIp = pPacket->ReadIntBE<quint32>(); oFromIp.setAddress(nFromIp); } } pPacket->m_nPosition = nNext; } // we already know QA GUID systemLog.postLog(LogSeverity::Debug, "Processing query acknowledge from %s (time adjust %+d seconds): %d hubs, %d leaves, %d suggested hubs, retry after %d seconds.", addr.toString().toAscii().constData(), int(tAdjust), nHubs, nLeaves, nSuggestedHubs, nRetryAfter); //qDebug("Processing query acknowledge from %s (time adjust %+d seconds): %d hubs, %d leaves, %d suggested hubs, retry after %d seconds.", // addr.toString().toAscii().constData(), int(tAdjust), nHubs, nLeaves, nSuggestedHubs, nRetryAfter); pSearch->m_nHubs += nHubs; pSearch->m_nLeaves += nLeaves; pSearch->OnHostAcknowledge(oFromIp, tNow); for(int i = 0; i < lDone.size(); i++) { pSearch->OnHostAcknowledge(lDone[i], tNow); } emit pSearch->StatsUpdated(); return false; } // not our ack - tell caller to route it return true; }
//获取通信参数,str为屏幕的settings str void CcomStatus::getCOMParaFromSettings(QString str) { QString str1; //int flag; QStringList screenGroups; //int screenSize; settings.beginGroup(str); settings.beginGroup("comTest"); //flag = settings.value("flag"); comThread->COM_Mode = settings.value("comMode").toInt(); comThread->COM_Port = settings.value("comPort").toString(); if(comThread->COM_Port EQ "") { if(getComPortList().count() > 0) comThread->COM_Port = getComPortList().at(0); //settings.setValue("comPort", comThread->COM_Port); } comThread->COM_Para.Addr = settings.value("screenID").toInt(); comThread->COM_Para.Baud = settings.value("baud").toInt(); comThread->Net_Para.IP = settings.value("ip").toInt(); settings.endGroup(); settings.endGroup(); screenNameEdit->clear(); paraEdit->clear(); statusEdit->clear(); progressBar->setValue(0); //------查找是第几号屏幕 int index = getScreenIndex(str); screenNameEdit->setText(QString::number(index) + tr("号屏幕")); //------------- if(comThread->COM_Mode EQ COM_MODE) { str1 = tr("串口通信方式, "); str1 += comThread->COM_Port + tr(" 波特率:"); if(comThread->COM_Para.Baud EQ 0) str1 += tr("57600"); else str1 += tr("9600"); paraEdit->append(str1); } else if(comThread->COM_Mode EQ ETH_MODE || comThread->COM_Mode EQ WIFI_MODE) { //INT8U ip[4]; INT32U IP; IP = comThread->Net_Para.IP; str1 = tr("目标地址:"); QHostAddress dstAddr; if(comThread->COM_Mode EQ ETH_MODE) dstAddr.setAddress(RevIP(IP)); else dstAddr.setAddress(DEF_WIFI_DST_IP); //192.168.1.15--固定使用该ip str1 += dstAddr.toString() + tr(":8000\r\n"); /* QHostInfo host = QHostInfo::fromName(QHostInfo::localHostName()); foreach (QHostAddress address, host.addresses()) str1 += QString(tr("本机:")) + address.toString() + tr(":") + QString::number(this->comThread->udpPort); */ paraEdit->append(str1); } }
bool CcomThread::sendFrame(char *data, int len, int bufLen) { int i,re; INT8U mode = COM_Mode; const char temp[3] = {0xEE, 0xEE, 0xEE}; this->timeOutFlag = 0; this->deniedFlag = 0; if(mode EQ PREVIEW_MODE)//预览模式 { Rcv_Frame_Proc(CH_SIM, (INT8U *)data, (INT16U)len, bufLen); //接收函数处理。在仿真情况下,将参数写入了硬盘文件。模拟写入EEROM return true; } else if(mode EQ SIM_MODE) //仿真模式 {/* for(i = 0; i < len; i ++) Com_Rcv_Byte(CH_SIM, *(data + i)); while(1) { Delay_ms(100); if(Screen_Status.Rcv_Flag EQ 0) //等待线程处理完该帧 break; } */ // Rcv_Frame_Proc(CH_SIM, (INT8U *)data, (INT16U)len, bufLen); //接收函数处理。在仿真情况下,将参数写入了硬盘文件。模拟写入EEROM for(i = 0; i < len; i ++) Com_Rcv_Byte(CH_SIM, *(data + i)); Screen_Com_Proc(); comReStr = tr("发送第") + QString::number(frameCounts + 1)+"/"+QString::number(totalFrameCounts)+tr("帧,等待应答..."); emit this->comStatusChanged(comReStr); frameCounts++; if((Rcv_Buf[FCMD] & 0xC0) EQ 0x40) //肯定应答 { emit comProgressChanged(100*frameCounts/totalFrameCounts); comReStr = tr("收到肯定应答"); emit this->comStatusChanged(comReStr); return true; } else if((Rcv_Buf[FCMD] & 0xC0) EQ 0x80) //否定应答 { comReStr = tr("收到否定应答"); this->deniedFlag = 1; comReStr += QString(":") + getRcvErrInfo(Rcv_Buf[FDATA]); emit this->comStatusChanged(comReStr); return false; } else { comReStr = tr("收到无效应答"); emit this->comStatusChanged(comReStr); return false; } } else if(mode EQ COM_MODE)//串口通信模式 { for(i = 0; i < 2; i ++) { port->write(temp, sizeof(temp)); port->write(data, len); if(i EQ 0) comReStr = tr("发送第") + QString::number(frameCounts + 1)+"/"+QString::number(totalFrameCounts)+tr("帧,等待应答...");// + QString::number(len); else comReStr = tr("重复发送第") + QString::number(frameCounts + 1)+"/"+QString::number(totalFrameCounts)+tr("帧,等待应答..."); emit this->comStatusChanged(comReStr); re = waitComRcv(comTimeOutSec); //等待应答 if(re > 0) { frameCounts++; emit comProgressChanged(100*frameCounts/totalFrameCounts); if((Rcv_Buf[FCMD] & 0xC0) EQ 0x40) //肯定应答 { comReStr = tr("收到肯定应答"); emit this->comStatusChanged(comReStr); return true; } else if((Rcv_Buf[FCMD] & 0xC0) EQ 0x80) //否定应答 { comReStr = tr("收到否定应答"); this->deniedFlag = 1; comReStr += QString(":") + getRcvErrInfo(Rcv_Buf[FDATA]); emit this->comStatusChanged(comReStr); return false; } else { comReStr = tr("收到无效应答"); emit this->comStatusChanged(comReStr); return false; } } } this->timeOutFlag = 1; //超时标志 comReStr = tr("等待应答超时"); emit this->comStatusChanged(comReStr); return false; } else if(mode EQ ETH_MODE || mode EQ WIFI_MODE)//以太网模式 { QHostAddress host; //host.setAddress("192.168.001.122");//Net_Para.IP); if(mode EQ ETH_MODE) host.setAddress(RevIP(Net_Para.IP)); else host.setAddress(DEF_WIFI_DST_IP); for(i = 0; i < 2; i ++) { //port->write(data, len); if(udpSocket->writeDatagram(data,len,host, 8000) != len)//将data中的数据发送 { comReStr = tr("发送数据失败"); emit this->comStatusChanged(comReStr); return false; } if(i EQ 0) comReStr = tr("发送第") + QString::number(frameCounts + 1)+"/"+QString::number(totalFrameCounts)+tr("帧,等待应答...");// + QString::number(len); else comReStr = tr("重复发送第") + QString::number(frameCounts + 1)+"/"+QString::number(totalFrameCounts)+tr("帧,等待应答..."); emit this->comStatusChanged(comReStr); re = waitComRcv(15); //等待应答 if(re > 0) { frameCounts++; emit comProgressChanged(100*frameCounts/totalFrameCounts); if((Rcv_Buf[FCMD] & 0xC0) EQ 0x40) //肯定应答 { comReStr = tr("收到肯定应答"); emit this->comStatusChanged(comReStr); return true; } else if((Rcv_Buf[FCMD] & 0xC0) EQ 0x80) //否定应答 { comReStr = tr("收到否定应答"); this->deniedFlag = 1; comReStr += QString(":") + getRcvErrInfo(Rcv_Buf[FDATA]); emit this->comStatusChanged(comReStr); return false; } else { comReStr = tr("收到无效应答"); emit this->comStatusChanged(comReStr); return false; } } } comReStr = tr("等待应答超时"); emit this->comStatusChanged(comReStr); return false; } else if(mode EQ GPRS_MODE) { } else if(mode EQ UDISK_MODE) { ASSERT_FAILED(); return false; } return true; }
QHostInfo QHostInfoAgent::fromName(const QString &hostName, QSharedPointer<QNetworkSession> networkSession) { QHostInfo results; // Connect to ESOCK RSocketServ socketServ(qt_symbianGetSocketServer()); RHostResolver hostResolver; int err; if (networkSession) err = QNetworkSessionPrivate::nativeOpenHostResolver(*networkSession, hostResolver, KAfInet, KProtocolInetUdp); else err = hostResolver.Open(socketServ, KAfInet, KProtocolInetUdp); if (err) { setError_helper(results, err); return results; } TNameEntry nameResult; #if defined(QHOSTINFO_DEBUG) qDebug("QHostInfoAgent::fromName(%s) looking up...", hostName.toLatin1().constData()); #endif QHostAddress address; if (address.setAddress(hostName)) { // Reverse lookup #if defined(QHOSTINFO_DEBUG) qDebug("(reverse lookup)"); #endif TInetAddr IpAdd; IpAdd.Input(qt_QString2TPtrC(hostName)); // Synchronous request. nameResult returns Host Name. err = hostResolver.GetByAddress(IpAdd, nameResult); if (err) { //for behavioural compatibility with Qt 4.7 and unix/windows //backends: don't report error, return ip address as host name results.setHostName(address.toString()); } else { results.setHostName(qt_TDesC2QString(nameResult().iName)); } 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; } // Call RHostResolver::GetByAddress, and place all IPv4 addresses at the start and // the IPv6 addresses at the end of the address list in results. // Synchronous request. err = hostResolver.GetByName(qt_QString2TPtrC(QString::fromLatin1(aceHostname)), nameResult); if (err) { setError_helper(results, err); return results; } QList<QHostAddress> hostAddresses; TInetAddr hostAdd = nameResult().iAddr; if (!(nameResult().iFlags & TNameRecord::EAlias) && !(hostAdd.IsUnspecified())) hostAddresses.append(qt_QHostAddressFromTInetAddr(hostAdd)); // Check if there's more than one IP address linkd to this name while (hostResolver.Next(nameResult) == KErrNone) { hostAdd = nameResult().iAddr; // Ensure that record is valid (not an alias and with length greater than 0) if (!(nameResult().iFlags & TNameRecord::EAlias) && !(hostAdd.IsUnspecified())) hostAddresses.append(qt_QHostAddressFromTInetAddr(hostAdd)); } hostResolver.Close(); results.setAddresses(hostAddresses); return results; }
/** * @see http://tools.ietf.org/html/rfc1928 * * The SOCKS request is formed as follows: * * +----+-----+-------+------+----------+----------+ * |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | * +----+-----+-------+------+----------+----------+ * | 1 | 1 | X'00' | 1 | Variable | 2 | * +----+-----+-------+------+----------+----------+ * * Where: * * o VER protocol version: X'05' * o CMD * o CONNECT X'01' * o BIND X'02' * o UDP ASSOCIATE X'03' * o RSV RESERVED * o ATYP address type of following address * o IP V4 address: X'01' * o DOMAINNAME: X'03' * o IP V6 address: X'04' * o DST.ADDR desired destination address * o DST.PORT desired destination port in network octet order * * The SOCKS server will typically evaluate the request based on source * and destination addresses, and return one or more reply messages, as * appropriate for the request type. * * In an address field (DST.ADDR, BND.ADDR), the ATYP field specifies * the type of address contained within the field: * * o X'01' * * the address is a version-4 IP address, with a length of 4 octets * * o X'03' * * the address field contains a fully-qualified domain name. The first * octet of the address field contains the number of octets of name that * follow, there is no terminating NUL octet. * * o X'04' * * the address is a version-6 IP address, with a length of 16 octets. */ void Worker::parseRequest(void) { int size = this->m_buf.size(); if (-1 == this->m_expected_length) { if (size > 4) { quint8 ver = static_cast<quint8>(this->m_buf.at(0)); quint8 rsv = static_cast<quint8>(this->m_buf.at(2)); quint8 atyp = static_cast<quint8>(this->m_buf.at(3)); if (ver != 5) { this->m_state = Worker::FatalErrorState; Q_EMIT this->error(Worker::ProtocolVersionMismatch); return; } if (rsv != 0) { this->m_state = Worker::FatalErrorState; Q_EMIT this->error(Worker::UnknownError); return; } switch (atyp) { case 1: // IPv4 address this->m_expected_length = 10; break; case 4: // IPv6 address this->m_expected_length = 22; break; case 3: // Domain name this->m_expected_length = 7 + static_cast<quint8>(this->m_buf.at(4)); break; default: this->m_state = Worker::FatalErrorState; Q_EMIT this->error(Worker::UnknownError); return; } } } if (this->m_expected_length != -1 && size > this->m_expected_length) { this->m_state = Worker::FatalErrorState; Q_EMIT this->error(Worker::TooMuchData); return; } QString address; quint16 port = 0; quint8 cmd = static_cast<quint8>(this->m_buf.at(1)); quint8 atyp = static_cast<quint8>(this->m_buf.at(3)); switch (atyp) { case 1: { QHostAddress a; quint32 addr; memcpy(&addr, this->m_buf.constData() + 4, sizeof(quint32)); memcpy(&port, this->m_buf.constData() + 8, sizeof(quint16)); a.setAddress(qFromBigEndian(addr)); address = a.toString(); break; } case 4: { QHostAddress a; quint8 addr[16]; memcpy(addr, this->m_buf.constData() + 4, 16); memcpy(&port, this->m_buf.constData() + 20, sizeof(quint16)); a.setAddress(addr); address = a.toString(); break; } case 3: { int len = static_cast<quint8>(this->m_buf.at(4)); QByteArray tmp = QByteArray(this->m_buf.constData() + 5, len); if (tmp.endsWith('.')) { tmp.chop(1); --len; } address = QString::fromLocal8Bit(tmp.constData(), len); memcpy(&port, this->m_buf.constData() + this->m_expected_length - 2, sizeof(quint16)); break; } default: Q_ASSERT(false); break; } this->m_expected_length = -1; this->m_buf.clear(); port = qFromBigEndian(port); if (cmd != 1) { // Connect char response[] = "\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00"; // Command not supported this->writeAndFlush(this->m_peer, response, 10); this->m_state = Worker::FatalErrorState; return; } this->m_connector = new SocketConnector(this); QHostAddress a; if (qobject_cast<QAbstractSocket*>(this->m_peer)) { a = (qobject_cast<QAbstractSocket*>(this->m_peer))->localAddress(); } if (!this->m_connector->createTcpSocket() || (!a.isNull() && !this->m_connector->bindTo(a))) { char response[] = "\x05\x01\x00\x01\x00\x00\x00\x00\x00\x00"; // General SOCKS server failure this->writeAndFlush(this->m_peer, response, 10); this->m_state = Worker::FatalErrorState; return; } this->m_state = Worker::RequestReceivedState; QObject::connect(this->m_connector, SIGNAL(connected()), this, SLOT(targetConnectedHandler())); QObject::connect(this->m_connector, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(targetConnectFailureHandler(QAbstractSocket::SocketError))); this->m_connector->connectToHost(address, port); }
void ContactsManager::ProbeAvailabilityForAll() { LOG(LOG_WARN, "######## PROBING CONTACTS - START ########"); if (!CONF.GetSipContactsProbing()) return; mContactsMutex.lock(); ContactsVector::iterator tIt, tItEnd = mContacts.end(); for (tIt = mContacts.begin(); tIt != tItEnd; tIt++) { if (!MEETING.IsLocalAddress(tIt->GetHostStdStr(), tIt->GetPortStdStr(), tIt->Transport)) { MEETING.SendAvailabilityProbe(tIt->GetUserStdStr(), tIt->GetHostStdStr(), tIt->GetPortStdStr(), tIt->Transport); } } mContactsMutex.unlock(); if(CONF.GetSipUnknownContactsProbing()) { /* * The following generates a storm of PROBE packets. * TODO: maybe we should limit this!? */ LOG(LOG_INFO, "Detecting unknown contacts..."); QList<QNetworkInterface> tLocalInterfaces = QNetworkInterface::allInterfaces (); QNetworkInterface tLocalInterface; foreach(tLocalInterface, tLocalInterfaces) { if((tLocalInterface.flags().testFlag(QNetworkInterface::IsUp)) && (tLocalInterface.flags().testFlag(QNetworkInterface::IsRunning)) && (!tLocalInterface.flags().testFlag(QNetworkInterface::IsLoopBack))) { QList<QNetworkAddressEntry> tLocalAddressEntries = tLocalInterface.addressEntries(); for (int i = 0; i < tLocalAddressEntries.size(); i++) { QHostAddress tHostAddress = tLocalAddressEntries[i].ip(); QHostAddress tHostAddressNetmask = tLocalAddressEntries[i].netmask(); QHostAddress tHostAddressNetwork; tHostAddressNetwork.setAddress(tHostAddress.toIPv4Address() & tHostAddressNetmask.toIPv4Address()); QString tAddress = tHostAddress.toString().toLower(); QString tNetmask = tHostAddressNetmask.toString().toLower(); if ((tHostAddress.protocol() == QAbstractSocket::IPv4Protocol) || ((tHostAddress.protocol() == QAbstractSocket::IPv6Protocol) && (!Socket::IsIPv6LinkLocal(tAddress.toStdString())))) { QHostAddress tCurrentProbeAddress; QHostAddress tCurrentProbeAddressNetwork; QHostAddress tNextProbeAddressNetwork;// to ignore broadcast addresses LOG(LOG_INFO, " ..local address: %s [%s]", tAddress.toStdString().c_str(), tNetmask.toStdString().c_str()); if(tHostAddress.protocol() == QAbstractSocket::IPv4Protocol) { quint32 tIPv4AddrNumber = tHostAddress.toIPv4Address(); quint32 tIPv4NetNumber = tHostAddressNetmask.toIPv4Address(); quint32 tIPv4AddrCurrentNumber = (tIPv4AddrNumber & tIPv4NetNumber); quint32 tIPv4AddrCurrentNumberNetwork = 0; tIPv4AddrCurrentNumber++; tIPv4AddrCurrentNumberNetwork = (tIPv4AddrCurrentNumber & tIPv4NetNumber); tCurrentProbeAddress.setAddress(tIPv4AddrCurrentNumber); tCurrentProbeAddressNetwork.setAddress(tIPv4AddrCurrentNumberNetwork); int tFoundAddresses = 0; do { if(tCurrentProbeAddressNetwork.toString() == tHostAddressNetwork.toString()) { tFoundAddresses++; LOG(LOG_INFO, " ..probing: %s (%u)", tCurrentProbeAddress.toString().toStdString().c_str(), tIPv4AddrCurrentNumber); if (!MEETING.IsLocalAddress(tCurrentProbeAddress.toString().toStdString(), "5060", SOCKET_UDP)) { MEETING.SendAvailabilityProbe("", tCurrentProbeAddress.toString().toStdString(), "5060", SOCKET_UDP); } }else{ LOG(LOG_INFO, " ..stopping at: %s [%s != %s]", tCurrentProbeAddress.toString().toStdString().c_str(), tCurrentProbeAddressNetwork.toString().toStdString().c_str(), tHostAddressNetwork.toString().toStdString().c_str()); break; } /** * Increase the current IP address */ tIPv4AddrCurrentNumber++; tIPv4AddrCurrentNumberNetwork = (tIPv4AddrCurrentNumber & tIPv4NetNumber); tCurrentProbeAddress.setAddress(tIPv4AddrCurrentNumber); tCurrentProbeAddressNetwork.setAddress(tIPv4AddrCurrentNumberNetwork); tNextProbeAddressNetwork.setAddress(((tIPv4AddrCurrentNumber + 1) & tIPv4NetNumber)); }while((tCurrentProbeAddressNetwork.toString() == tHostAddressNetwork.toString()) && (tNextProbeAddressNetwork.toString() == tHostAddressNetwork.toString())); } } } } } }