Exemplo n.º 1
0
        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);
            }
        }
Exemplo n.º 2
0
        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);
            }
        }
Exemplo n.º 3
0
        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);
        }
Exemplo n.º 4
0
        private int SendNegotiatingData(byte[] lpBuf, uint nBufLen, uint nStartCryptFromByte, bool bDelaySend)
        {
            Debug.Assert(streamCryptState_ == StreamCryptStateEnum.ECS_NEGOTIATING ||
                         streamCryptState_ == StreamCryptStateEnum.ECS_ENCRYPTING);
            Debug.Assert(nStartCryptFromByte <= nBufLen);
            Debug.Assert(negotiatingState_ == NegotiatingStateEnum.ONS_BASIC_SERVER_DELAYEDSENDING ||
                         !bDelaySend);

            byte[] pBuffer  = null;
            bool   bProcess = false;

            if (lpBuf != null)
            {
                pBuffer = new byte[nBufLen];
                if (nStartCryptFromByte > 0)
                {
                    Array.Copy(lpBuf, pBuffer, nStartCryptFromByte);
                }
                if (nBufLen - nStartCryptFromByte > 0)
                {
                    MuleUtilities.RC4Crypt(lpBuf, Convert.ToInt32(nStartCryptFromByte),
                                           pBuffer, Convert.ToInt32(nStartCryptFromByte),
                                           nBufLen - nStartCryptFromByte,
                                           rc4SendKey_);
                }
                if (fiSendBuffer_ != null)
                {
                    // we already have data pending. Attach it and try to send
                    if (negotiatingState_ == NegotiatingStateEnum.ONS_BASIC_SERVER_DELAYEDSENDING)
                    {
                        negotiatingState_ = NegotiatingStateEnum.ONS_COMPLETE;
                    }
                    else
                    {
                        Debug.Assert(false);
                    }
                    fiSendBuffer_.Seek(0, System.IO.SeekOrigin.End);
                    fiSendBuffer_.Write(pBuffer, 0, Convert.ToInt32(nBufLen));
                    pBuffer             = null;
                    nStartCryptFromByte = 0;
                    bProcess            = true; // we want to try to send it right now
                }
            }
            if (lpBuf == null || bProcess)
            {
                // this call is for processing pending data
                if (fiSendBuffer_ == null || nStartCryptFromByte != 0)
                {
                    Debug.Assert(false);
                    return(0);                                                   // or not
                }
                nBufLen       = Convert.ToUInt32(fiSendBuffer_.Length);
                pBuffer       = fiSendBuffer_.Buffer;
                fiSendBuffer_ = null;
            }
            Debug.Assert(fiSendBuffer_ == null);
            int result = 0;

            if (!bDelaySend)
            {
                result = base.Send(pBuffer, Convert.ToInt32(nBufLen));
            }
            if (result == SOCKET_ERROR || bDelaySend)
            {
                fiSendBuffer_ = MpdObjectManager.CreateSafeMemFile(128);
                fiSendBuffer_.Write(pBuffer, 0, Convert.ToInt32(nBufLen));
                return(result);
            }
            else
            {
                if (result < nBufLen)
                {
                    fiSendBuffer_ = MpdObjectManager.CreateSafeMemFile(128);
                    fiSendBuffer_.Write(pBuffer, Convert.ToInt32(result), Convert.ToInt32(nBufLen - result));
                }
                return(result);
            }
        }
