// BRIDGE Connection checks void WebServer::checkBridges(){ //qDebug() << "Check Bridges:" << WS_MODE << QDateTime::currentDateTime().toString(Qt::ISODate); if(!WS_MODE){ return; } //Get all the unique bridge URL's we need connections to QStringList bridgeKeys = CONFIG->allKeys().filter("bridge_connections/"); for(int i=0; i<bridgeKeys.length(); i++){ bridgeKeys[i] = CONFIG->value(bridgeKeys[i]).toString(); //turn the key into the URL for the bridge (unique ID) } //Now browse through all the current connections and see if any are already active for(int i=0; i<OpenSockets.length(); i++){ bool active = OpenSockets[i]->isActive(); if( bridgeKeys.contains( OpenSockets[i]->ID() ) && active){ bridgeKeys.removeAll( OpenSockets[i]->ID() ); //already running - remove from the temporary list }else if( OpenSockets[i]->ID().toInt()==0 || !active){ //non-integer ID - another bridge connection which must have been removed from the server settings OpenSockets[i]->closeConnection(); } } //Now startup any connections which are missing for(int i=0; i<bridgeKeys.length(); i++){ //qDebug() << "Try to connect to bridge:" << bridgeKeys[i]; WebSocket *sock = new WebSocket(this, bridgeKeys[i], bridgeKeys[i], AUTH); connect(sock, SIGNAL(SocketClosed(QString)), this, SLOT(SocketClosed(QString)) ); OpenSockets << sock; } }
void SocketTCP::write(const char* text, int size){ const char *ptr = text; int left = size; if(!_connected) throw std::string("Socket is not connected"); while(left > 0){ timeout(TIMEOUT); int written = ::write(_fd, ptr, left); if(written > 0){ left -= written; ptr += written; continue; }else if(written == 0){ debug("Didn't write the text. Will try again"); } else if(written == -1){ if(errno == 104) throw SocketClosed(); if(errno == EPIPE) throw std::string("DISCONNETED"); throw std::string("SocketTCP::write ").append(strerror(errno)); } } }
//======================= // PRIVATE SLOTS //======================= //GENERIC SERVER SIGNALS // New Connection Signals void WebServer::NewSocketConnection(){ WebSocket *sock = 0; if(WSServer!=0){ if(WSServer->hasPendingConnections()){ QWebSocket *ws = WSServer->nextPendingConnection(); if( !allowConnection(ws->peerAddress()) ){ ws->close(); } else{ sock = new WebSocket( ws, generateID(), AUTH); } } }else if(TCPServer!=0){ if(TCPServer->hasPendingConnections()){ QSslSocket *ss = TCPServer->nextPendingConnection(); if( !allowConnection(ss->peerAddress()) ){ ss->close(); } else{ sock = new WebSocket( ss, generateID(), AUTH); } } } if(sock==0){ return; } //no new connection //qDebug() << "New Socket Connection"; connect(sock, SIGNAL(SocketClosed(QString)), this, SLOT(SocketClosed(QString)) ); connect(EVENTS, SIGNAL(NewEvent(EventWatcher::EVENT_TYPE, QJsonValue)), sock, SLOT(EventUpdate(EventWatcher::EVENT_TYPE, QJsonValue)) ); OpenSockets << sock; }
void WebSocket::SocketClosing(){ qDebug() << "Socket Closing..."; if(idletimer->isActive()){ //This means the client deliberately closed the connection - not the idle timer idletimer->stop(); } //Stop any current requests //Reset the pointer SOCKET = 0; emit SocketClosed(SockID); }
void WebSocket::SocketClosing(){ LogManager::log(LogManager::HOST,"Connection Closing: "+SockPeerIP); if(idletimer->isActive()){ //This means the client deliberately closed the connection - not the idle timer //qDebug() << " - Client Closed Connection"; idletimer->stop(); }else{ //qDebug() << "idleTimer not running"; } //Stop any current requests //Reset the pointer if(SOCKET!=0){ SOCKET = 0; } if(TSOCKET!=0){ TSOCKET = 0; } emit SocketClosed(SockID); }
void SocketTCP::write(char* text, int size){ char *ptr = text; int left = size; if(!_connected) throw std::string("SocketTCP::write: Socket is not connected"); while(left > 0){ timeout(TIMEOUT); int written = ::write(_fd, ptr, left); if(written < 0){ debug("ERROR: " + std::to_string(errno) + "\n" + strerror(errno)); if(errno == 11) throw SocketClosed(); if(errno == EPIPE) throw std::string("DISCONNETED"); throw std::string("SocketTCP::write ").append(strerror(errno)); } left -= written; ptr += written; } }
void CMuleKad::Process(UINT Tick) { if(m_MyBuddy && IsFirewalled() && m_NextBuddyPing < GetCurTick()) { m_NextBuddyPing = GetCurTick() + MIN2MS(10); m_MyBuddy->SendBuddyPing(); } QVariantMap Request; Request["Firewalled"] = theCore->m_MuleManager->IsFirewalled(CAddress::IPv4, false, true); Request["PublicIP"] = theCore->m_MuleManager->GetAddress(CAddress::IPv4, true).ToQString(); if(theCore->m_MuleManager->IsFirewalled(CAddress::IPv4)) { if(m_MyBuddy) { Request["BuddyIP"] = m_MyBuddy->GetMule().IPv4.ToQString(); Request["BuddyPort"] = m_MyBuddy->GetKadPort(); } } // Note: we always advertize IPv6 addresses CAddress IPv6 = theCore->m_MuleManager->GetAddress(CAddress::IPv6, true); if(!IPv6.IsNull()) Request["IPv6"] = IPv6.ToQString(); if(Tick & EPerSec) { if(theCore->Cfg()->GetBool("Log/Merge")) SyncLog(); } QVariantMap Response = theCore->m_Interfaces->RemoteProcedureCall("MuleKad", "SyncState", Request).toMap(); m_KadID = Response["KadID"].toByteArray(); if(Response["Result"] == "Connected") { if(m_KadStatus != eConnected) { LogLine(LOG_SUCCESS, tr("MuleKad Connected, ID: %1").arg(QString(m_KadID.toHex()).toUpper())); m_KadStatus = eConnected; } } else if(Response["Result"] == "Connecting") m_KadStatus = eConnecting; else //if(Response["Result"] == "Disconnected") m_KadStatus = eDisconnected; if(m_KadStatus == eDisconnected) { if(GetCurTick() > m_NextConnectionAttempt) { LogLine(LOG_INFO, tr("Connecting emule kademlia")); m_NextConnectionAttempt = GetCurTick() + SEC2MS(theCore->Cfg()->GetInt("Ed2kMule/IdleTimeout")); StartKad(); } return; } m_Address = CAddress(Response["PublicIP"].toString()); m_KadPort = Response["KadPort"].toUInt(); // external kad port //m_UDPPort = Response["UDPPort"].toUInt(); // socket port m_Firewalled = Response["Firewalled"].toBool(); m_KadFirewalled = Response["KadFirewalled"].toBool(); if (m_KadFirewalled && m_uNextKadFirewallRecheck <= GetCurTick()) { m_uNextKadFirewallRecheck = GetCurTick() + SEC2MS(theCore->Cfg()->GetInt("Ed2kMule/CheckFWInterval")); CheckFWState(); } foreach(const QVariant& vQueuedFWCheck, Response["QueuedFWChecks"].toList()) { QVariantMap QueuedFWCheck = vQueuedFWCheck.toMap(); SMuleSource Mule; Mule.SetIP(CAddress(QueuedFWCheck["Address"].toString())); Mule.TCPPort = QueuedFWCheck["TCPPort"].toUInt(); Mule.ConOpts.Bits = QueuedFWCheck["ConOpts"].toUInt(); if(Mule.ConOpts.Fields.RequestsCryptLayer) // some cleints seam to mess this up Mule.ConOpts.Fields.SupportsCryptLayer = true; QByteArray UserHash = QueuedFWCheck["UserHash"].toByteArray(); if(!Mule.SelectIP() || !theCore->m_PeerWatch->CheckPeer(Mule.GetIP(), Mule.TCPPort)) continue; bool bAdded = false; CMuleClient* pClient = theCore->m_MuleManager->GetClient(Mule, &bAdded); if(!bAdded) { if(QueuedFWCheck["TestUDP"].toBool() == true) SetUDPFWCheckResult(pClient, true); continue; } if(QueuedFWCheck["TestUDP"].toBool() == true) { uint32 UDPKey; if(QueuedFWCheck.contains("UDPKey")) UDPKey = QueuedFWCheck["UDPKey"].toUInt(); else UDPKey = theCore->m_MuleManager->GetServer()->GetUDPKey(Mule.GetIP()); m_QueuedFWChecks.insert(pClient, SFWCheck(QueuedFWCheck["IntPort"].toUInt(), QueuedFWCheck["ExtPort"].toUInt(), UDPKey)); } else m_QueuedFWChecks.insert(pClient, SFWCheck()); connect(pClient, SIGNAL(HelloRecived()), this, SLOT(OnHelloRecived())); connect(pClient, SIGNAL(SocketClosed()), this, SLOT(OnSocketClosed())); pClient->SetUserHash(UserHash); pClient->Connect(); } QList<CAddress> PendingFWChecks; foreach(const QVariant& vPendingFWCheck, Response["PendingFWChecks"].toList()) { QVariantMap PendingFWCheck = vPendingFWCheck.toMap(); PendingFWChecks.append(CAddress(PendingFWCheck["Address"].toString())); } theCore->m_MuleManager->GetServer()->SetExpected(PendingFWChecks); foreach(const QVariant& vBufferedCallback, Response["BufferedCallbacks"].toList()) { QVariantMap BufferedCallback = vBufferedCallback.toMap(); CAddress Address = CAddress(BufferedCallback["Address"].toString()); uint16 uPort = BufferedCallback["TCPPort"].toUInt(); QByteArray BuddyID = BufferedCallback["BuddyID"].toByteArray(); QByteArray FileID = BufferedCallback["FileID"].toByteArray(); if(m_MyBuddy && m_MyBuddy->IsFirewalled(CAddress::IPv4)) { if(m_MyBuddy->GetBuddyID() == BuddyID) m_MyBuddy->RelayKadCallback(Address, uPort, BuddyID, FileID); } } // Note: This comes in on the normal UDP Socket, as we provide thesocket now we dont haveto pull it /*foreach(const QVariant& vBufferedPackets, Response["BufferedPackets"].toList()) { QVariantMap BufferedPackets = vBufferedPackets.toMap(); CAddress Address = CAddress(BufferedPackets["Address"].toString()); uint16 uPort = BufferedPackets["UDPPort"].toUInt(); QByteArray Data = BufferedPackets["Data"].toByteArray(); CBuffer Packet((byte*)Data.data(), Data.size(), true); RelayUDPPacket(Address, uPort, Packet); } foreach(const QVariant& vPendingCallback, Response["PendingCallbacks"].toList()) { QVariantMap PendingCallback = vPendingCallback.toMap(); SMuleSource Mule; Mule.SetIP(CAddress(PendingCallback["Address"].toString())); Mule.TCPPort = PendingCallback["TCPPort"].toUInt(); Mule.UserHash = PendingCallback["UserHash"].toByteArray(); Mule.ConOpts.Bits = PendingCallback["ConOpts"].toUInt(); if(Mule.ConOpts.Fields.RequestsCryptLayer) // some cleints seam to mess this up Mule.ConOpts.Fields.SupportsCryptLayer = true; theCore->m_MuleManager->CallbackRequested(Mule); }*/ foreach(const QVariant& vPendingBuddys, Response["PendingBuddys"].toList()) { if(m_MyBuddy) // if we have a buddy we are not interested in new ones break; QVariantMap PendingBuddy = vPendingBuddys.toMap(); SMuleSource Mule; Mule.SetIP(CAddress(PendingBuddy["Address"].toString())); Mule.TCPPort = PendingBuddy["TCPPort"].toUInt(); Mule.KadPort = PendingBuddy["KadPort"].toUInt(); Mule.ConOpts.Bits = PendingBuddy["ConOpts"].toUInt(); if(Mule.ConOpts.Fields.RequestsCryptLayer) // some cleints seam to mess this up Mule.ConOpts.Fields.SupportsCryptLayer = true; Mule.UserHash = PendingBuddy["UserHash"].toByteArray(); Mule.BuddyID = PendingBuddy["BuddyID"].toByteArray(); if(!theCore->m_PeerWatch->CheckPeer(Mule.GetIP(), Mule.TCPPort)) continue; bool bAdded = false; CMuleClient* pClient = theCore->m_MuleManager->GetClient(Mule, &bAdded); if(!bAdded) continue; // already known clients are not viable budies connect(pClient, SIGNAL(HelloRecived()), this, SLOT(OnHelloRecived())); connect(pClient, SIGNAL(SocketClosed()), this, SLOT(OnSocketClosed())); if(m_PendingBuddys.contains(pClient)) continue; // already listes m_PendingBuddys.append(pClient); if(PendingBuddy["Incoming"].toBool()) // is this a lowID client that wants us to become his buddy ans will soon connect us? pClient->ExpectConnection(); else //this is a high ID client that agreed to become our buddy pClient->Connect(); } m_KadStats = Response["Stats"].toMap(); if(Tick & EPerSec) { if(IsConnected()) { SyncFiles(); SyncNotes(); foreach(CAbstractSearch* pSearch, m_RunningSearches) SyncSearch(pSearch); } } }