protected override void OnReceive(int nErrorCode) { byte[] buffer = new byte[5000]; byte[] pBuffer = buffer; EndPoint endpoint = null; int length = ReceiveFrom(buffer, ref endpoint); if (length != SOCKET_ERROR) { IPEndPoint ipEndPoint = endpoint as IPEndPoint; int nPayLoadLen = length; ED2KServer pServer = MuleApplication.Instance.ServerList.GetServerByIPUDP(BitConverter.ToUInt32(ipEndPoint.Address.GetAddressBytes(), 0), (ushort)IPAddress.NetworkToHostOrder(ipEndPoint.Port), true); if (pServer != null && MuleApplication.Instance.Preference.IsServerCryptLayerUDPEnabled && ((pServer.ServerKeyUDP != 0 && pServer.DoesSupportsObfuscationUDP) || (pServer.CryptPingReplyPending && pServer.Challenge != 0))) { // TODO uint dwKey = 0; if (pServer.CryptPingReplyPending && pServer.Challenge != 0 /* && pServer.GetPort() == ntohs(sockAddr.sin_port) - 12 */) { dwKey = pServer.Challenge; } else { dwKey = pServer.ServerKeyUDP; } Debug.Assert(dwKey != 0); nPayLoadLen = DecryptReceivedServer(buffer, length, out pBuffer, dwKey, BitConverter.ToUInt32(ipEndPoint.Address.GetAddressBytes(), 0)); } if (pBuffer[0] == MuleConstants.PROTOCOL_EDONKEYPROT) { ProcessPacket(pBuffer, 2, nPayLoadLen - 2, pBuffer[1], BitConverter.ToUInt32(ipEndPoint.Address.GetAddressBytes(), 0), (ushort)IPAddress.NetworkToHostOrder(ipEndPoint.Port)); } } else { IPEndPoint ipEndPoint = endpoint as IPEndPoint; if (ipEndPoint != null) { ED2KServer pServer = MuleApplication.Instance.ServerList.GetServerByIPUDP(BitConverter.ToUInt32(ipEndPoint.Address.GetAddressBytes(), 0), (ushort)IPAddress.NetworkToHostOrder(ipEndPoint.Port), true); if (pServer != null && !pServer.CryptPingReplyPending && MpdUtilities.GetTickCount() - pServer.LastPinged >= MuleConstants.ONE_SEC_MS * 30) { pServer.AddFailedCount(); } } } }
public bool SendPacket(Packet packet, uint dwIP, ushort nPort, bool bEncrypt, byte[] pachTargetClientHashORKadID, bool bKad, uint nReceiverVerifyKey) { UDPPack newpending = new UDPPack(); newpending.dwIP = dwIP; newpending.nPort = nPort; newpending.packet = packet; newpending.dwTime = MpdUtilities.GetTickCount(); newpending.bEncrypt = bEncrypt && (pachTargetClientHashORKadID != null || (bKad && nReceiverVerifyKey != 0)); newpending.bKad = bKad; newpending.nReceiverVerifyKey = nReceiverVerifyKey; if (newpending.bEncrypt && pachTargetClientHashORKadID != null) { MpdUtilities.Md4Cpy(newpending.pachTargetClientHashORKadID, pachTargetClientHashORKadID); } else { MpdUtilities.Md4Clr(newpending.pachTargetClientHashORKadID); } lock (sendLocker_) { controlpacketQueue_.Add(newpending); }// sendLocker.Unlock(); MuleApplication.Instance.UploadBandwidthThrottler.QueueForSendingControlPacket(this); return(true); }
public bool IsDeadSource(UpDownClient pToCheck) { if (!pToCheck.HasLowID || pToCheck.ServerIP != 0) { DeadSource ds = new DeadSource(pToCheck.UserIDHybrid, pToCheck.UserPort, pToCheck.ServerIP, pToCheck.KadPort); if (deadSources_.ContainsKey(ds)) { if (deadSources_[ds] > MpdUtilities.GetTickCount()) { return(true); } } } if (((pToCheck.HasValidBuddyID || pToCheck.SupportsDirectUDPCallback) && !MpdUtilities.IsNullMd4(pToCheck.UserHash)) || (pToCheck.HasLowID && pToCheck.ServerIP == 0)) { DeadSource ds = new DeadSource(pToCheck.UserHash); if (deadSources_.ContainsKey(ds)) { if (deadSources_[ds] > MpdUtilities.GetTickCount()) { return(true); } } } return(false); }
public void AddTrackClient(UpDownClient toadd) { DeletedClient pResult = null; if (trackedClientsList_.ContainsKey(toadd.IP)) { pResult = trackedClientsList_[toadd.IP]; pResult.m_dwInserted = MpdUtilities.GetTickCount(); for (int i = 0; i != pResult.m_ItemsList.Count; i++) { if (pResult.m_ItemsList[i].nPort == toadd.UserPort) { // already tracked, update pResult.m_ItemsList[i].pHash = toadd.Credits; return; } } PORTANDHASH porthash = new PORTANDHASH(toadd.UserPort, toadd.Credits); pResult.m_ItemsList.Add(porthash); } else { trackedClientsList_[toadd.IP] = new DeletedClient(toadd); } }
public uint GetSecureWaitStartTime(uint dwForIP) { if (unSecureWaitTime_ == 0 || secureWaitTime_ == 0) { SetSecWaitStartTime(dwForIP); } if (credits_.nKeySize != 0) { // this client is a SecureHash Client if (GetCurrentIdentState(dwForIP) == IdentStateEnum.IS_IDENTIFIED) { // good boy return(secureWaitTime_); } else { // not so good boy if (dwForIP == waitTimeIP_) { return(unSecureWaitTime_); } else { // bad boy unSecureWaitTime_ = MpdUtilities.GetTickCount(); waitTimeIP_ = dwForIP; return(unSecureWaitTime_); } } } else { // not a SecureHash Client - handle it like before for now (no security checks) return(unSecureWaitTime_); } }
public bool CheckTimeOut() { if (socketState_ == SocketStateEnum.SS_Half) { //This socket is still in a half connection state.. Because of SP2, we don't know //if this socket is actually failing, or if this socket is just queued in SP2's new //protection queue. Therefore we give the socket a chance to either finally report //the connection error, or finally make it through SP2's new queued socket system.. if (MpdUtilities.GetTickCount() - timeout_timer_ > base.TimeOut * 4) { timeout_timer_ = MpdUtilities.GetTickCount(); string str = string.Format(("Timeout: State:{0} = SocketStateEnum.SS_Half"), socketState_); Disconnect(str); return(true); } return(false); } uint uTimeout = TimeOut; if (CheckClientTimeOut != null) { uTimeout += CheckClientTimeOut(this, new SocketEventArgs()); } if (MpdUtilities.GetTickCount() - timeout_timer_ > uTimeout) { timeout_timer_ = MpdUtilities.GetTickCount(); string str = string.Format(("Timeout: State:{0} (0 = SocketStateEnum.SS_Other, 1 = SocketStateEnum.SS_Half, 2 = SocketStateEnum.SS_Complete"), socketState_); Disconnect(str); return(true); } return(false); }
public void AddDeadSource(UpDownClient pToAdd) { if (!pToAdd.HasLowID) { DeadSource ds = new DeadSource(pToAdd.UserIDHybrid, pToAdd.UserPort, pToAdd.ServerIP, pToAdd.KadPort); deadSources_[ds] = BLOCKTIME(); } else { if (pToAdd.ServerIP != 0) { DeadSource ds = new DeadSource(pToAdd.UserIDHybrid, pToAdd.UserPort, pToAdd.ServerIP, 0); deadSources_[ds] = BLOCKTIMEFW(); } if (pToAdd.HasValidBuddyID || pToAdd.SupportsDirectUDPCallback) { DeadSource ds = new DeadSource(pToAdd.UserHash); deadSources_[ds] = BLOCKTIMEFW(); } } if (MpdUtilities.GetTickCount() - lastCleanUp_ > CLEANUPTIME) { CleanUp(); } }
public ClientCreditsListImpl() { lastSaved_ = MpdUtilities.GetTickCount(); LoadList(); InitalizeCrypting(); }
public void Process() { if (MpdUtilities.GetTickCount() - lastSaved_ > MuleConstants.ONE_MIN_MS * 13) { SaveList(); } }
public void Process() { if (MpdUtilities.GetTickCount() - lastSaved_ > MuleConstants.ONE_MIN_MS * 17) { MuleApplication.Instance.Preference.Save(); } }
public DeletedClient(UpDownClient pClient) { m_cBadRequest = 0; m_dwInserted = MpdUtilities.GetTickCount(); PORTANDHASH porthash = new PORTANDHASH(pClient.UserPort, pClient.Credits); m_ItemsList.Add(porthash); }
public ED2KServerListImpl() { serverpos_ = 0; searchserverpos_ = 0; statserverpos_ = 0; delservercount_ = 0; lastSaved_ = MpdUtilities.GetTickCount(); }
public ClientCreditsImpl(byte[] key) { credits_ = new CreditStruct(); MpdUtilities.Md4Cpy(credits_.abyKey, key); InitalizeIdent(); unSecureWaitTime_ = MpdUtilities.GetTickCount(); secureWaitTime_ = MpdUtilities.GetTickCount(); waitTimeIP_ = 0; }
public bool IsKadFirewallCheckIP(uint dwIP) { foreach (IPANDTICS v in firewallCheckRequests_) { if (v.dwIP == dwIP && MpdUtilities.GetTickCount() - v.dwInserted < MuleConstants.ONE_SEC_MS * 180) { return(true); } } return(false); }
public bool AllowCalbackRequest(uint dwIP) { foreach (IPANDTICS c in directCallbackRequests_) { if (c.dwIP == dwIP && MpdUtilities.GetTickCount() - c.dwInserted < MuleConstants.ONE_MIN_MS * 3) { return(false); } } return(true); }
public bool IsBannedClient(uint dwIP) { if (bannedList_.ContainsKey(dwIP)) { uint dwBantime = bannedList_[dwIP]; if (dwBantime + MuleConstants.CLIENTBANTIME > MpdUtilities.GetTickCount()) { return(true); } } return(false); }
public virtual void SendPacket(Packet packet, bool delpacket, bool controlpacket, uint actualPayloadSize, bool bForceImmediateSend) { lock (sendLocker_) { do { if (connState_ == ConnectionStateEnum.CS_DISCONNECTED) { break; } else { if (!delpacket) { //Debug.Assert ( !packet.IsSplitted() ); Packet copy = MuleApplication.Instance.NetworkObjectManager.CreatePacket(packet.OperationCode, packet.Size); Array.Copy(packet.Buffer, copy.Buffer, packet.Size); packet = copy; } if (controlpacket) { controlpacket_queue_.Enqueue(packet); // queue up for controlpacket MuleApplication.Instance.UploadBandwidthThrottler.QueueForSendingControlPacket(this, HasSent); } else { bool first = !((sendbuffer_ != null && !currentPacket_is_controlpacket_) || standartpacket_queue_.Count != 0); StandardPacketQueueEntry queueEntry = new StandardPacketQueueEntry(packet, actualPayloadSize); standartpacket_queue_.Enqueue(queueEntry); // reset timeout for the first time if (first) { lastFinishedStandard_ = MpdUtilities.GetTickCount(); accelerateUpload_ = true; // Always accelerate first packet in a block } } } }while (false); } if (bForceImmediateSend) { Debug.Assert(controlpacket_queue_.Count == 1); Send(1024, 0, true); } }
public void AddConnectingClient(UpDownClient pToAdd) { foreach (CONNECTINGCLIENT client in connectingClients_) { if (client.pClient == pToAdd) { return; } } CONNECTINGCLIENT cc = new CONNECTINGCLIENT(pToAdd, MpdUtilities.GetTickCount()); connectingClients_.Add(cc); }
public SocketSentBytes SendControlData(uint maxNumberOfBytesToSend, uint minFragSize) { uint sentBytes = 0; lock (sendLocker_) { while (controlpacketQueue_.Count > 0 && sentBytes < maxNumberOfBytesToSend) { UDPPack cur_packet = controlpacketQueue_[0]; if (MpdUtilities.GetTickCount() - cur_packet.dwTime < MuleConstants.UDPMAXQUEUETIME) { uint nLen = cur_packet.packet.Size + 2; byte[] sendbuffer = new byte[nLen]; Array.Copy(cur_packet.packet.UDPHeader, sendbuffer, 2); Array.Copy(cur_packet.packet.Buffer, 0, sendbuffer, 2, cur_packet.packet.Size); if (cur_packet.bEncrypt && (MuleApplication.Instance.PublicIP > 0 || cur_packet.bKad)) { nLen = (uint)EncryptSendClient(ref sendbuffer, (int)nLen, cur_packet.pachTargetClientHashORKadID, cur_packet.bKad, cur_packet.nReceiverVerifyKey, (cur_packet.bKad ? MuleApplication.Instance.KadEngine.Preference.GetUDPVerifyKey(cur_packet.dwIP) : 0)); } if (UDPSendTo(sendbuffer, (int)nLen, cur_packet.dwIP, cur_packet.nPort) == 0) { sentBytes += nLen; controlpacketQueue_.RemoveAt(0); } } else { controlpacketQueue_.RemoveAt(0); } } if (controlpacketQueue_.Count > 0) { MuleApplication.Instance.UploadBandwidthThrottler.QueueForSendingControlPacket(this); } }//sendLocker.Unlock(); SocketSentBytes returnVal = new SocketSentBytes(true, 0, sentBytes); return(returnVal); }
public void CheckForTimeout() { uint dwServerConnectTimeout = MuleConstants.CONSERVTIMEOUT; // If we are using a proxy, increase server connection timeout to default connection timeout if (MuleApplication.Instance.Preference.ProxySettings.UseProxy) { dwServerConnectTimeout = Math.Max(dwServerConnectTimeout, MuleConstants.CONNECTION_TIMEOUT); } uint dwCurTick = MpdUtilities.GetTickCount(); int pos = 0; while (pos < connectionAttemps_.Count) { List <ulong> keys = connectionAttemps_.Keys.ToList(); ulong key = keys[pos]; ServerSocket sock = connectionAttemps_[key]; if (sock == null) { connectionAttemps_.Remove(key); return; } if (dwCurTick - key > dwServerConnectTimeout) { connectionAttemps_.Remove(key); DestroySocket(sock); if (IsSingleConnect) { StopConnectionTry(); } else { TryAnotherConnectionRequest(); } } else { pos++; } } }
public void ConnectToServer(Mule.ED2K.ED2KServer toconnect, bool multiconnect, bool bNoCrypt) { if (!multiconnect) { StopConnectionTry(); Disconnect(); } IsConnecting = true; IsSingleConnect = !multiconnect; ServerSocket newsocket = MuleApplication.Instance.NetworkObjectManager.CreateServerSocket(this, !multiconnect); openSockets_.Add(newsocket); newsocket.ConnectTo(toconnect, bNoCrypt); connectionAttemps_[MpdUtilities.GetTickCount()] = newsocket; }
public void AddTrackCallbackRequests(uint dwIP) { IPANDTICS add = new IPANDTICS(dwIP, MpdUtilities.GetTickCount()); directCallbackRequests_.Insert(0, add); while (directCallbackRequests_.Count > 0) { if (MpdUtilities.GetTickCount() - directCallbackRequests_.Last().dwInserted > MuleConstants.ONE_MIN_MS * 3) { directCallbackRequests_.Remove(directCallbackRequests_.Last()); } else { break; } } }
public void AddKadFirewallRequest(uint dwIP) { IPANDTICS add = new IPANDTICS(dwIP, MpdUtilities.GetTickCount()); firewallCheckRequests_.Insert(0, add); while (firewallCheckRequests_.Count > 0) { if (MpdUtilities.GetTickCount() - firewallCheckRequests_.Last().dwInserted > MuleConstants.ONE_SEC_MS * 180) { firewallCheckRequests_.Remove(firewallCheckRequests_.Last()); } else { break; } } }
public EMSocketImpl() : base() { DataReceived += OnDataReceived; PacketReceived += OnPacketReceived; connState_ = ConnectionStateEnum.CS_NOTCONNECTED; TimeOut = MuleConstants.CONNECTION_TIMEOUT; // default timeout for ed2k sockets // Download (pseudo) rate control downloadLimit_ = 0; enableDownloadLimit_ = false; pendingOnReceive_ = false; // Download partial header pendingHeaderSize_ = 0; // Download partial packet pendingPacket_ = null; pendingPacketSize_ = 0; // Upload control sendbuffer_ = null; sendblen_ = 0; sent_ = 0; //bLinkedPackets_ = false; currentPacket_is_controlpacket_ = false; currentPackageIsFromPartFile_ = false; numberOfSentBytesCompleteFile_ = 0; numberOfSentBytesPartFile_ = 0; numberOfSentBytesControlPacket_ = 0; lastCalledSend_ = MpdUtilities.GetTickCount(); lastSent_ = MpdUtilities.GetTickCount() - 1000; accelerateUpload_ = false; actualPayloadSize_ = 0; actualPayloadSizeSent_ = 0; hasSent_ = false; useBigSendBuffer_ = false; }
void CleanUp() { lastCleanUp_ = MpdUtilities.GetTickCount(); List <DeadSource> toRemove = new List <DeadSource>(); uint dwTick = MpdUtilities.GetTickCount(); Dictionary <DeadSource, uint> .Enumerator pos = deadSources_.GetEnumerator(); while (pos.MoveNext()) { if (pos.Current.Value < dwTick) { toRemove.Add(pos.Current.Key); } } foreach (DeadSource ds in toRemove) { deadSources_.Remove(ds); } }
public void KeepConnectionAlive() { uint dwServerKeepAliveTimeout = MuleApplication.Instance.Preference.ServerKeepAliveTimeout; if (dwServerKeepAliveTimeout > 0 && IsConnected && connectedSocket_ != null && connectedSocket_.ConnectionState == ConnectionStateEnum.CS_CONNECTED && MpdUtilities.GetTickCount() - connectedSocket_.LastTransmission >= dwServerKeepAliveTimeout) { // "Ping" the server if the TCP connection was not used for the specified interval with // an empty publish files packet . recommended by lugdunummaster himself! SafeMemFile files = MpdObjectManager.CreateSafeMemFile(4); files.WriteUInt32(0); // nr. of files Packet packet = MuleApplication.Instance.NetworkObjectManager.CreatePacket(files); packet.OperationCode = OperationCodeEnum.OP_OFFERFILES; MuleApplication.Instance.Statistics.AddUpDataOverheadServer(packet.Size); connectedSocket_.SendPacket(packet, true); } }
protected void SaveList() { lastSaved_ = MpdUtilities.GetTickCount(); string name = System.IO.Path.Combine(MuleApplication.Instance.Preference.GetMuleDirectory(Mule.Preference.DefaultDirectoryEnum.EMULE_CONFIGDIR), CLIENTS_MET_FILENAME); try { using (FileStream file = new FileStream(name, FileMode.Create, FileAccess.Write, FileShare.None)) { int count = clients_.Count; SafeMemFile memfile = MpdObjectManager.CreateSafeMemFile(count * (16 + 5 * 4 + 1 * 2 + 1 + CreditStruct.MAXPUBKEYSIZE)); memfile.WriteUInt8((byte)VersionsEnum.CREDITFILE_VERSION); Dictionary <MapCKey, ClientCredits> .Enumerator pos = clients_.GetEnumerator(); count = 0; while (pos.MoveNext()) { ClientCredits cur_credit = pos.Current.Value; if (cur_credit.GetUploadedTotal() != 0 || cur_credit.GetDownloadedTotal() != 0) { WriteCreditStruct(memfile, cur_credit.DataStruct); count++; } } memfile.WriteUInt32((uint)count); file.Write(memfile.Buffer, 0, (int)memfile.Length); file.Flush(); file.Close(); memfile.Close(); } } catch (Exception error) { MpdUtilities.DebugLogError(error); } }
public void TrackBadRequest(UpDownClient upcClient, int nIncreaseCounter) { DeletedClient pResult = null; if (upcClient.IP == 0) { Debug.Assert(false); return; } if (trackedClientsList_.ContainsKey(upcClient.IP)) { pResult = trackedClientsList_[upcClient.IP]; pResult.m_dwInserted = MpdUtilities.GetTickCount(); pResult.m_cBadRequest += (uint)nIncreaseCounter; } else { DeletedClient ccToAdd = new DeletedClient(upcClient); ccToAdd.m_cBadRequest = (uint)nIncreaseCounter; trackedClientsList_[upcClient.IP] = ccToAdd; } }
protected void CleanUpClientList() { // we remove clients which are not needed any more by time // this check is also done on CUpDownClient::Disconnected, however it will not catch all // cases (if a client changes the state without beeing connected // // Adding this check directly to every point where any state changes would be more effective, // is however not compatible with the current code, because there are points where a client has // no state for some code lines and the code is also not prepared that a client object gets // invalid while working with it (aka setting a new state) // so this way is just the easy and safe one to go (as long as emule is basically single threaded) uint cur_tick = MpdUtilities.GetTickCount(); if (lastClientCleanUp_ + MuleConstants.CLIENTLIST_CLEANUP_TIME < cur_tick) { lastClientCleanUp_ = cur_tick; int pos = 0; while (pos < clientList_.Count) { UpDownClient pCurClient = clientList_[pos]; if ((pCurClient.UploadState == UploadStateEnum.US_NONE || pCurClient.UploadState == UploadStateEnum.US_BANNED && !pCurClient.IsBanned) && pCurClient.DownloadState == DownloadStateEnum.DS_NONE && pCurClient.ChatState == ChatStateEnum.MS_NONE && pCurClient.KadState == KadStateEnum.KS_NONE && pCurClient.ClientSocket == null) { pCurClient.CleanUp(); } else { pos++; } } } }
protected void ProcessConnectingClientsList() { // we do check if any connects have timed out by now uint cur_tick = MpdUtilities.GetTickCount(); int pos1 = 0; while (pos1 < connectingClients_.Count) { CONNECTINGCLIENT cc = connectingClients_[pos1]; if (cc.dwInserted + MuleConstants.ONE_SEC_MS * 45 < cur_tick) { connectingClients_.RemoveAt(pos1); if (cc.pClient.Disconnected("Connectiontry Timeout")) { cc.pClient.CleanUp(); } } else { pos1++; } } }