Exemplo n.º 5
0
        public void ConnectionEstablished(Mule.Network.ServerSocket sender)
        {
            if (!IsConnecting)
            {
                // we are already IsConnected to another server
                DestroySocket(sender);
                return;
            }

            InitLocalIP();
            if (sender.ConnectionState == ConnectionStateEnum.CS_WAITFORLOGIN)
            {
                ED2KServer pServer =
                    MuleApplication.Instance.ServerList.GetServerByAddress(sender.CurrentServer.Address,
                                                                           sender.CurrentServer.Port);
                if (pServer != null)
                {
                    pServer.ResetFailedCount();
                }

                // Send login packet
                SafeMemFile data = MpdObjectManager.CreateSafeMemFile(256);
                data.WriteHash16(MuleApplication.Instance.Preference.UserHash);
                data.WriteUInt32(ClientID);
                data.WriteUInt16(MuleApplication.Instance.Preference.Port);

                uint tagcount = 4;
                data.WriteUInt32(tagcount);

                Tag tagName = MpdObjectManager.CreateTag(TagTypeEnum.CT_NAME,
                                                         MuleApplication.Instance.Preference.UserNick);
                tagName.WriteTagToFile(data);

                Tag tagVersion = MpdObjectManager.CreateTag(TagTypeEnum.CT_VERSION, VersionsEnum.EDONKEYVERSION);
                tagVersion.WriteTagToFile(data);

                ServerFlagsEnum dwCryptFlags = 0;
                if (MuleApplication.Instance.Preference.IsClientCryptLayerSupported)
                {
                    dwCryptFlags |= ServerFlagsEnum.SRVCAP_SUPPORTCRYPT;
                }
                if (MuleApplication.Instance.Preference.IsClientCryptLayerRequested)
                {
                    dwCryptFlags |= ServerFlagsEnum.SRVCAP_REQUESTCRYPT;
                }
                if (MuleApplication.Instance.Preference.IsClientCryptLayerRequired)
                {
                    dwCryptFlags |= ServerFlagsEnum.SRVCAP_REQUIRECRYPT;
                }

                Tag tagFlags = MpdObjectManager.CreateTag(TagTypeEnum.CT_SERVER_FLAGS,
                                                          ServerFlagsEnum.SRVCAP_ZLIB | ServerFlagsEnum.SRVCAP_NEWTAGS |
                                                          ServerFlagsEnum.SRVCAP_LARGEFILES |
                                                          ServerFlagsEnum.SRVCAP_UNICODE | dwCryptFlags);

                tagFlags.WriteTagToFile(data);

                // eMule Version (14-Mar-2004: requested by lugdunummaster (need for LowID clients which have no chance
                // to send an Hello packet to the server during the callback test))
                Tag tagMuleVersion = MpdObjectManager.CreateTag(TagTypeEnum.CT_EMULE_VERSION,
                                                                (MuleApplication.Instance.Version.Major << 17) |
                                                                (MuleApplication.Instance.Version.Minor << 10) |
                                                                (MuleApplication.Instance.Version.Build << 7));
                tagMuleVersion.WriteTagToFile(data);

                Packet packet = MuleApplication.Instance.NetworkObjectManager.CreatePacket(data);
                packet.OperationCode = OperationCodeEnum.OP_LOGINREQUEST;
                MuleApplication.Instance.Statistics.AddUpDataOverheadServer(packet.Size);
                SendPacket(packet, true, sender);
            }
            else if (sender.ConnectionState == ConnectionStateEnum.CS_CONNECTED)
            {
                MuleApplication.Instance.Statistics.Reconnects++;
                MuleApplication.Instance.Statistics.ServerConnectTime = MpdUtilities.GetTickCount();
                IsConnected      = true;
                connectedSocket_ = sender;
                StopConnectionTry();
                MuleApplication.Instance.SharedFiles.ClearED2KPublishInfo();
                MuleApplication.Instance.SharedFiles.SendListToServer();

                if (MuleApplication.Instance.Preference.DoesAddServersFromServer)
                {
                    Packet packet =
                        MuleApplication.Instance.NetworkObjectManager.CreatePacket(
                            OperationCodeEnum.OP_GETSERVERLIST, 0);
                    MuleApplication.Instance.Statistics.AddUpDataOverheadServer(packet.Size);
                    SendPacket(packet, true);
                }
            }
        }
