private bool ProcessPacket(byte[] buffer, int offset, int size, uint opcode, uint nIP, ushort nUDPPort) { try { MuleApplication.Instance.Statistics.AddDownDataOverheadServer((uint)size); ED2KServer pServer = MuleApplication.Instance.ServerList.GetServerByIPUDP(nIP, nUDPPort, true); if (pServer != null) { pServer.ResetFailedCount(); } switch ((OperationCodeEnum)opcode) { case OperationCodeEnum.OP_GLOBSEARCHRES: { SafeMemFile data = MpdObjectManager.CreateSafeMemFile(buffer, size); // process all search result packets int iLeft; do { uint uResultCount = MuleApplication.Instance.SearchList.ProcessUDPSearchAnswer(data, true /*pServer.GetUnicodeSupport()*/, nIP, nUDPPort - 4); // check if there is another source packet iLeft = (int)(data.Length - data.Position); if (iLeft >= 2) { byte protocol = data.ReadUInt8(); iLeft--; if (protocol != MuleConstants.PROTOCOL_EDONKEYPROT) { data.Seek(-1, System.IO.SeekOrigin.Current); iLeft += 1; break; } byte opcode1 = data.ReadUInt8(); iLeft--; if (opcode1 != (byte)OperationCodeEnum.OP_GLOBSEARCHRES) { data.Seek(-2, System.IO.SeekOrigin.Current); iLeft += 2; break; } } }while (iLeft > 0); break; } case OperationCodeEnum.OP_GLOBFOUNDSOURCES: { SafeMemFile data = MpdObjectManager.CreateSafeMemFile(buffer, size); // process all source packets int iLeft; do { byte[] fileid = new byte[16]; data.ReadHash16(fileid); PartFile file = MuleApplication.Instance.DownloadQueue.GetFileByID(fileid); if (file != null) { file.AddSources(data, nIP, (ushort)(nUDPPort - 4), false); } else { // skip sources for that file uint count = data.ReadUInt8(); data.Seek(count * (4 + 2), System.IO.SeekOrigin.Current); } // check if there is another source packet iLeft = (int)(data.Length - data.Position); if (iLeft >= 2) { byte protocol = data.ReadUInt8(); iLeft--; if (protocol != MuleConstants.PROTOCOL_EDONKEYPROT) { data.Seek(-1, System.IO.SeekOrigin.Current); iLeft += 1; break; } byte opcode1 = data.ReadUInt8(); iLeft--; if (opcode1 != (byte)OperationCodeEnum.OP_GLOBFOUNDSOURCES) { data.Seek(-2, System.IO.SeekOrigin.Current); iLeft += 2; break; } } }while (iLeft > 0); break; } case OperationCodeEnum.OP_GLOBSERVSTATRES: { if (size < 12 || pServer == null) { return(true); } uint challenge = BitConverter.ToUInt32(buffer, 0); if (challenge != pServer.Challenge) { return(true); } if (pServer != null) { pServer.Challenge = 0; pServer.CryptPingReplyPending = false; uint tNow = MpdUtilities.Time(); Random rand = new Random(); // if we used Obfuscated ping, we still need to reset the time properly pServer.LastPingedTime = Convert.ToUInt32(tNow - (rand.Next() % MuleConstants.ONE_HOUR_SEC)); } uint cur_user = BitConverter.ToUInt32(buffer, 4); uint cur_files = BitConverter.ToUInt32(buffer, 8); uint cur_maxusers = 0; uint cur_softfiles = 0; uint cur_hardfiles = 0; uint uUDPFlags = 0; uint uLowIDUsers = 0; uint dwServerUDPKey = 0; ushort nTCPObfuscationPort = 0; ushort nUDPObfuscationPort = 0; if (size >= 16) { cur_maxusers = BitConverter.ToUInt32(buffer, 12); } if (size >= 24) { cur_softfiles = BitConverter.ToUInt32(buffer, 16); cur_hardfiles = BitConverter.ToUInt32(buffer, 20); } if (size >= 28) { uUDPFlags = BitConverter.ToUInt32(buffer, 24); } if (size >= 32) { uLowIDUsers = BitConverter.ToUInt32(buffer, 28); } if (size >= 40) { // TODO debug check if this packet was encrypted if it has a key nUDPObfuscationPort = BitConverter.ToUInt16(buffer, 32); nTCPObfuscationPort = BitConverter.ToUInt16(buffer, 34);; dwServerUDPKey = BitConverter.ToUInt32(buffer, 36); } if (pServer != null) { pServer.Ping = MpdUtilities.GetTickCount() - pServer.LastPinged; pServer.UserCount = cur_user; pServer.FileCount = cur_files; pServer.MaxUsers = cur_maxusers; pServer.SoftFiles = cur_softfiles; pServer.HardFiles = cur_hardfiles; pServer.ServerKeyUDP = dwServerUDPKey; pServer.ObfuscationPortTCP = nTCPObfuscationPort; pServer.ObfuscationPortUDP = nUDPObfuscationPort; // if the received UDP flags do not match any already stored UDP flags, // reset the server version string because the version (which was determined by last connecting to // that server) is most likely not accurat any longer. // this may also give 'false' results because we don't know the UDP flags when connecting to a server // with TCP. //if (pServer.GetUDPFlags() != uUDPFlags) // pServer.Version(_T = ""); pServer.UDPFlags = (ED2KServerUdpFlagsEnum)uUDPFlags; pServer.LowIDUsers = uLowIDUsers; pServer.SetLastDescPingedCount(false); if (pServer.LastDescPingedCount < 2) { // eserver 16.45+ supports a new OP_SERVER_DESC_RES answer, if the OP_SERVER_DESC_REQ contains a uint // challenge, the server returns additional info with OP_SERVER_DESC_RES. To properly distinguish the // old and new OP_SERVER_DESC_RES answer, the challenge has to be selected carefully. The first 2 bytes // of the challenge (in network byte order) MUST NOT be a valid string-len-int16! Packet packet1 = MuleApplication.Instance.NetworkObjectManager.CreatePacket(OperationCodeEnum.OP_SERVER_DESC_REQ, 4); uint uDescReqChallenge = ((uint)MpdUtilities.GetRandomUInt16() << 16) + MuleConstants.INV_SERV_DESC_LEN; // 0xF0FF = an 'invalid' string length. pServer.DescReqChallenge = uDescReqChallenge; Array.Copy(BitConverter.GetBytes(uDescReqChallenge), packet1.Buffer, 4); MuleApplication.Instance.Statistics.AddUpDataOverheadServer(packet1.Size); MuleApplication.Instance.ServerConnect.SendUDPPacket(packet1, pServer, true); } else { pServer.SetLastDescPingedCount(true); } } break; } case OperationCodeEnum.OP_SERVER_DESC_RES: { if (pServer == null) { return(true); } // old packet: <name_len 2><name name_len><desc_len 2 desc_en> // new packet: <challenge 4><taglist> // // NOTE: To properly distinguish between the two packets which are both useing the same opcode... // the first two bytes of <challenge> (in network byte order) have to be an invalid <name_len> at least. SafeMemFile srvinfo = MpdObjectManager.CreateSafeMemFile(buffer, size); if (size >= 8 && BitConverter.ToUInt16(buffer, 0) == MuleConstants.INV_SERV_DESC_LEN) { if (pServer.DescReqChallenge != 0 && BitConverter.ToUInt32(buffer, 0) == pServer.DescReqChallenge) { pServer.DescReqChallenge = 0; srvinfo.ReadUInt32(); // skip challenge uint uTags = srvinfo.ReadUInt32(); for (uint i = 0; i < uTags; i++) { Tag tag = MpdObjectManager.CreateTag(srvinfo, true /*pServer.GetUnicodeSupport()*/); if (tag.NameID == MuleConstants.ST_SERVERNAME && tag.IsStr) { pServer.ServerName = tag.Str; } else if (tag.NameID == MuleConstants.ST_DESCRIPTION && tag.IsStr) { pServer.Description = tag.Str; } else if (tag.NameID == MuleConstants.ST_DYNIP && tag.IsStr) { // Verify that we really received a DN. IPAddress address; if (!IPAddress.TryParse(tag.Str, out address) || address == IPAddress.None) { string strOldDynIP = pServer.DynIP; pServer.DynIP = tag.Str; // If a dynIP-server changed its address or, if this is the // first time we get the dynIP-address for a server which we // already have as non-dynIP in our list, we need to remove // an already available server with the same 'dynIP:port'. if (string.Compare(strOldDynIP, pServer.DynIP, true) != 0) { MuleApplication.Instance.ServerList.RemoveDuplicatesByAddress(pServer); } } } else if (tag.NameID == MuleConstants.ST_VERSION && tag.IsStr) { pServer.Version = tag.Str; } else if (tag.NameID == MuleConstants.ST_VERSION && tag.IsInt) { pServer.Version = string.Format("{0}.{1}", tag.Int >> 16, tag.Int & 0xFFFF); } } } else { // A server sent us a new server description packet (including a challenge) although we did not // ask for it. This may happen, if there are multiple servers running on the same machine with // multiple IPs. If such a server is asked for a description, the server will answer 2 times, // but with the same IP. } } else { string strName = srvinfo.ReadString(true /*pServer.GetUnicodeSupport()*/); string strDesc = srvinfo.ReadString(true /*pServer.GetUnicodeSupport()*/); pServer.Description = strDesc; pServer.ServerName = strName; } break; } default: return(false); } return(true); } catch (Exception error) { ProcessPacketError((uint)size, (uint)opcode, nIP, nUDPPort, error); if (opcode == (byte)OperationCodeEnum.OP_GLOBSEARCHRES || opcode == (byte)OperationCodeEnum.OP_GLOBFOUNDSOURCES) { return(true); } } return(false); }
private bool ProcessPacket(byte[] packet, uint offset, uint size, byte opcode, uint ip, ushort port) { switch ((OperationCodeEnum)opcode) { case OperationCodeEnum.OP_REASKCALLBACKUDP: { MuleApplication.Instance.Statistics.AddDownDataOverheadOther(size); UpDownClient buddy = MuleApplication.Instance.ClientList.Buddy; if (buddy != null) { if (size < 17 || buddy.ClientSocket == null) { break; } if (MpdUtilities.Md4Cmp(packet, (int)offset, buddy.BuddyID, 0) == 0) { Array.Copy(BitConverter.GetBytes(ip), 0, packet, offset + 10, 4); Array.Copy(BitConverter.GetBytes(port), 0, packet, offset + 14, 2); Packet response = MuleApplication.Instance.NetworkObjectManager.CreatePacket(MuleConstants.PROTOCOL_EMULEPROT); response.OperationCode = OperationCodeEnum.OP_REASKCALLBACKTCP; response.Buffer = new byte[size]; Array.Copy(packet, offset + 10, response.Buffer, 0, size - 10); response.Size = size - 10; MuleApplication.Instance.Statistics.AddUpDataOverheadFileRequest(response.Size); buddy.SendPacket(response, true); } } break; } case OperationCodeEnum.OP_REASKFILEPING: { MuleApplication.Instance.Statistics.AddDownDataOverheadFileRequest(size); SafeMemFile data_in = MpdObjectManager.CreateSafeMemFile(packet, offset, size); byte[] reqfilehash = new byte[16]; data_in.ReadHash16(reqfilehash); KnownFile reqfile = MuleApplication.Instance.SharedFiles.GetFileByID(reqfilehash); bool bSenderMultipleIpUnknown = false; UpDownClient sender = MuleApplication.Instance.UploadQueue.GetWaitingClientByIP_UDP(ip, port, true, ref bSenderMultipleIpUnknown); if (reqfile == null) { Packet response = MuleApplication.Instance.NetworkObjectManager.CreatePacket(OperationCodeEnum.OP_FILENOTFOUND, 0, MuleConstants.PROTOCOL_EMULEPROT); MuleApplication.Instance.Statistics.AddUpDataOverheadFileRequest(response.Size); if (sender != null) { SendPacket(response, ip, port, sender.ShouldReceiveCryptUDPPackets, sender.UserHash, false, 0); } else { SendPacket(response, ip, port, false, null, false, 0); } break; } if (sender != null) { //Make sure we are still thinking about the same file if (MpdUtilities.Md4Cmp(reqfilehash, sender.UploadFileID) == 0) { sender.AddAskedCount(); sender.SetLastUpRequest(); //I messed up when I first added extended info to UDP //I should have originally used the entire ProcessExtenedInfo the first time. //So now I am forced to check UDPVersion to see if we are sending all the extended info. //For now on, we should not have to change anything here if we change //anything to the extended info data as this will be taken care of in ProcessExtendedInfo() //Update extended info. if (sender.UDPVersion > 3) { sender.ProcessExtendedInfo(data_in, reqfile); } //Update our complete source counts. else if (sender.UDPVersion > 2) { ushort nCompleteCountLast = sender.UpCompleteSourcesCount; ushort nCompleteCountNew = data_in.ReadUInt16(); sender.UpCompleteSourcesCount = nCompleteCountNew; if (nCompleteCountLast != nCompleteCountNew) { reqfile.UpdatePartsInfo(); } } SafeMemFile data_out = MpdObjectManager.CreateSafeMemFile(128); if (sender.UDPVersion > 3) { if (reqfile.IsPartFile) { ((PartFile)reqfile).WritePartStatus(data_out); } else { data_out.WriteUInt16(0); } } data_out.WriteUInt16((ushort)(MuleApplication.Instance.UploadQueue.GetWaitingPosition(sender))); Packet response = MuleApplication.Instance.NetworkObjectManager.CreatePacket(data_out, MuleConstants.PROTOCOL_EMULEPROT); response.OperationCode = OperationCodeEnum.OP_REASKACK; MuleApplication.Instance.Statistics.AddUpDataOverheadFileRequest(response.Size); SendPacket(response, ip, port, sender.ShouldReceiveCryptUDPPackets, sender.UserHash, false, 0); } } else { // Don't answer him. We probably have him on our queue already, but can't locate him. Force him to establish a TCP connection if (!bSenderMultipleIpUnknown) { if (((uint)MuleApplication.Instance.UploadQueue.WaitingUserCount + 50) > MuleApplication.Instance.Preference.QueueSize) { Packet response = MuleApplication.Instance.NetworkObjectManager.CreatePacket(OperationCodeEnum.OP_QUEUEFULL, 0, MuleConstants.PROTOCOL_EMULEPROT); MuleApplication.Instance.Statistics.AddUpDataOverheadFileRequest(response.Size); SendPacket(response, ip, port, false, null, false, 0); // we cannot answer this one encrypted since we dont know this client } } } break; } case OperationCodeEnum.OP_QUEUEFULL: { MuleApplication.Instance.Statistics.AddDownDataOverheadFileRequest(size); UpDownClient sender = MuleApplication.Instance.DownloadQueue.GetDownloadClientByIP_UDP(ip, port, true); if (sender != null && sender.UDPPacketPending) { sender.IsRemoteQueueFull = true; sender.UDPReaskACK(0); } break; } case OperationCodeEnum.OP_REASKACK: { MuleApplication.Instance.Statistics.AddDownDataOverheadFileRequest(size); UpDownClient sender = MuleApplication.Instance.DownloadQueue.GetDownloadClientByIP_UDP(ip, port, true); if (sender != null && sender.UDPPacketPending) { SafeMemFile data_in = MpdObjectManager.CreateSafeMemFile(packet, size); if (sender.UDPVersion > 3) { sender.ProcessFileStatus(true, data_in, sender.RequestFile); } ushort nRank = data_in.ReadUInt16(); sender.IsRemoteQueueFull = false; sender.UDPReaskACK(nRank); sender.AddAskedCountDown(); } break; } case OperationCodeEnum.OP_FILENOTFOUND: { MuleApplication.Instance.Statistics.AddDownDataOverheadFileRequest(size); UpDownClient sender = MuleApplication.Instance.DownloadQueue.GetDownloadClientByIP_UDP(ip, port, true); if (sender != null && sender.UDPPacketPending) { sender.UDPReaskFNF(); // may delete 'sender'! sender = null; } break; } case OperationCodeEnum.OP_PORTTEST: { MuleApplication.Instance.Statistics.AddDownDataOverheadOther(size); if (size == 1) { if (packet[0] == 0x12) { bool ret = MuleApplication.Instance.ListenSocket.SendPortTestReply('1', true); } } break; } case OperationCodeEnum.OP_DIRECTCALLBACKREQ: { if (!MuleApplication.Instance.ClientList.AllowCalbackRequest(ip)) { break; } // do we accept callbackrequests at all? if (MuleApplication.Instance.KadEngine.IsRunning && MuleApplication.Instance.KadEngine.IsFirewalled) { MuleApplication.Instance.ClientList.AddTrackCallbackRequests(ip); SafeMemFile data = MpdObjectManager.CreateSafeMemFile(packet, size); ushort nRemoteTCPPort = data.ReadUInt16(); byte[] uchUserHash = new byte[16]; data.ReadHash16(uchUserHash); byte byConnectOptions = data.ReadUInt8(); UpDownClient pRequester = MuleApplication.Instance.ClientList.FindClientByUserHash(uchUserHash, ip, nRemoteTCPPort); if (pRequester == null) { pRequester = MuleApplication.Instance.CoreObjectManager.CreateUpDownClient(null, nRemoteTCPPort, ip, 0, 0, true); pRequester.UserHash = uchUserHash; MuleApplication.Instance.ClientList.AddClient(pRequester); } pRequester.SetConnectOptions(byConnectOptions, true, false); pRequester.DoesDirectUDPCallbackSupport = false; pRequester.IP = ip; pRequester.UserPort = nRemoteTCPPort; pRequester.TryToConnect(); } break; } default: MuleApplication.Instance.Statistics.AddDownDataOverheadOther(size); return(false); } return(true); }