Exemple #1
0
 public void CopyTags(TagList tags)
 {
     foreach (Tag tag in tags)
     {
         tagList_.Add(MpdObjectManager.CreateTag(tag));
     }
 }
 public ED2KFileLink CreateED2KFileLink(string pszName,
                                        string pszSize,
                                        string pszHash,
                                        string[] allParams,
                                        string pszSources)
 {
     return(MpdObjectManager.CreateObject(typeof(ED2KFileLinkImpl), pszName, pszSize, pszHash, allParams, pszSources) as ED2KFileLink);
 }
Exemple #3
0
        protected void InitalizeCrypting()
        {
            publicKeyLen_ = 0;
            Array.Clear(publicKey_, 0, 80); // not really needed; better for debugging tho
            signkey_ = null;
            if (!MuleApplication.Instance.Preference.IsSecureIdentEnabled)
            {
                return;
            }
            // check if keyfile is there
            bool bCreateNewKey = false;

            string filename =
                System.IO.Path.Combine(MuleApplication.Instance.Preference.GetMuleDirectory(Mule.Preference.DefaultDirectoryEnum.EMULE_CONFIGDIR),
                                       "crytkey.dat");

            if (System.IO.File.Exists(filename))
            {
                FileInfo info = new FileInfo(filename);

                if (info.Length == 0)
                {
                    bCreateNewKey = true;
                }
            }
            else
            {
                bCreateNewKey = true;
            }

            if (bCreateNewKey)
            {
                CreateKeyPair();
            }

            // load key
            try
            {
                string keyText = System.IO.File.ReadAllText(filename);
                byte[] key     = Convert.FromBase64String(keyText);

                // load private key
                signkey_ = MpdObjectManager.CreateRSAPKCS1V15SHA1Signer(key);

                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider((int)MuleConstants.RSAKEYSIZE);
                rsa.ImportCspBlob(key);

                byte[] tmp = rsa.ExportCspBlob(false);
                Array.Copy(tmp, publicKey_, tmp.Length);
                publicKeyLen_ = (byte)tmp.Length;
            }
            catch (Exception ex)
            {
                signkey_ = null;
                MpdUtilities.DebugLogError(ex);
            }
        }
Exemple #4
0
 private object CreateObject(string configFullTypeName,
                             string defaultFullName)
 {
     if (string.IsNullOrEmpty(configFullTypeName))
     {
         return(MpdObjectManager.CreateObject(Type.GetType(defaultFullName)));
     }
     else
     {
         return(MpdObjectManager.CreateObject(Type.GetType(configFullTypeName)));
     }
 }
Exemple #5
0
        public static bool WriteOptED2KUTF8Tag(FileDataIO file,
                                               string filename, byte uTagName)
        {
            if (!NeedUTF8String(filename))
            {
                return(false);
            }
            Tag tag = MpdObjectManager.CreateTag(uTagName, filename);

            tag.WriteTagToFile(file, Utf8StrEnum.utf8strOptBOM);
            return(true);
        }
Exemple #6
0
        public void SetInt64TagValue(byte nameId, ulong uValue)
        {
            foreach (Tag tag in tagList_)
            {
                if (tag.NameID == nameId &&
                    tag.IsInt64(true))
                {
                    tag.Int64 = uValue;
                    return;
                }
            }

            Tag newTag = MpdObjectManager.CreateTag(nameId, uValue);

            tagList_.Add(newTag);
        }
Exemple #7
0
        public void SetStrTagValue(byte nameId, string val)
        {
            foreach (Tag tag in tagList_)
            {
                if (tag.NameID == nameId &&
                    tag.IsStr)
                {
                    tag.Str = val;
                    return;
                }
            }

            Tag newTag = MpdObjectManager.CreateTag(nameId, val);

            tagList_.Add(newTag);
        }
Exemple #8
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);
            }
        }
Exemple #9
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);
            }
        }
        public bool InitFromLink(string sLink)
        {
            ED2KLink     pLink     = null;
            ED2KFileLink pFileLink = null;

            try
            {
                pLink = MuleApplication.Instance.ED2KObjectManager.CreateLinkFromUrl(sLink);
                if (pLink == null)
                {
                    throw new Exception("Not a Valid file link:" + sLink);
                }

                pFileLink = pLink.FileLink;
                if (pFileLink == null)
                {
                    throw new Exception("Not a Valid file link:" + sLink);
                }
            }
            catch (Exception)
            {
                //TODO:Log
                return(false);
            }

            tagList_.Add(MpdObjectManager.CreateTag(MuleConstants.FT_FILEHASH, pFileLink.HashKey));
            MpdUtilities.Md4Cpy(FileHash, pFileLink.HashKey);

            tagList_.Add(MpdObjectManager.CreateTag(MuleConstants.FT_FILESIZE, pFileLink.Size, true));
            FileSize = pFileLink.Size;

            tagList_.Add(MpdObjectManager.CreateTag(MuleConstants.FT_FILENAME, pFileLink.Name));
            SetFileName(pFileLink.Name, false, false, false);

            return(true);
        }