Exemplo n.º 6
0
        private void StartNegotiation(bool bOutgoing)
        {
            if (!bOutgoing)
            {
                negotiatingState_   = NegotiatingStateEnum.ONS_BASIC_CLIENTA_RANDOMPART;
                streamCryptState_   = StreamCryptStateEnum.ECS_NEGOTIATING;
                receiveBytesWanted_ = 4;
            }
            else if (streamCryptState_ == StreamCryptStateEnum.ECS_PENDING)
            {
                SafeMemFile fileRequest = MpdObjectManager.CreateSafeMemFile(29);
                byte        bySemiRandomNotProtocolMarker = GetSemiRandomNotProtocolMarker();
                fileRequest.WriteUInt8(bySemiRandomNotProtocolMarker);
                fileRequest.WriteUInt32(randomKeyPart_);
                fileRequest.WriteUInt32(MuleConstants.MAGICVALUE_SYNC);
                byte bySupportedEncryptionMethod = Convert.ToByte(EncryptionMethodsEnum.ENM_OBFUSCATION); // we do not support any further encryption in this version
                fileRequest.WriteUInt8(bySupportedEncryptionMethod);
                fileRequest.WriteUInt8(bySupportedEncryptionMethod);                                      // so we also prefer this one
                byte byPadding = Convert.ToByte(MpdUtilities.GetRandomUInt8() %
                                                (MuleApplication.Instance.Preference.CryptTCPPaddingLength + 1));
                fileRequest.WriteUInt8(byPadding);
                for (int i = 0; i < byPadding; i++)
                {
                    fileRequest.WriteUInt8(MpdUtilities.GetRandomUInt8());
                }

                negotiatingState_   = NegotiatingStateEnum.ONS_BASIC_CLIENTB_MAGICVALUE;
                streamCryptState_   = StreamCryptStateEnum.ECS_NEGOTIATING;
                receiveBytesWanted_ = 4;

                SendNegotiatingData(fileRequest.Buffer, (uint)fileRequest.Length, 5);
            }
            else if (streamCryptState_ == StreamCryptStateEnum.ECS_PENDING_SERVER)
            {
                SafeMemFile fileRequest = MpdObjectManager.CreateSafeMemFile(113);
                byte        bySemiRandomNotProtocolMarker = GetSemiRandomNotProtocolMarker();
                fileRequest.WriteUInt8(bySemiRandomNotProtocolMarker);

                cryptDHA_.genRandomBits((int)MuleConstants.DHAGREEMENT_A_BITS, new Random()); // our random a
                BigInteger cryptDHPrime =
                    new BigInteger(dh768_p_, (int)MuleConstants.PRIMESIZE_BYTES);             // our fixed prime
                // calculate g^a % p
                BigInteger cryptDHGexpAmodP =
                    new BigInteger(2).modPow(cryptDHA_, cryptDHPrime);

                // put the result into a buffer
                byte[] aBuffer = new byte[MuleConstants.PRIMESIZE_BYTES];
                Array.Copy(cryptDHGexpAmodP.getBytes(), aBuffer, MuleConstants.PRIMESIZE_BYTES);

                fileRequest.Write(aBuffer);
                byte byPadding = (byte)(MpdUtilities.GetRandomUInt8() % 16); // add random padding
                fileRequest.WriteUInt8(byPadding);
                for (int i = 0; i < byPadding; i++)
                {
                    fileRequest.WriteUInt8(MpdUtilities.GetRandomUInt8());
                }

                negotiatingState_   = NegotiatingStateEnum.ONS_BASIC_SERVER_DHANSWER;
                streamCryptState_   = StreamCryptStateEnum.ECS_NEGOTIATING;
                receiveBytesWanted_ = 96;

                SendNegotiatingData(fileRequest.Buffer, (uint)fileRequest.Length, (uint)fileRequest.Length);
            }
            else
            {
                Debug.Assert(false);
                streamCryptState_ = StreamCryptStateEnum.ECS_NONE;
                return;
            }
        }
