Exemplo n.º 1
0
        public void AddPartner(CClient client)
        {
            if (!AllowNewParner())
            {
                return;
            }

            //select a client and kick to allow slot for a partner
            m_AddingPartner = true;
            CClient kickClient;

            if ((UploadList.Count >= this.m_GetNumberOfSlots()))
            {
                for (int i = 0; i < UploadList.Count; i++)
                {
                    kickClient = (CClient)UploadList[i];
                    if (!kickClient.IsPartner)
                    {
                        kickClient.CancelUploadTransfer(true);
                        CLog.Log(Constants.Log.Verbose, "kicked " + kickClient.UserName + " to allow new partner");
                        break;
                    }
                }
            }

            if (client != null)
            {
                client.IsPartner = true;
                m_Partners++;
                client.StartUpload();
                m_LastAcceptedClientTime = DateTime.Now;
                UploadList.Add(client);
                m_QueueList.Remove(client);
                CKernel.NewUpload(client);
            }
            m_AddingPartner = false;
        }
Exemplo n.º 2
0
        /// <summary>
        /// Load a list of servers from binary file (server.met).
        /// </summary>
        /// <param name="fullpathfile">The full Path to the file.</param>
        /// <param name="clear">Set clear to true if the list should be cleared before read.</param>
        /// <returns>Count of servers which could be loaded.</returns>
        public int Load(string fullpathfile, bool clear)
        {
            if (clear)
            {
                Clear();
            }
            FileStream servermet;

            if (fullpathfile.Length == 0)
            {
                //fullpathfile=Application.StartupPath + Path.DirectorySeparatorChar + "server.met";
                fullpathfile = Path.Combine(CKernel.DllDirectory, "server.met");
            }

            try
            {
                servermet = File.OpenRead(fullpathfile);
            }
            catch
            {
                return(0);
            }

            byte         version;
            BinaryReader reader = new BinaryReader(servermet);
            int          added  = 0;

            try
            {
                version = reader.ReadByte();

                if (!Enum.IsDefined(typeof(Protocol.ServerMet), version))
                {
                    servermet.Close();
                    CLog.Log(Constants.Log.Notify, "SRVMET_INVALID");
                    return(0);
                }
                uint    nServers = reader.ReadUInt32();
                uint    ip;
                ushort  port;
                CServer server;
                while (nServers > 0)
                {
                    ip     = reader.ReadUInt32();
                    port   = reader.ReadUInt16();
                    server = Add(ip, port);
                    if (server != null)
                    {
                        added++;
                    }
                    else
                    {
                        server = this[ip, 0];
                    }
                    server.Load(reader);
                    nServers--;
                }
                Sort();
            }
            catch (EndOfStreamException eose)
            {
                Debug.WriteLine(eose.ToString());
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                CLog.Log(Constants.Log.Notify, "SRVMET_INVALID");
            }
            servermet.Close();
            CLog.Log(Constants.Log.Info, "SRV_ADDED", added);
            return(added);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Search sources for the 15 next files using TCP
        /// </summary>
        public void SearchNextSourcesTCP()
        {
            if ((ActiveServer != null) &&
                (!ActiveServer.AllFilesPublished) &&
                (DateTime.Now - ActiveServer.LastPublishedTime > new TimeSpan(0, 1, 0)))
            {
                ActiveServer.PublishSharedFiles();
            }
            if ((m_NextTCPSourcesSearch > DateTime.Now) || (ActiveServer == null) || (CKernel.FilesList.Count == 0))
            {
                return;
            }

            if (m_TimesshownUDPClosedMessage < 8)
            {
                m_TimesshownUDPClosedMessage++;
            }
            if ((!CKernel.UDPListener.PortIsAccesible) &&
                (m_TimesshownUDPClosedMessage < 8) &&
                (m_TimesshownUDPClosedMessage > 2) &&              //ignore first 2 pass
                (CKernel.Preferences.GetUInt("ID") > Protocol.LowIDLimit))
            {
                if (m_TimesshownUDPClosedMessage < 7)
                {
                    CLog.Log(Types.Constants.Log.Info, "UDP_PORT_NOT_OPEN");
                }
                else
                {
                    CLog.Log(Types.Constants.Log.Notify, "UDP_PORT_NOT_OPEN");
                }
            }
            ArrayList hashes = new ArrayList();
            CElement  Element;

            do
            {
                if (CKernel.FilesList.Count <= m_TCPSourceSearchFileIndex)
                {
                    m_TCPSourceSearchFileIndex = 0;
                    break;
                }
                else
                {
                    Element = CKernel.FilesList[m_TCPSourceSearchFileIndex];
                    m_TCPSourceSearchFileIndex++;
                }
                if ((Element.SourcesList != null) && (Element.File.FileStatus != Protocol.FileState.Stopped) && (Element.File.MaxSources > Element.SourcesList.Count() - 5))
                {
                    hashes.Add(Element.File.FileHash);
                }
            }while (hashes.Count < Protocol.SourcesPerTCPFrame);
            if ((m_TCPSourceSearchFileIndex == 0) || (hashes.Count == 0))
            {
                m_NextTCPSourcesSearch = DateTime.Now + new TimeSpan(0, Protocol.ReaskServerTCP, 0);
            }
            else
            {
                m_NextTCPSourcesSearch = DateTime.Now + new TimeSpan(0, 0, Protocol.ReaskNextTCPFile * hashes.Count);
            }
            if (hashes.Count > 0)
            {
                ActiveServer.RequestSources(hashes);
            }
        }
Exemplo n.º 4
0
        private void m_GetInfoXML()
        {
            XmlTextReader reader = null;

            try
            {
                reader   = new XmlTextReader(m_remoteInfoUri);
                m_myInfo = new Hashtable();

                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:
                        m_nodeName = reader.Name;
                        break;

                    case XmlNodeType.Text:
                        m_myInfo.Add(m_nodeName, reader.Value);
                        break;

                    case XmlNodeType.CDATA:
                        break;

                    case XmlNodeType.ProcessingInstruction:
                        break;

                    case XmlNodeType.Comment:
                        break;

                    case XmlNodeType.XmlDeclaration:
                        break;

                    case XmlNodeType.Document:
                        break;

                    case XmlNodeType.DocumentType:
                        break;

                    case XmlNodeType.EntityReference:
                        break;

                    case XmlNodeType.EndElement:
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }

            //display info to log. Usefull if threaded
            if (m_infoToLog != null)
            {
                foreach (string info in m_infoToLog)
                {
                    if (info != null)
                    {
                        m_information = getReadInfoFromXML(info);
                        CLog.Log(Constants.Log.Info, m_information);
                    }
                }
            }
        }
Exemplo n.º 5
0
        private void m_DownloadFile()
        {
            if (m_path.Length == 0)
            {
                m_path = Application.StartupPath;
            }

            m_fullpath = Path.Combine(m_path, m_fileName);

            try
            {
                if (File.Exists(m_fullpath))
                {
                    File.Copy(m_fullpath, m_fullpath + ".backup", true);
                }
            }
            catch {}

            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(m_remoteUri);

            myHttpWebRequest.UserAgent = "www.lPhant.com";
            HttpWebResponse myHttpWebResponse = null;

            try
            {
                CLog.Log(Constants.Log.Notify, "FIL_ADDED", m_fileName);
                myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
            }

            catch (WebException we)
            {
                try
                {
                    if (File.Exists(m_fullpath + ".backup"))
                    {
                        File.Copy(m_fullpath + ".backup", m_fullpath, true);
                    }
                    CLog.Log(Constants.Log.Info, we.Message);
                }
                catch {}

                m_isDownloaded = false;
                OnDownloaded(EventArgs.Empty);
                return;
            }

            Stream       receiveStream = myHttpWebResponse.GetResponseStream();
            BinaryReader readStream    = new BinaryReader(receiveStream);


            FileStream fileDownloaded;

            fileDownloaded = File.Open(m_fullpath, FileMode.Create);
            BinaryWriter BinWriter = new BinaryWriter(fileDownloaded);

            byte[] read  = new byte[1024];
            int    count = readStream.Read(read, 0, 1024);

            while (count > 0)
            {
                BinWriter.Write(read, 0, count);
                count = readStream.Read(read, 0, 1024);
            }

            BinWriter.Close();
            fileDownloaded.Close();
            readStream.Close();
            myHttpWebResponse.Close();

            CLog.Log(Constants.Log.Info, "FIL_DOWNLOADED", m_fileName, m_remoteUri);

            OnDownloaded(EventArgs.Empty);
            m_isDownloaded = true;
        }
Exemplo n.º 6
0
        private bool SetValueFromXmlElement(XmlElement element)
        {
            try
            {
                XmlNodeList nodes = element.ChildNodes;
                foreach (XmlElement el in nodes)
                {
                    if (el.Name == "Friend")
                    {
                        SFriend my_Friend = new SFriend();
                        my_Friend.FriendSlot = false;
                        //load Friend.UserHash
                        if (el.Attributes["UserHash"].InnerText != "")
                        {
                            byte[] x = null;
                            switch (_currentversion)
                            {
                            case "0.1":
                                x = new byte[el.Attributes["UserHash"].InnerText.Length];
                                x = Encoding.Default.GetBytes(el.Attributes["UserHash"].InnerText);
                                break;

                            case "0.2":
                                x = Convert.FromBase64String(el.Attributes["UserHash"].InnerText);
                                break;
                            }
                            my_Friend.UserHash = (byte[])x;
                        }
                        else
                        {
                            my_Friend.UserHash = null;
                        }

                        //load Friend.ID
                        my_Friend.ID = uint.Parse(el.Attributes["ID"].InnerText);

                        //load Friend.OurName
                        my_Friend.OurName = el.Attributes["OurName"].InnerText;

                        //load Friend.Name
                        my_Friend.Name = el.Attributes["Name"].InnerText;

                        //load Friend.Port
                        my_Friend.Port = ushort.Parse(el.Attributes["Port"].InnerText);

                        //load Friend.Software
                        my_Friend.Software = el.Attributes["Software"].InnerText;

                        //load Friend.Version
                        my_Friend.Version = uint.Parse(el.Attributes["Version"].InnerText);

                        //load Friend.LastOnline
                        my_Friend.LastOnline = new DateTime(long.Parse(el.Attributes["LastOnline"].InnerText));

                        //load friendSlot
                        if (el.Attributes["FriendSlot"] != null)
                        {
                            my_Friend.FriendSlot = bool.Parse(el.Attributes["FriendSlot"].InnerText);
                        }

                        List.Add(my_Friend);
                        Constants.FriendLevel friendSlot;
                        if (my_Friend.FriendSlot)
                        {
                            friendSlot = Constants.FriendLevel.FriendSlot;
                        }
                        else
                        {
                            friendSlot = Constants.FriendLevel.Friend;
                        }

                        CKernel.ClientsList.AddClient(my_Friend.ID, my_Friend.Port, 0, my_Friend.UserHash, my_Friend.Port, null, friendSlot);

                        //switch ( el.Attributes["type"].InnerText )
                    }
                }
            }
            catch
            {
                CLog.Log(Constants.Log.Info, "Error loading friends list");
                return(false);
            }
            return(true);
        }
Exemplo n.º 7
0
        public void Process()
        {
            //Search more sources in the connected server
//			if (((DateTime.Now-m_LastTCPSearch)>new TimeSpan(0,Protocol.ReaskClient,0))&&
//				(CKernel.Preferences.GetInt("MaxSourcesPerFile")>m_ArrayList.Count-5))
//			{
//				if ((CKernel.ServersList.ActiveServer!=null)&&(m_Element!=null)&&(m_Element.File!=null))
//				{
//					CKernel.ServersList.ActiveServer.RequestSources(m_Element.File.FileHash);
//					m_LastTCPSearch=DateTime.Now;
//					Debug.Write("Asking for file "+ m_Element.File.GetFileName() +"\n");
//				}
//			}
            float     aux_VelocidadDescarga   = 0;
            ushort    aux_nDownloadingClients = 0;
            ushort    aux_nUsableClients      = 0;
            float     factor;
            ArrayList timedOutCalledBack = null;

            lock (m_ArrayList.SyncRoot)
            {
                try
                {
                    foreach (CClient Client in m_ArrayList)
                    {
                        factor = 1.0F;
                        if (Client.DownloadState == Protocol.DownloadState.NoNeededParts)
                        {
                            factor = 2.0F;
                        }
                        else if ((Client.SoftwareID == (uint)Protocol.Client.mlDonkey) && (Client.DownloadTries > 0))
                        {
                            factor = 0.55F;
                        }
                        else if ((Client.QRDownload == 0) && (Client.DownloadTries > 0))
                        {
                            factor = 0.75F;
                        }

                        if ((DateTime.Now - Client.LastDownloadRequest > new TimeSpan(0, 0, (int)((float)Protocol.MinClientReask * factor) - 1, 0)) &&
                            (Client.DownloadState != Protocol.DownloadState.Connecting) &&
                            (Client.DownloadState != Protocol.DownloadState.Downloading) &&
                            (Client.DownloadState != Protocol.DownloadState.Connected) &&
                            (Client.DownloadState != Protocol.DownloadState.WaitCallBack))
                        {
                            if (!Client.AskingUDP)
                            {
                                Client.TryUDPDownload();
                            }
                            else
                            {
                                if (DateTime.Now - Client.LastDownloadRequest > new TimeSpan(0, 0, (int)((float)Protocol.MinClientReask * factor), 0))
                                {
                                    Client.TryDownload();
                                }
                            }
                        }

                        if ((Client.DownloadState == Protocol.DownloadState.Downloading))
                        {
                            aux_nDownloadingClients++;
                            Client.UpdateDownloadSpeed();
                            aux_VelocidadDescarga += Client.DownloadSpeed;
                        }

                        if ((Client.DownloadState == Protocol.DownloadState.WaitCallBack)
                            //||(Client.UploadState==Protocol.UploadState.WaitCallBack))
                            && (Client.CallBackTimedOut))
                        {
                            if (timedOutCalledBack == null)
                            {
                                timedOutCalledBack = new ArrayList();
                            }
                            timedOutCalledBack.Add(Client);
                        }

                        if ((Client.DownloadState != Protocol.DownloadState.None) &&
                            (Client.DownloadState != Protocol.DownloadState.NoNeededParts))
                        {
                            aux_nUsableClients++;
                        }
                    }
                }
                catch (InvalidOperationException e)
                {
                    //in some vary rare case the enumerating the sources collection can fail
                    //possible errors a can not create a socket or similar
                    //we catch this execption and continue since we will process sources again in 1 second
                    //if entering here is not rare then we must delete the sources with this error outside the loop
#if DEBUG
                    CLog.Log(Types.Constants.Log.Verbose, "Error enumerating sources collection in SourcesList.Process " + e.ToString());
#endif
                    Debug.WriteLine(e.ToString());
                }
            }

            // Disconnect may modify the sources list collection, so we disconnect outside the loop
            if (timedOutCalledBack != null)
            {
                foreach (CClient CallBackClient in timedOutCalledBack)
                {
                    CallBackClient.OnDisconnect((byte)Protocol.ConnectionReason.CannotConnect);
                }
            }

            m_PrevDownloadSpeed   = m_DownloadSpeed;
            m_DownloadSpeed       = aux_VelocidadDescarga;
            m_nDownloadingClients = aux_nDownloadingClients;
            m_nUsableClients      = aux_nUsableClients;
        }
Exemplo n.º 8
0
        /// <summary>
        /// Process incomming eDonkey packet.
        /// </summary>
        /// <param name="packet">Packet which need to be processed.</param>
        protected virtual void ProcessDonkeyPacket(ref byte[] packet)
        {
            try
            {
                switch ((Protocol.ClientCommand)m_DonkeyHeader.Command)
                {
                case Protocol.ClientCommand.Hello:
                    if (m_Client == null)
                    {
                        CReceiveHello HelloPacket = new CReceiveHello(false, new MemoryStream(packet));
                        m_Client = CKernel.ClientsList.GetClient(HelloPacket.UserID, HelloPacket.UserPort, HelloPacket.ServerIP, HelloPacket.Hash);
                        if (m_Client == null)
                        {
                            m_Client = new CClient(this);
                            CKernel.ClientsList.AddClient(m_Client);
                        }
                        else
                        {
                            if ((m_Client.connection != null) && (m_Client.connection.Connected) && (m_Client.connection != this))
                            {
                                m_Client.connection.CloseConnection();
                                Debug.WriteLine("Client conexion!=null");
                            }
                            m_Client.connection = this;
                        }
                    }
                    CClient     cant              = m_Client;
                    CConnection conant            = m_Client.connection;
                    bool        NeedExtendRequest = !m_Client.ProcessHello(false, packet);
                    if ((NeedExtendRequest) && (m_Client.EmuleProtocol) && (CKernel.Preferences.GetBool("UseEmuleProtocol")))
                    {
                        m_Client.SendEmuleHello(false);
                    }
                    m_Client.ResponseHello();
                    break;

                case Protocol.ClientCommand.FileRequest:
                    m_Client.ProcessFileRequest(packet);
                    break;

                case Protocol.ClientCommand.HelloAnswer:
                    m_Client.ProcessHello(true, packet);
                    break;

                case Protocol.ClientCommand.SetRequestFileID:
                    m_Client.ProcessRequestFileID(packet);
                    break;

                case Protocol.ClientCommand.FileRequestAnswer:
                    m_Client.ProcessFileInfo(packet);
                    break;

                case Protocol.ClientCommand.FileState:
                    m_Client.ProcessChunksStatus(packet, false /*tcp*/);
                    break;

                case Protocol.ClientCommand.HashSetAnswer:
                    m_Client.ProcessHashSet(packet);
                    break;

                case Protocol.ClientCommand.HashSetRequest:
                    m_Client.SendHashSet();
                    break;

                case Protocol.ClientCommand.AcceptUploadRequest:
                    if (m_Client.DownloadState == Protocol.DownloadState.OnQueue)
                    {
                        m_Client.RequestBlocks();
                    }
                    else
                    {
                        if (m_Client.DownFileHash != null)
                        {
//								CLog.Log(Constants.Log.Verbose,"Trying to resume download {2}: {0},hashdescarga=null? {1}",m_Client.DownloadState,(m_Client.DownFileHash==null),m_Client.UserName);
                            m_Client.RequestBlocks();
                        }
                        else
                        {
                            if (m_Client.UpFileHash != null)
                            {
#if DEBUG
                                CLog.Log(Constants.Log.Verbose, "Recovering source to download " + m_Client.UserName);
#endif
                                m_Client.DownFileHash = m_Client.UpFileHash;
                                m_Client.RequestBlocks();
                            }

                            else
                            {
                                CSourceOld sourceRecovered = CKernel.SourcesOld.GetSourceOld(m_Client.UserHash);
                                if (sourceRecovered != null)
                                {
                                    m_Client.DownFileHash   = sourceRecovered.FileHash;
                                    m_Client.DownFileChunks = sourceRecovered.FileChunks;
                                    m_Client.RequestBlocks();
#if DEBUG
                                    CLog.Log(Constants.Log.Verbose, "RECOVERED SOURCE from sources cache " + m_Client.UserName);
#endif
                                }
#if DEBUG
                                else
                                {
                                    CLog.Log(Constants.Log.Verbose, "download lost: {0}", m_Client.UserName);
                                }
#endif
                            }
                        }
                    }
                    break;

                case Protocol.ClientCommand.OutOfPartRequest:
                    m_Client.ProcessOutOfParts();
                    break;

                case Protocol.ClientCommand.StartUploadRequest:
                    m_Client.ProcessStartUploadRequest(packet);
                    break;

                case Protocol.ClientCommand.RequestParts:
                    m_Client.ProcessRequestParts(packet);
                    break;

                case Protocol.ClientCommand.EndOfDownload:
                case Protocol.ClientCommand.CancelTransfer:
                    m_Client.CancelUploadTransfer(false);
                    break;

                case Protocol.ClientCommand.SendingPart:
                    m_Client.ReceiveBlock(packet);
                    break;

                case Protocol.ClientCommand.QueueRank:
                    m_Client.ProcessQR(packet);
                    break;

                case Protocol.ClientCommand.FileRequestAnswerNoFile:
                    m_Client.FileNotFound(packet);
                    break;

                case Protocol.ClientCommand.ChangeClientID:
                    m_Client.ProcessIDChange(packet);
                    break;

                case Protocol.ClientCommand.ChangeSlot:
                    break;

                case Protocol.ClientCommand.AskSharedFiles:
                    Constants.AllowViewShared allow = (Constants.AllowViewShared)CKernel.Preferences.GetEnum("AllowViewShared", Constants.AllowViewShared.Nobody);
                    if (allow == Constants.AllowViewShared.All)
                    {
                        m_Client.ProcessSharedListRequest();
                    }
                    break;

                case Protocol.ClientCommand.AskSharedFilesAnswer:
                    m_Client.ProcessSharedListResponse(packet);
                    break;

                case Protocol.ClientCommand.Message:
                    m_Client.ProcessChatMessage(packet);
                    break;

                case Protocol.ClientCommand.CrumbSetResponse:
                    m_Client.ProcessCrumbSetResponse(packet);
                    break;

                default:
                    CLog.Log(Constants.Log.Verbose, "CLI_UNK_DONK_TCP_PACKET", m_DonkeyHeader.Command);
                    break;
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
#if DEBUG
                if (m_DonkeyHeader != null)
                {
                    CLog.Log(Constants.Log.Verbose, "CLI_PAQ_DONK_ERROR", m_DonkeyHeader.Command);
                }
#endif
            }
            packet = null;
            return;
        }
Exemplo n.º 9
0
        public int SelectChunk(byte[] clientPartStatus, int lastRequestedPart)
        {
            ArrayList ActiveRareChunks  = new ArrayList();              //prioridad 1
            ArrayList ParcialRareChunks = new ArrayList();              //prioridad 2
            ArrayList RareChunks        = new ArrayList();              //prioridad 3
            ArrayList ParcialChunks     = new ArrayList();              //prioridad 4
            ArrayList EmptyChunks       = new ArrayList();              //prioridad 5
            ArrayList ActiveChunks      = new ArrayList();              //prioridad 6
            uint      minRareChunks     = 10;
            uint      maxRareChunks     = 1;

            if (m_Element == null)
            {
                return(-1);
            }
            if ((lastRequestedPart > -1) && (m_Element.File.RemainingToAskInChunk(lastRequestedPart)))
            {
                return(lastRequestedPart);
            }
            if (m_Avaibility.Length == 1)           //si el fichero solo tiene una parte
            {
                return(0);
            }
            byte[] chunkStatus = m_Element.File.ChunksStatus;

            //seleccionar primero la primera y última partes para poder hacer preview
            if ((((clientPartStatus == null)) || ((Protocol.ChunkState)clientPartStatus[0] == Protocol.ChunkState.Complete)) &&
                (m_Element.File.IsEmptyChunk(0)))
            {
                CLog.Log(Types.Constants.Log.Verbose, "selected 1st chunk");
                return(0);
            }
            if ((((clientPartStatus == null)) || ((Protocol.ChunkState)clientPartStatus[m_Element.File.NumChunks - 1] == Protocol.ChunkState.Complete)) &&
                (m_Element.File.IsEmptyChunk(m_Element.File.NumChunks - 1)))
            {
                CLog.Log(Types.Constants.Log.Verbose, "selected last chunk");
                return(m_Element.File.NumChunks - 1);
            }

            //calcular la ventana de partes Raras
            for (int i = 0; i != m_Avaibility.Length; i++)
            {
                if (((clientPartStatus == null) || ((Protocol.ChunkState)clientPartStatus[i] == Protocol.ChunkState.Complete)) && (m_Element.File.RemainingToAskInChunk(i)))
                {
                    if (m_Avaibility[i] < minRareChunks)
                    {
                        minRareChunks = m_Avaibility[i];
                    }
                    if (m_Avaibility[i] > maxRareChunks)
                    {
                        maxRareChunks = m_Avaibility[i];
                    }
                }
            }
            //Clasificar las partes por tipos
            for (int i = 0; i != m_Avaibility.Length; i++)
            {
                if (((Protocol.ChunkState)chunkStatus[i] == Protocol.ChunkState.InProgress) || ((Protocol.ChunkState)chunkStatus[i] == Protocol.ChunkState.Empty))
                {
                    if ((clientPartStatus == null) || ((Protocol.ChunkState)clientPartStatus[i] == Protocol.ChunkState.Complete))
                    {
                        //partes raras
                        if (m_Avaibility[i] == minRareChunks && minRareChunks < maxRareChunks)
                        {
                            if (m_Element.File.RequestingBlocksInChunk(i))
                            {
                                ActiveRareChunks.Add(i);
                            }
                            else if (!m_Element.File.IsEmptyChunk(i))
                            {
                                ParcialRareChunks.Add(i);
                            }
                            else
                            {
                                RareChunks.Add(i);
                            }
                        }
                        else if (m_Element.File.RequestingBlocksInChunk(i))
                        {
                            ActiveChunks.Add(i);
                        }
                        else if (m_Element.File.IsEmptyChunk(i))
                        {
                            EmptyChunks.Add(i);
                        }
                        else
                        {
                            ParcialChunks.Add(i);
                        }
                    }
                }
            }
            //Seleccionar la mejor parte posible
            int    num_chunk;
            Random rnd = new Random();

            while (true)
            {
                if (ActiveRareChunks.Count > 0)
                {
                    num_chunk = (int)ActiveRareChunks[rnd.Next(ActiveRareChunks.Count - 1)];
                    ActiveRareChunks.Remove(num_chunk);
                }
                else if (RareChunks.Count > 0)
                {
                    num_chunk = (int)RareChunks[rnd.Next(RareChunks.Count - 1)];
                    RareChunks.Remove(num_chunk);
                }
                else if (ParcialChunks.Count > 0)
                {
                    num_chunk = (int)ParcialChunks[rnd.Next(ParcialChunks.Count - 1)];
                    ParcialChunks.Remove(num_chunk);
                }
                else if (EmptyChunks.Count > 0)
                {
                    num_chunk = (int)EmptyChunks[rnd.Next(EmptyChunks.Count - 1)];
                    EmptyChunks.Remove(num_chunk);
                }
                else if (ActiveChunks.Count > 0)
                {
                    num_chunk = (int)ActiveChunks[rnd.Next(ActiveChunks.Count - 1)];
                    ActiveChunks.Remove(num_chunk);
                }
                else
                {
                    num_chunk = -1;
                    break;
                }
                if (m_Element.File.RemainingToAskInChunk(num_chunk))
                {
                    break;
                }
            }
            return(num_chunk);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Connection to server failed.
        /// </summary>
        /// <param name="reason">Reason</param>
        protected override void OnConnectionFail(byte reason)
        {
            if (m_Server != null)
            {
                m_Server.Connected = false;
                if (!m_Server.DisconectedByUser)
                {
                    switch ((Protocol.ConnectionReason)reason)
                    {
                    case Protocol.ConnectionReason.CannotConnect:
                        m_Server.IncFails((byte)Protocol.ConnectionReason.CannotConnect);
                        break;

                    case Protocol.ConnectionReason.ClosedConnection:
                        m_Server.IncFails((byte)Protocol.ConnectionReason.ClosedConnection);
                        break;

                    case Protocol.ConnectionReason.NullPacket:
                        m_Server.IncFails((byte)Protocol.ConnectionReason.NullPacket);
                        break;

                    case Protocol.ConnectionReason.NullID:
                        m_Server.IncFails((byte)Protocol.ConnectionReason.NullID);
                        break;

                    case Protocol.ConnectionReason.InvalidHeader:
                        m_Server.IncFails((byte)Protocol.ConnectionReason.InvalidHeader);
                        break;
                    }
                }
                else
                {
                    string strreason = "";
                    switch ((Protocol.ConnectionReason)reason)
                    {
                    case Protocol.ConnectionReason.CannotConnect:
                        strreason = CKernel.Globalization["SRV_DOWN"];
                        break;

                    case Protocol.ConnectionReason.ClosedConnection:
                        strreason = CKernel.Globalization["SRV_DISCONNECTED"];
                        break;

                    case Protocol.ConnectionReason.NullPacket:
                        strreason = CKernel.Globalization["SRV_FULL"];
                        break;

                    case Protocol.ConnectionReason.NullID:
                        strreason = CKernel.Globalization["SRV_FULL"];
                        break;

                    case Protocol.ConnectionReason.InvalidHeader:
                        strreason = CKernel.Globalization["SRV_FULL"];
                        break;
                    }
                    CLog.Log(Constants.Log.Info, "SRV_NOTCONNECT", m_Server.Name, strreason);
                }
                if (m_Server != null)
                {
                    m_Server.DisconectedByUser = false;                               //check !=null again, the server may be deleted
                }
            }
            CloseConnection();
            m_Server = null;
        }
Exemplo n.º 11
0
        /// <summary>
        /// Process incomming eDonkey packet.
        /// </summary>
        /// <param name="packet">Packet which need to be processed.</param>
        protected override void ProcessDonkeyPacket(ref byte[] packet)
        {
            if (m_Server == null)
            {
                return;
            }
            try
            {
                switch ((Protocol.ServerCommand)m_DonkeyHeader.Command)
                {
                case Protocol.ServerCommand.ServerMessage:
                    m_Server.SetMessage(packet);
                    break;

                case Protocol.ServerCommand.IDChange:
                    uint   m_ID;
                    string LowHigh_ID = "low ID";
                    bool   IsHighID   = false;

                    BinaryReader reader = new BinaryReader(new MemoryStream(packet));
                    m_ID = reader.ReadUInt32();

                    if (reader.PeekChar() > 0)
                    {
                        m_Server.TCPFlags = reader.ReadUInt32();
                        if (reader.PeekChar() > 0)
                        {
                            m_Server.MainPort = (ushort)reader.ReadUInt32();
                        }
                    }
                    else
                    {
                        m_Server.TCPFlags = 0;
                    }

                    if (m_ID > 0)
                    {
                        if (m_Server.ConnectionReady())
                        {
                            if (m_ID > Protocol.LowIDLimit)
                            {
                                LowHigh_ID = "high ID";
                                IsHighID   = true;
                                CKernel.ServersList.LowIDRetryHelper.GotHighID();
                            }
                            else
                            {
                                //Check if is advisable to decline the low id and retry
                                if (CKernel.ServersList.LowIDRetryHelper.ShouldRetry())
                                {
                                    CLog.Log(Constants.Log.Info, CKernel.Globalization["LOW_ID_RETRY"],
                                             m_Server.Description);
                                    CKernel.ServersList.ActiveServer = null;
                                    CloseConnection();
                                    //OnConnectionFail((byte)Protocol.ConnectionReason.ClosedConnection);
                                    break;
                                }
                            }

                            CLog.Log(Constants.Log.Notify, "SRV_NEW_ID", LowHigh_ID, m_ID);
                            CKernel.ServersList.ActiveServer.IsHighID = IsHighID;
                            CKernel.ServersList.ActiveServer.UserID   = m_ID;
                            CKernel.Preferences.SetProperty("ID", m_ID);
                        }
                    }
                    else
                    {
                        OnConnectionFail((byte)Protocol.ConnectionReason.NullID);
                    }
                    break;

                case Protocol.ServerCommand.SearchResult:
                    m_Server.ProcessSearchResults(packet);
                    break;

                case Protocol.ServerCommand.FoundSources:
                    Debug.WriteLine(DateTime.Now.ToLongTimeString() + " : Found TCP Sources");
                    m_Server.ProcessSources(new MemoryStream(packet));
                    break;

                case Protocol.ServerCommand.ServerState:
                    m_Server.UpdateState(packet);
                    break;

                case Protocol.ServerCommand.ServerIdent:
                    m_Server.ProcessDescription(packet);
                    break;

                case Protocol.ServerCommand.ServerList:
                    m_Server.ProcessServerList(packet);
                    break;

                case Protocol.ServerCommand.CallBackRequested:
                    m_Server.ProcessCallBackResponse(packet);
                    break;

                default:
                    break;
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                CLog.Log(Constants.Log.Verbose, "SRV_PAQ_TCP_ERROR", m_DonkeyHeader.Command);
            }
        }
Exemplo n.º 12
0
        private void m_ProcessUDPPacket(byte command, ref MemoryStream packet)
        {
            try
            {
                switch ((Protocol.ClientCommandExtUDP)command)
                {
                case Protocol.ClientCommandExtUDP.ReaskFilePing:
                    if (!m_PortIsAccesible)
                    {
                        CLog.Log(Types.Constants.Log.Info, "UDP_PORT_IS_OPEN");
                    }
                    m_PortIsAccesible = true;
                    MemoryStream responseBuffer;
//						if (packet.Length!=16) break;
//						byte[] FilaHash=new byte[16];
//						packet.Read(FilaHash,0,16);
                    CFileReaskUDP reaskMessage = new CFileReaskUDP(packet);
                    byte[]        FilaHash     = reaskMessage.FileHash;
                    //byte[] chunksAvaibility=reaskMessage.partes;
                    //TODO update chunksAvaibility in shared file

                    CElement requestedElement = CKernel.FilesList[FilaHash];
                    if (requestedElement == null)
                    {
                        responseBuffer = new MemoryStream(2);
                        CFileNotFoundUDP FicheroNoEncontradoUDP = new CFileNotFoundUDP(responseBuffer);
                    }
                    else
                    {
                        m_RemoteIPEndPoint = (IPEndPoint)m_RemoteEndPoint;
                        CClient foundClient   = null;
                        ushort  queuePosition = CKernel.Queue.RefreshClientUDP(BitConverter.ToUInt32(m_RemoteIPEndPoint.Address.GetAddressBytes(), 0), (ushort)m_RemoteIPEndPoint.Port, ref foundClient);
                        if (queuePosition <= 0)
                        {
                            responseBuffer = new MemoryStream(2);
                            CQueueFullUDP PaqueteColaLlenaUDP = new CQueueFullUDP(responseBuffer);
                        }
                        else
                        {
                            responseBuffer = new MemoryStream(4);
                            CQueuePositionUDP PaquetePosicionColaUDP = new CQueuePositionUDP(responseBuffer, queuePosition, requestedElement.File.ChunksStatus, foundClient.VersionUDP);
                        }
                    }
                    SendPacketUDP(responseBuffer.GetBuffer(), m_RemoteIPEndPoint);
                    break;

                case Protocol.ClientCommandExtUDP.ReaskAck:
                    m_RemoteIPEndPoint = (IPEndPoint)m_RemoteEndPoint;
                    CClient client = CKernel.ClientsList.GetClient(BitConverter.ToUInt32(m_RemoteIPEndPoint.Address.GetAddressBytes(), 0), 0, 0, null);
                    if (client != null)
                    {
                        ushort queuePosition;


                        if ((packet.Length > 2) && (client.VersionUDP > 3))
                        {
                            packet.Seek(0, SeekOrigin.Begin);
                            client.ProcessChunksStatus(packet, true);
                        }
                        BinaryReader reader = new BinaryReader(packet);
                        queuePosition = reader.ReadUInt16();
                        client.ProcessUDPReask(queuePosition);
                        packet.Close();
                        packet = null;
                    }
                    break;

                case Protocol.ClientCommandExtUDP.QueueFull:
                    client = CKernel.ClientsList.GetClient(BitConverter.ToUInt32(m_RemoteIPEndPoint.Address.GetAddressBytes(), 0), 0, 0, null);
                    if (client != null)
                    {
                        client.ProcessUDPReask(0);
                    }
                    break;

                case Protocol.ClientCommandExtUDP.FileNotFound:
                    client = CKernel.ClientsList.GetClient(BitConverter.ToUInt32(m_RemoteIPEndPoint.Address.GetAddressBytes(), 0), 0, 0, null);
                    if ((client != null) && (client.DownloadElement != null) && (client.DownloadElement.SourcesList != null))
                    {
                        client.DownloadElement.SourcesList.RemoveSource(client);
                    }
                    break;

                default:
                    CLog.Log(Constants.Log.Verbose, "CLI_UNK_UDP_PACKET", command);
                    break;
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                CLog.Log(Constants.Log.Verbose, "CLI_PAQ_UDP_ERROR", command);
            }
        }
Exemplo n.º 13
0
        private bool m_LoadKnownFiles(string filefullpath, bool showErrorMessage)
        {
            FileStream   knownmet = null;
            BinaryReader reader   = null;

            if (filefullpath.Length == 0)
            {
                filefullpath = Path.Combine(CKernel.DllDirectory, "known.met");
            }
            try
            {
                knownmet = File.OpenRead(filefullpath);

                reader = new BinaryReader(knownmet);

                if (!Enum.IsDefined(typeof(Protocol.KnownMet), reader.ReadByte()))
                //	if (reader.ReadByte() != 0x0E)
                {
                    reader.Close();
                    knownmet.Close();
                    CLog.Log(Constants.Log.Notify, "KNWMET_INVALID");
                    return(false);
                }
                int nFiles = reader.ReadInt32();
                m_KnownMetList = new Hashtable(nFiles);
                for (uint i = 0; i != nFiles; i++)
                {
                    CKnownFileAttributes attributesKnownFile = new CKnownFileAttributes();
                    attributesKnownFile.Date     = new DateTime(((long)reader.ReadUInt32() * 10000000L) + 621355968000000000L);
                    attributesKnownFile.FileHash = reader.ReadBytes(16);
                    ushort nChunks = reader.ReadUInt16();
                    attributesKnownFile.HashSet = new ArrayList(nChunks);
                    for (uint chunk = 0; chunk != nChunks; chunk++)
                    {
                        attributesKnownFile.HashSet.Add(reader.ReadBytes(16));
                    }
                    CParameterReader ParameterReader;
                    uint             nparameters = reader.ReadUInt32();
                    for (uint parameter = 0; parameter != nparameters; parameter++)
                    {
                        ParameterReader = new CParameterReader(reader);
                        switch ((Protocol.FileTag)ParameterReader.id)
                        {
                        case Protocol.FileTag.Name:
                            attributesKnownFile.FileName = ParameterReader.valorString;
                            break;

                        case Protocol.FileTag.Size:
                            attributesKnownFile.Size = ParameterReader.valorNum;
                            break;

                        case Protocol.FileTag.Priority:
                            attributesKnownFile.Priority = (Constants.Priority)ParameterReader.valorNum;
                            break;

                        case Protocol.FileTag.Permissions:
                            attributesKnownFile.Permisions = (byte)ParameterReader.valorNum;
                            break;

                        case Protocol.FileTag.Comment:
                            attributesKnownFile.Comment = ParameterReader.valorString;
                            break;

                        case Protocol.FileTag.Rating:
                            attributesKnownFile.Rating = (byte)ParameterReader.valorNum;
                            break;

                        default:
                            break;
                            //faltan los parametros para las estadisticas....
                        }
                    }

                    if (!m_KnownMetList.ContainsKey(attributesKnownFile.FileName + (attributesKnownFile.Date.Ticks / 10000000L).ToString()))
                    {
                        m_KnownMetList.Add(attributesKnownFile.FileName + (attributesKnownFile.Date.Ticks / 10000000L).ToString(), attributesKnownFile);
                    }
                }

                reader.Close();
                knownmet.Close();
                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                if (showErrorMessage)
                {
                    CLog.Log(Constants.Log.Notify, "Can not load known.met, hashing shared files");
                }
                try
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                    if (knownmet != null)
                    {
                        knownmet.Close();
                    }
                }
                catch {};
                return(false);
            }
        }