Exemple #11
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;
            }
        }
Exemple #12
0
 public FileIdentifier CreateFileIdentifier(params object[] args)
 {
     return(MpdObjectManager.CreateObject(typeof(FileIdentifierImpl), args) as FileIdentifier);
 }
Exemple #13
0
 public KnownFile CreateKnownFile()
 {
     return(MpdObjectManager.CreateObject(typeof(KnownFileImpl)) as KnownFile);
 }
Exemple #14
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);
            }
        }
Exemple #15
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);
        }
Exemple #16
0
        public static void ConvertED2KTag(ref Tag pTag)
        {
            if (pTag.NameID == 0 && pTag.Name != null)
            {
                EmuleToED2KMetaTagsMap[] _aEmuleToED2KMetaTagsMap = new EmuleToED2KMetaTagsMap[]
                {
                    // Artist, Album and Title are disabled because they should be already part of the filename
                    // and would therefore be redundant information sent to the servers.. and the servers count the
                    // amount of sent data!
                    new EmuleToED2KMetaTagsMap(MuleConstants.FT_MEDIA_ARTIST, MuleConstants.TAGTYPE_STRING, MuleConstants.FT_ED2K_MEDIA_ARTIST),
                    new EmuleToED2KMetaTagsMap(MuleConstants.FT_MEDIA_ALBUM, MuleConstants.TAGTYPE_STRING, MuleConstants.FT_ED2K_MEDIA_ALBUM),
                    new EmuleToED2KMetaTagsMap(MuleConstants.FT_MEDIA_TITLE, MuleConstants.TAGTYPE_STRING, MuleConstants.FT_ED2K_MEDIA_TITLE),
                    new EmuleToED2KMetaTagsMap(MuleConstants.FT_MEDIA_LENGTH, MuleConstants.TAGTYPE_STRING, MuleConstants.FT_ED2K_MEDIA_LENGTH),
                    new EmuleToED2KMetaTagsMap(MuleConstants.FT_MEDIA_LENGTH, MuleConstants.TAGTYPE_UINT32, MuleConstants.FT_ED2K_MEDIA_LENGTH),
                    new EmuleToED2KMetaTagsMap(MuleConstants.FT_MEDIA_BITRATE, MuleConstants.TAGTYPE_UINT32, MuleConstants.FT_ED2K_MEDIA_BITRATE),
                    new EmuleToED2KMetaTagsMap(MuleConstants.FT_MEDIA_CODEC, MuleConstants.TAGTYPE_STRING, MuleConstants.FT_ED2K_MEDIA_CODEC)
                };

                for (int j = 0; j < _aEmuleToED2KMetaTagsMap.Length; j++)
                {
                    if (string.Compare(pTag.Name, _aEmuleToED2KMetaTagsMap[j].pszED2KName) == 0 &&
                        ((pTag.IsStr && _aEmuleToED2KMetaTagsMap[j].nED2KType == MuleConstants.TAGTYPE_STRING) ||
                         (pTag.IsInt && _aEmuleToED2KMetaTagsMap[j].nED2KType == MuleConstants.TAGTYPE_UINT32)))
                    {
                        if (pTag.IsStr)
                        {
                            if (_aEmuleToED2KMetaTagsMap[j].nID == MuleConstants.FT_MEDIA_LENGTH)
                            {
                                uint     nMediaLength = 0;
                                uint     hour = 0, min = 0, sec = 0;
                                DateTime dt = DateTime.Now;

                                if (MpdUtilities.Scan3UInt32(pTag.Str, ref hour, ref min, ref sec) == 3)
                                {
                                    nMediaLength = hour * 3600 + min * 60 + sec;
                                }
                                else if (MpdUtilities.Scan2UInt32(pTag.Str, ref min, ref sec) == 2)
                                {
                                    nMediaLength = min * 60 + sec;
                                }
                                else if (MpdUtilities.ScanUInt32(pTag.Str, ref sec) == 1)
                                {
                                    nMediaLength = sec;
                                }

                                if (nMediaLength == 0)
                                {
                                    pTag = null;
                                }
                                else
                                {
                                    pTag =
                                        MpdObjectManager.CreateTag(_aEmuleToED2KMetaTagsMap[j].nID,
                                                                   nMediaLength);
                                }
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(pTag.Str))
                                {
                                    pTag =
                                        MpdObjectManager.CreateTag(_aEmuleToED2KMetaTagsMap[j].nID, pTag.Str);
                                }
                                else
                                {
                                    pTag = null;
                                }
                            }
                        }
                        else if (pTag.IsInt)
                        {
                            if (pTag.Int != 0)
                            {
                                pTag =
                                    MpdObjectManager.CreateTag(_aEmuleToED2KMetaTagsMap[j].nID, pTag.Int);
                            }
                            else
                            {
                                pTag = null;
                            }
                        }
                        break;
                    }
                }
            }
        }