Exemplo n.º 7
0
        private int Negotiate(byte[] pBuffer, int offset, int nLen)
        {
            int nRead = 0;

            Debug.Assert(receiveBytesWanted_ > 0);
            try
            {
                while (negotiatingState_ != NegotiatingStateEnum.ONS_COMPLETE && receiveBytesWanted_ > 0)
                {
                    if (receiveBytesWanted_ > 512)
                    {
                        Debug.Assert(false);
                        return(0);
                    }

                    if (fiReceiveBuffer_ == null)
                    {
                        byte[] pReceiveBuffer = new byte[512]; // use a fixed size buffer
                        fiReceiveBuffer_ = MpdObjectManager.CreateSafeMemFile(pReceiveBuffer);
                    }
                    int nToRead = Math.Min(Convert.ToInt32(nLen) - nRead, Convert.ToInt32(receiveBytesWanted_));
                    fiReceiveBuffer_.Write(pBuffer, nRead, nToRead);
                    nRead += nToRead;
                    receiveBytesWanted_ -= Convert.ToUInt32(nToRead);
                    if (receiveBytesWanted_ > 0)
                    {
                        return(nRead);
                    }
                    uint nCurrentBytesLen = (uint)fiReceiveBuffer_.Position;

                    if (negotiatingState_ != NegotiatingStateEnum.ONS_BASIC_CLIENTA_RANDOMPART &&
                        negotiatingState_ != NegotiatingStateEnum.ONS_BASIC_SERVER_DHANSWER)
                    { // don't have the keys yet
                        byte[] pCryptBuffer = fiReceiveBuffer_.Buffer;
                        MuleUtilities.RC4Crypt(pCryptBuffer, pCryptBuffer, nCurrentBytesLen, rc4ReceiveKey_);
                    }
                    fiReceiveBuffer_.SeekToBegin();

                    switch (negotiatingState_)
                    {
                    case NegotiatingStateEnum.ONS_NONE:     // would be a bug
                        Debug.Assert(false);
                        return(0);

                    case NegotiatingStateEnum.ONS_BASIC_CLIENTA_RANDOMPART:
                    {
                        Debug.Assert(rc4ReceiveKey_ == null);

                        byte[] achKeyData = new byte[21];
                        MpdUtilities.Md4Cpy(achKeyData, MuleApplication.Instance.Preference.UserHash);
                        achKeyData[16] = Convert.ToByte(MuleConstants.MAGICVALUE_REQUESTER);
                        fiReceiveBuffer_.Read(achKeyData, 17, 4);         // random key part sent from remote client

                        MD5 md5 = MD5.Create();
                        rc4ReceiveKey_ =
                            MuleUtilities.RC4CreateKey(md5.ComputeHash(achKeyData), 16);
                        achKeyData[16] = Convert.ToByte(MuleConstants.MAGICVALUE_SERVER);
                        rc4SendKey_    =
                            MuleUtilities.RC4CreateKey(md5.ComputeHash(achKeyData), 16);

                        negotiatingState_   = NegotiatingStateEnum.ONS_BASIC_CLIENTA_MAGICVALUE;
                        receiveBytesWanted_ = 4;
                        break;
                    }

                    case NegotiatingStateEnum.ONS_BASIC_CLIENTA_MAGICVALUE:
                    {
                        uint dwValue = fiReceiveBuffer_.ReadUInt32();
                        if (dwValue == MuleConstants.MAGICVALUE_SYNC)
                        {
                            // yup, the one or the other way it worked, this is an encrypted stream
                            //DEBUG_ONLY( MpdUtilities.DebugLog(("Received proper magic value, clientIP: %s"), DbgGetIPString()) );
                            // set the receiver key
                            negotiatingState_   = NegotiatingStateEnum.ONS_BASIC_CLIENTA_METHODTAGSPADLEN;
                            receiveBytesWanted_ = 3;
                        }
                        else
                        {
                            MpdUtilities.DebugLogError(("CEncryptedStreamSocket: Received wrong magic value from clientIP %s on a supposly encrytped stream / Wrong Header"), DbgGetIPString());
                            OnError(Convert.ToInt32(EMSocketErrorCodeEnum.ERR_ENCRYPTION));
                            return(-1);
                        }
                        break;
                    }

                    case NegotiatingStateEnum.ONS_BASIC_CLIENTA_METHODTAGSPADLEN:
                        DbgByEncryptionSupported = fiReceiveBuffer_.ReadUInt8();
                        DbgByEncryptionRequested = fiReceiveBuffer_.ReadUInt8();
                        if (DbgByEncryptionRequested != Convert.ToByte(EncryptionMethodsEnum.ENM_OBFUSCATION))
                        {
                            MpdUtilities.AddDebugLogLine(EDebugLogPriority.DLP_LOW, false, ("CEncryptedStreamSocket: Client %s preffered unsupported encryption method (%i)"), DbgGetIPString(), DbgByEncryptionRequested);
                        }
                        receiveBytesWanted_ = fiReceiveBuffer_.ReadUInt8();
                        negotiatingState_   = NegotiatingStateEnum.ONS_BASIC_CLIENTA_PADDING;
                        if (receiveBytesWanted_ > 0)
                        {
                            break;
                        }
                        else
                        {
                            goto case NegotiatingStateEnum.ONS_BASIC_CLIENTA_PADDING;
                        }

                    case NegotiatingStateEnum.ONS_BASIC_CLIENTA_PADDING:
                    {
                        // ignore the random bytes, send the response, set status complete
                        SafeMemFile fileResponse = MpdObjectManager.CreateSafeMemFile(26);
                        fileResponse.WriteUInt32(MuleConstants.MAGICVALUE_SYNC);
                        byte bySelectedEncryptionMethod = Convert.ToByte(EncryptionMethodsEnum.ENM_OBFUSCATION);         // we do not support any further encryption in this version, so no need to look which the other client preferred
                        fileResponse.WriteUInt8(bySelectedEncryptionMethod);

                        IPEndPoint remoteEp = RemoteEndPoint as IPEndPoint;

                        byte byPaddingLen =
                            MuleApplication.Instance.ServerConnect.AwaitingTestFromIP(BitConverter.ToUInt32(remoteEp.Address.GetAddressBytes(), 0))
                                        ? Convert.ToByte(16) :
                            Convert.ToByte(MuleApplication.Instance.Preference.CryptTCPPaddingLength + 1);
                        byte byPadding = Convert.ToByte(MpdUtilities.GetRandomUInt8() % byPaddingLen);

                        fileResponse.WriteUInt8(byPadding);
                        for (int i = 0; i < byPadding; i++)
                        {
                            fileResponse.WriteUInt8(MpdUtilities.GetRandomUInt8());
                        }
                        SendNegotiatingData(fileResponse.Buffer, (uint)fileResponse.Length);
                        negotiatingState_ = NegotiatingStateEnum.ONS_COMPLETE;
                        streamCryptState_ = StreamCryptStateEnum.ECS_ENCRYPTING;
                        //DEBUG_ONLY( MpdUtilities.DebugLog(("CEncryptedStreamSocket: Finished Obufscation handshake with client %s (incoming)"), DbgGetIPString()) );
                        break;
                    }

                    case NegotiatingStateEnum.ONS_BASIC_CLIENTB_MAGICVALUE:
                    {
                        if (fiReceiveBuffer_.ReadUInt32() != MuleConstants.MAGICVALUE_SYNC)
                        {
                            MpdUtilities.DebugLogError(("CEncryptedStreamSocket: EncryptedstreamSyncError: Client sent wrong Magic Value as answer, cannot complete handshake (%s)"), DbgGetIPString());
                            OnError(Convert.ToInt32(EMSocketErrorCodeEnum.ERR_ENCRYPTION));
                            return(-1);
                        }
                        negotiatingState_   = NegotiatingStateEnum.ONS_BASIC_CLIENTB_METHODTAGSPADLEN;
                        receiveBytesWanted_ = 2;
                        break;
                    }

                    case NegotiatingStateEnum.ONS_BASIC_CLIENTB_METHODTAGSPADLEN:
                    {
                        DbgByEncryptionMethodSet = fiReceiveBuffer_.ReadUInt8();
                        if (DbgByEncryptionMethodSet != Convert.ToByte(EncryptionMethodsEnum.ENM_OBFUSCATION))
                        {
                            MpdUtilities.DebugLogError(("CEncryptedStreamSocket: Client %s set unsupported encryption method (%i), handshake failed"),
                                                       DbgGetIPString(), DbgByEncryptionMethodSet);
                            OnError(Convert.ToInt32(EMSocketErrorCodeEnum.ERR_ENCRYPTION));
                            return(-1);
                        }
                        receiveBytesWanted_ = fiReceiveBuffer_.ReadUInt8();
                        negotiatingState_   = NegotiatingStateEnum.ONS_BASIC_CLIENTB_PADDING;
                        if (receiveBytesWanted_ > 0)
                        {
                            break;
                        }
                        else
                        {
                            goto case NegotiatingStateEnum.ONS_BASIC_CLIENTB_PADDING;
                        }
                    }

                    case NegotiatingStateEnum.ONS_BASIC_CLIENTB_PADDING:
                        // ignore the random bytes, the handshake is complete
                        negotiatingState_ = NegotiatingStateEnum.ONS_COMPLETE;
                        streamCryptState_ = StreamCryptStateEnum.ECS_ENCRYPTING;
                        //DEBUG_ONLY( MpdUtilities.DebugLog(("CEncryptedStreamSocket: Finished Obufscation handshake with client %s (outgoing)"), DbgGetIPString()) );
                        break;

                    case NegotiatingStateEnum.ONS_BASIC_SERVER_DHANSWER:
                    {
                        Debug.Assert(cryptDHA_ != new BigInteger(0));
                        byte[] aBuffer = new byte[MuleConstants.PRIMESIZE_BYTES + 1];
                        fiReceiveBuffer_.Read(aBuffer, 0, Convert.ToInt32(MuleConstants.PRIMESIZE_BYTES));
                        BigInteger cryptDHAnswer =
                            new BigInteger(aBuffer, (int)MuleConstants.PRIMESIZE_BYTES);
                        BigInteger cryptDHPrime =
                            new BigInteger(dh768_p_, (int)MuleConstants.PRIMESIZE_BYTES);          // our fixed prime
                        BigInteger cryptResult =
                            cryptDHAnswer.modPow(cryptDHA_, cryptDHPrime);

                        cryptDHA_ = 0;
                        Array.Clear(aBuffer, 0, aBuffer.Length);

                        // create the keys
                        Array.Copy(cryptResult.getBytes(), aBuffer, MuleConstants.PRIMESIZE_BYTES);
                        aBuffer[MuleConstants.PRIMESIZE_BYTES] = Convert.ToByte(MuleConstants.MAGICVALUE_REQUESTER);
                        MD5 md5 = MD5.Create();

                        rc4SendKey_ =
                            MuleUtilities.RC4CreateKey(md5.ComputeHash(aBuffer), 16);
                        aBuffer[MuleConstants.PRIMESIZE_BYTES] = Convert.ToByte(MuleConstants.MAGICVALUE_SERVER);
                        rc4ReceiveKey_ =
                            MuleUtilities.RC4CreateKey(md5.ComputeHash(aBuffer), 16);

                        negotiatingState_   = NegotiatingStateEnum.ONS_BASIC_SERVER_MAGICVALUE;
                        receiveBytesWanted_ = 4;
                        break;
                    }

                    case NegotiatingStateEnum.ONS_BASIC_SERVER_MAGICVALUE:
                    {
                        uint dwValue = fiReceiveBuffer_.ReadUInt32();
                        if (dwValue == MuleConstants.MAGICVALUE_SYNC)
                        {
                            // yup, the one or the other way it worked, this is an encrypted stream
                            MpdUtilities.DebugLog(("Received proper magic value after DH-Agreement from Serverconnection IP: %s"), DbgGetIPString());
                            // set the receiver key
                            negotiatingState_   = NegotiatingStateEnum.ONS_BASIC_SERVER_METHODTAGSPADLEN;
                            receiveBytesWanted_ = 3;
                        }
                        else
                        {
                            MpdUtilities.DebugLogError(("CEncryptedStreamSocket: Received wrong magic value after DH-Agreement from Serverconnection"), DbgGetIPString());
                            OnError(Convert.ToInt32(EMSocketErrorCodeEnum.ERR_ENCRYPTION));
                            return(-1);
                        }
                        break;
                    }

                    case NegotiatingStateEnum.ONS_BASIC_SERVER_METHODTAGSPADLEN:
                        DbgByEncryptionSupported = fiReceiveBuffer_.ReadUInt8();
                        DbgByEncryptionRequested = fiReceiveBuffer_.ReadUInt8();
                        if (DbgByEncryptionRequested != Convert.ToByte(EncryptionMethodsEnum.ENM_OBFUSCATION))
                        {
                            MpdUtilities.AddDebugLogLine(EDebugLogPriority.DLP_LOW, false, ("CEncryptedStreamSocket: Server %s preffered unsupported encryption method (%i)"), DbgGetIPString(), DbgByEncryptionRequested);
                        }
                        receiveBytesWanted_ = fiReceiveBuffer_.ReadUInt8();
                        negotiatingState_   = NegotiatingStateEnum.ONS_BASIC_SERVER_PADDING;
                        if (receiveBytesWanted_ > 16)
                        {
                            MpdUtilities.AddDebugLogLine(EDebugLogPriority.DLP_LOW, false, ("CEncryptedStreamSocket: Server %s sent more than 16 (%i) padding bytes"), DbgGetIPString(), receiveBytesWanted_);
                        }
                        if (receiveBytesWanted_ > 0)
                        {
                            break;
                        }
                        else
                        {
                            goto case NegotiatingStateEnum.ONS_BASIC_SERVER_PADDING;
                        }

                    case NegotiatingStateEnum.ONS_BASIC_SERVER_PADDING:
                    {
                        // ignore the random bytes (they are decrypted already), send the response, set status complete
                        SafeMemFile fileResponse = MpdObjectManager.CreateSafeMemFile(26);
                        fileResponse.WriteUInt32(MuleConstants.MAGICVALUE_SYNC);
                        byte bySelectedEncryptionMethod =
                            Convert.ToByte(EncryptionMethodsEnum.ENM_OBFUSCATION);         // we do not support any further encryption in this version, so no need to look which the other client preferred
                        fileResponse.WriteUInt8(bySelectedEncryptionMethod);
                        byte byPadding = (byte)(MpdUtilities.GetRandomUInt8() % 16);
                        fileResponse.WriteUInt8(byPadding);
                        for (int i = 0; i < byPadding; i++)
                        {
                            fileResponse.WriteUInt8(MpdUtilities.GetRandomUInt8());
                        }

                        negotiatingState_ = NegotiatingStateEnum.ONS_BASIC_SERVER_DELAYEDSENDING;
                        SendNegotiatingData(fileResponse.Buffer, (uint)fileResponse.Length, 0, true);         // don't actually send it right now, store it in our sendbuffer
                        streamCryptState_ = StreamCryptStateEnum.ECS_ENCRYPTING;
                        MpdUtilities.DebugLog(("CEncryptedStreamSocket: Finished DH Obufscation handshake with Server %s"), DbgGetIPString());
                        break;
                    }

                    default:
                        Debug.Assert(false);
                        break;
                    }
                    fiReceiveBuffer_.SeekToBegin();
                }

                fiReceiveBuffer_ = null;
                return(nRead);
            }
            catch (Exception)
            {
                Debug.Assert(false);
                OnError(Convert.ToInt32(EMSocketErrorCodeEnum.ERR_ENCRYPTION));
                fiReceiveBuffer_ = null;
                return(-1);
            }
        }
Exemplo n.º 8
0
        private void HandleParams(string[] allParams)
        {
            if (allParams == null || allParams.Length == 0)
            {
                return;
            }

            bool bError = false;

            for (int i = 0; !bError && i < allParams.Length; i++)
            {
                string strParam = allParams[i];

                string[] tokens = strParam.Split('=');

                if (tokens == null || tokens.Length < 2)
                {
                    //TODO:Log
                    continue;
                }

                string strTok = tokens[0];
                if (strTok.Equals("s"))
                {
                    string strURL = strParam.Substring(strTok.Length + 1);

                    if (!string.IsNullOrEmpty(strURL))
                    {
                        if (Uri.IsWellFormedUriString(strURL, UriKind.RelativeOrAbsolute))
                        {
                            Uri uri = new Uri(strURL, UriKind.RelativeOrAbsolute);

                            UnresolvedHostname hostname =
                                MuleApplication.Instance.ED2KObjectManager.CreateUnresolvedHostname();

                            hostname.Url      = strURL;
                            hostname.HostName = uri.Host;
                            hostname.Port     = Convert.ToUInt16(uri.Port);
                            hostnameSourcesList_.Add(hostname);
                        }
                        else
                        {
                            //ASSERT(0);
                            //TODO:Log
                        }
                    }
                    else
                    {
                        //ASSERT(0);
                        //TODO:Log
                    }
                }
                else if (strTok.Equals("p"))
                {
                    string strPartHashs = tokens[1];

                    if (HashSet != null)
                    {
                        //ASSERT(0);
                        //TODO:Log
                        bError = true;
                        break;
                    }

                    HashSet = MpdObjectManager.CreateSafeMemFile(256);
                    HashSet.WriteHash16(hash_);
                    HashSet.WriteUInt16(0);

                    int      iPartHashs = 0;
                    string[] strHashs   = strPartHashs.Split(':');

                    while (strHashs != null && iPartHashs < strHashs.Length)
                    {
                        if (string.IsNullOrEmpty(strHashs[iPartHashs]))
                        {
                            //TODO:Log
                            continue;
                        }

                        byte[] aucPartHash = new byte[16];
                        if (!MpdUtilities.DecodeHexString(strHashs[iPartHashs], aucPartHash))
                        {
                            bError = true;
                            break;
                        }
                        HashSet.WriteHash16(aucPartHash);
                        iPartHashs++;
                    }

                    if (bError)
                    {
                        break;
                    }

                    HashSet.Seek(16, System.IO.SeekOrigin.Begin);
                    HashSet.WriteUInt16(Convert.ToUInt16(iPartHashs));
                    HashSet.Seek(0, System.IO.SeekOrigin.Begin);
                }
                else if (strTok.Equals("h"))
                {
                    string strHash = strParam.Substring(strTok.Length + 1);
                    if (!string.IsNullOrEmpty(strHash))
                    {
                        if (MpdUtilities.DecodeBase32(strHash.ToCharArray(), aichHash_.RawHash) == MuleConstants.HASHSIZE)
                        {
                            aichHashValid_ = true;
                        }
                        else
                        {
                            //ASSERT(0);
                            //TODO:Log
                        }
                    }
                    else
                    {
                        //ASSERT(0);
                        //TODO:Log
                    }
                }
                else
                {
                    //ASSERT(0);
                    //TODO:Log
                }
            }

            if (bError)
            {
                HashSet = null;
            }
        }