Exemple #17
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);
            }
        }
 public ED2KServerLink CreateED2KServerLink(string ip, string port)
 {
     return(MpdObjectManager.CreateObject(typeof(ED2KServerLinkImpl), ip, port) as ED2KServerLink);
 }
Exemple #19
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);
                }
            }
        }
 public ProxySettings CreateProxySettings()
 {
     return(MpdObjectManager.CreateObject(typeof(ProxySettingsImpl)) as ProxySettings);
 }
 public MuleStatistics CreateStatistics()
 {
     return(MpdObjectManager.CreateObject(typeof(MuleStatisticsImpl)) as MuleStatistics);
 }
Exemple #22
0
        public bool VerifyIdent(ClientCredits pTarget,
                                byte[] pachSignature, byte nInputSize,
                                uint dwForIP, byte byChaIPKind)
        {
            if (!IsCryptoAvailable)
            {
                pTarget.IdentState = IdentStateEnum.IS_NOTAVAILABLE;
                return(false);
            }
            bool bResult;

            try
            {
                RSAPKCS1SignatureDeformatter pubkey =
                    MpdObjectManager.CreateRSAPKCS1V15SHA1Verifier(pTarget.SecureIdent, pTarget.SecIDKeyLen);
                // 4 additional bytes random data send from this client +5 bytes v2
                byte[] abyBuffer = new byte[CreditStruct.MAXPUBKEYSIZE + 9];
                Array.Copy(publicKey_, abyBuffer, publicKeyLen_);
                uint challenge = pTarget.CryptRndChallengeFor;

                Array.Copy(BitConverter.GetBytes(challenge), 0,
                           abyBuffer, publicKeyLen_, 4);

                // v2 security improvments (not supported by 29b, not used as default by 29c)
                byte nChIpSize = 0;
                if (byChaIPKind != 0)
                {
                    nChIpSize = 5;
                    uint ChallengeIP = 0;
                    switch (byChaIPKind)
                    {
                    case CRYPT_CIP_LOCALCLIENT:
                        ChallengeIP = dwForIP;
                        break;

                    case CRYPT_CIP_REMOTECLIENT:
                        if (MuleApplication.Instance.ServerConnect.ClientID == 0 ||
                            MuleApplication.Instance.ServerConnect.IsLowID)
                        {
                            ChallengeIP = MuleApplication.Instance.ServerConnect.LocalIP;
                        }
                        else
                        {
                            ChallengeIP = MuleApplication.Instance.ServerConnect.ClientID;
                        }
                        break;

                    case CRYPT_CIP_NONECLIENT:     // maybe not supported in future versions
                        ChallengeIP = 0;
                        break;
                    }
                    Array.Copy(BitConverter.GetBytes(ChallengeIP), 0,
                               abyBuffer, publicKeyLen_ + 4, 4);
                    abyBuffer[publicKeyLen_ + 4 + 4] = byChaIPKind;
                }
                //v2 end

                byte[] hash = new byte[publicKeyLen_ + 4 + nChIpSize];
                Array.Copy(abyBuffer, hash, publicKeyLen_ + 4 + nChIpSize);

                byte[] sign = new byte[nInputSize];
                Array.Copy(pachSignature, sign, nInputSize);

                bResult = pubkey.VerifySignature(hash, sign);
            }
            catch (Exception ex)
            {
                MpdUtilities.DebugLogError(ex);
                bResult = false;
            }
            if (!bResult)
            {
                if (pTarget.IdentState == IdentStateEnum.IS_IDNEEDED)
                {
                    pTarget.IdentState = IdentStateEnum.IS_IDFAILED;
                }
            }
            else
            {
                pTarget.Verified(dwForIP);
            }
            return(bResult);
        }