Exemplo n.º 9
0
        private void HandleSources(string pszSources)
        {
            if (string.IsNullOrEmpty(pszSources))
            {
                return;
            }

            bool bAllowSources;
            int  nYear, nMonth, nDay;

            ushort nCount = 0;
            uint   dwID;
            ushort nPort;
            uint   dwServerIP  = 0;
            ushort nServerPort = 0;

            int nInvalid = 0;

            int pCh = pszSources.IndexOf("sources");

            if (pCh < 0)
            {
                return;
            }

            pCh = pCh + 7; // point to char after "sources"
            int pEnd = pszSources.Length;

            bAllowSources = true;

            // if there's an expiration date...
            if (pszSources[pCh] == '@' && (pEnd - pCh) > 7)
            {
                // after '@'
                pCh++;

                int.TryParse(pszSources.Substring(pCh, 2), out nYear);
                nYear += 2000;
                pCh   += 2;

                int.TryParse(pszSources.Substring(pCh, 2), out nMonth);
                pCh += 2;

                int.TryParse(pszSources.Substring(pCh, 2), out nDay);
                pCh += 2;

                DateTime expirationDate = DateTime.Now;

                try
                {
                    expirationDate = new DateTime(nYear, nMonth, nDay);
                }
                catch
                {
                }

                bAllowSources = expirationDate != null;

                if (bAllowSources)
                {
                    bAllowSources = (DateTime.Today < expirationDate);
                }
            }

            // increment pCh to point to the first "ip:port" and check for sources
            if (bAllowSources && ++pCh < pEnd)
            {
                SourcesList = MpdObjectManager.CreateSafeMemFile(256);
                // init to 0, we'll fix this at the end.
                SourcesList.WriteUInt16(nCount);
                // for each "ip:port" source string until the end
                // limit to prevent overflow (ushort due to CPartFile::AddClientSources)
                while (pCh < pEnd && nCount < ushort.MaxValue)
                {
                    string strIP = string.Empty;
                    int    pIP   = pCh;

                    // find the end of this ip:port string & start of next ip:port string.
                    if ((pCh = pszSources.IndexOf(',', pCh)) >= 0)
                    {
                        strIP = pszSources.Substring(pIP, pCh - pIP);

                        pCh++; // point to next "ip:port"
                    }
                    else
                    {
                        pCh = pEnd;
                    }

                    // if port is not present for this ip, go to the next ip.
                    int pPort = -1;

                    if ((pPort = strIP.IndexOf(':')) < 0)
                    {
                        nInvalid++;
                        continue;
                    }

                    string strPort = strIP.Substring(pPort + 1);        // terminate ip string
                    strIP = strIP.Substring(0, pPort);

                    if (!ushort.TryParse(strPort, out nPort))
                    {
                        nInvalid++;
                        continue;
                    }

                    // skip bad ips / ports
                    if (nPort > 0xFFFF || nPort == 0)   // port
                    {
                        nInvalid++;
                        continue;
                    }

                    IPAddress address = null;

                    if (!IPAddress.TryParse(strIP, out address))
                    {
                        // hostname?
                        if (strIP.Length > 512)
                        {
                            nInvalid++;
                            continue;
                        }

                        UnresolvedHostname hostname =
                            MuleApplication.Instance.ED2KObjectManager.CreateUnresolvedHostname();

                        hostname.Port     = nPort;
                        hostname.HostName = strIP;

                        hostnameSourcesList_.Add(hostname);
                        continue;
                    }

                    //TODO: This will filter out *.*.*.0 clients. Is there a nice way to fix?
                    dwID = BitConverter.ToUInt32(address.GetAddressBytes(), 0);

                    if (MuleUtilities.IsLowID(dwID))    // ip
                    {
                        nInvalid++;
                        continue;
                    }

                    SourcesList.WriteUInt32(dwID);
                    SourcesList.WriteUInt16(nPort);
                    SourcesList.WriteUInt32(dwServerIP);
                    SourcesList.WriteUInt16(nServerPort);
                    nCount++;
                }

                SourcesList.SeekToBegin();
                SourcesList.WriteUInt16(nCount);
                SourcesList.SeekToBegin();

                if (nCount == 0)
                {
                    SourcesList = null;
                }
            }
        }
Exemplo n.º 10
0
        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);
        }