Exemple #23
0
        protected void LoadList()
        {
            string strFileName =
                System.IO.Path.Combine(MuleApplication.Instance.Preference.GetMuleDirectory(Mule.Preference.DefaultDirectoryEnum.EMULE_CONFIGDIR),
                                       CLIENTS_MET_FILENAME);

            if (!System.IO.File.Exists(strFileName))
            {
                return;
            }

            SafeBufferedFile file = null;

            try
            {
                file =
                    MpdObjectManager.CreateSafeBufferedFile(strFileName,
                                                            System.IO.FileMode.Open,
                                                            System.IO.FileAccess.Read,
                                                            System.IO.FileShare.None);

                byte version = file.ReadUInt8();

                if (version != (byte)VersionsEnum.CREDITFILE_VERSION &&
                    version != (byte)VersionsEnum.CREDITFILE_VERSION_29)
                {
                    file.Close();
                    return;
                }

                // everything is ok, lets see if the backup exist...
                string strBakFileName =
                    System.IO.Path.Combine(MuleApplication.Instance.Preference.GetMuleDirectory(Mule.Preference.DefaultDirectoryEnum.EMULE_CONFIGDIR),
                                           string.Format("{0}{1}", CLIENTS_MET_FILENAME, ".bak"));

                uint dwBakFileSize = 0;
                bool bCreateBackup = true;

                if (System.IO.File.Exists(strBakFileName))
                {
                    FileInfo fInfo = new FileInfo(strBakFileName);

                    dwBakFileSize = (uint)fInfo.Length;
                    if (dwBakFileSize > (uint)file.Length)
                    {
                        // the size of the backup was larger then the org. file, something is wrong here, don't overwrite old backup..
                        bCreateBackup = false;
                    }
                }
                //else: the backup doesn't exist, create it

                if (bCreateBackup)
                {
                    file.Close(); // close the file before copying

                    System.IO.File.Copy(strFileName, strBakFileName, true);

                    file = MpdObjectManager.CreateSafeBufferedFile(strFileName,
                                                                   System.IO.FileMode.Open,
                                                                   System.IO.FileAccess.Read,
                                                                   System.IO.FileShare.None);

                    file.Seek(1, SeekOrigin.Begin); //set filepointer behind file version byte
                }

                uint count = file.ReadUInt32();

                uint dwExpired = MpdUtilities.Time() - 12960000; // today - 150 day
                uint cDeleted  = 0;
                for (uint i = 0; i < count; i++)
                {
                    CreditStruct newcstruct = new CreditStruct();
                    if (version == (byte)VersionsEnum.CREDITFILE_VERSION_29)
                    {
                        ReadCreditStruct29a(file, newcstruct);
                    }
                    else
                    {
                        ReadCreditStruct(file, newcstruct);
                    }

                    if (newcstruct.nLastSeen < dwExpired)
                    {
                        cDeleted++;
                        continue;
                    }

                    ClientCredits newcredits =
                        MuleApplication.Instance.CoreObjectManager.CreateClientCredits(newcstruct);
                    clients_[new MapCKey(newcredits.Key)] = newcredits;
                }
                file.Close();
            }
            catch (Exception error)
            {
                MpdUtilities.DebugLogError(error);
                file.Close();
            }
        }
 public ED2KFileTypes CreateED2KFileTypes()
 {
     return(MpdObjectManager.CreateObject(typeof(ED2KFileTypesImpl)) as ED2KFileTypes);
 }
Exemple #25
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;
                }
            }
        }
Exemple #26
0
 public PartFile CreatePartFile(params object[] parameters)
 {
     return(MpdObjectManager.CreateObject(typeof(PartFileImpl), parameters) as PartFile);
 }
 public UnresolvedHostname CreateUnresolvedHostname()
 {
     return(MpdObjectManager.CreateObject(typeof(UnresolvedHostnameImpl)) as UnresolvedHostname);
 }
Exemple #28
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;
            }
        }
Exemple #29
0
 public UpDownClient CreateUpDownClient(params object[] args)
 {
     return(MpdObjectManager.CreateObject(typeof(UpDownClientImpl), args) as UpDownClient);
 }
 public ED2KServerListLink CreateED2KServerListLink(string address)
 {
     return(MpdObjectManager.CreateObject(typeof(ED2KServerListLinkImpl), address) as ED2KServerListLink);
 }