Exemple #1
0
        public void ResumeFile(string strFileHash)
        {
            CElement Elemento = (CElement)this[CKernel.StringToHash(strFileHash)];

            if ((Elemento != null) && (Elemento.SourcesList == null) && ((Elemento.File.FileStatus == Protocol.FileState.Stopped) || (Elemento.File.FileStatus == Protocol.FileState.Pause)))
            {
                Elemento.SourcesList     = new CSourcesList(Elemento);
                Elemento.File.FileStatus = Protocol.FileState.Ready;
                if (Elemento.Comments == null)
                {
                    Elemento.Comments = new CedonkeyComments(Elemento);
                }
                Elemento.Statistics.ResetStartTime();
                lock (CKernel.Queue.List.SyncRoot)
                {
                    foreach (CClient Client in CKernel.Queue.List)
                    {
                        if (Client.UploadElement == Elemento)
                        {
                            CKernel.ClientsList.AddClientToFile(Client, Elemento.File.FileHash);
                        }
                    }
                    if (CKernel.ServersList.ActiveServer != null)
                    {
                        CKernel.ServersList.ActiveServer.RequestSources(Elemento.File.FileHash);
                    }
                }
            }
        }
Exemple #2
0
        public void DeleteFile(string strFileHash)
        {
            CElement Element = (CElement)this[CKernel.StringToHash(strFileHash)];

            if ((Element != null) && (Element.File.FileStatus == Protocol.FileState.Complete))
            {
                if (Element.SourcesList != null)
                {
                    m_StopFile(Element);
                }
                if (Element.Comments != null)
                {
                    Element.Comments.Element = null;
                }
                Element.Comments = null;

                try
                {
                    File.Delete(Element.File.CompleteName);
                }
                catch {}

                Element.File = null;
                m_FileList.Remove(Element);
                Element = null;
            }
        }
Exemple #3
0
 public CElement this[byte[] key]
 {
     get
     {
         try
         {
             CElement result = null;
             lock (m_FileList.SyncRoot)
             {
                 foreach (CElement element in m_FileList)
                 {
                     if (CKernel.SameHash(ref key, ref element.File.FileHash))
                     {
                         result = element;
                         break;
                     }
                 }
             }
             return(result);
         }
         catch
         {
             return(null);
         }
     }
 }
Exemple #4
0
 private void AddFile(CFile file)
 {
     if (!m_Contains(file.FileHash))
     {
         CElement Element = new CElement();
         Element.File       = file;
         Element.Statistics = new CFileStatistics();
         m_FileList.Add(Element);
         if (((file.FileStatus == Protocol.FileState.Ready) || (Element.File.FileStatus == Protocol.FileState.Completing)) && (!file.Completed))
         {
             Element.SourcesList = new CSourcesList(Element);
             Element.Comments    = new CedonkeyComments(Element);
         }
         if (!file.Completed)
         {
             CKernel.NewFile(Element);
         }
         else
         {
             CKernel.NewSharedFile(Element);
         }
     }
     else
     {
         CLog.Log(Constants.Log.Notify, "FIL_DUP", CKernel.HashToString(file.FileHash));
         file = null;
     }
 }
Exemple #5
0
        public void AddFile(string name, uint size, byte[] Hash, stDatosFuente[] sources)
        {
            CElement Element;

            if (this.m_Contains(Hash))
            {
                CLog.Log(Constants.Log.Notify, "FIL_DUP", name);
                Element = (CElement)this[Hash];
            }
            else
            {
                CFile file = new CFile(Hash, name, size);
                Element            = new CElement();
                Element.File       = file;
                Element.Statistics = new CFileStatistics();
                m_FileList.Add(Element);
                CKernel.NewFile(Element);
                CLog.Log(Constants.Log.Notify, "FIL_ADDED", name);
            }
            if ((Element.SourcesList == null) && ((Element.File.FileStatus == Protocol.FileState.Ready) || (Element.File.FileStatus == Protocol.FileState.Completing)))
            {
                CSourcesList sourcesList = new CSourcesList(Element);
                Element.SourcesList = sourcesList;
                if (CKernel.ServersList.ActiveServer != null)
                {
                    CKernel.ServersList.ActiveServer.RequestSources(Element.File.FileHash);
                }
            }
            if ((Element.SourcesList != null) &&
                ((Element.File.FileStatus == Protocol.FileState.Ready) || (Element.File.FileStatus == Protocol.FileState.Completing)) &&
                (sources != null))
            {
                CKernel.ClientsList.AddClientsToFile(sources, Hash);
            }
        }
Exemple #6
0
        public void RemoveSharedFileIfNotExists(byte[] fileHash)
        {
            CElement Element = this[fileHash];

            if ((Element != null) && (Element.File != null) && (Element.File.Completed) && (!File.Exists(Element.File.CompleteName)))
            {
                m_FileList.Remove(Element);

                ArrayList toRemove = null;
                foreach (CClient Client in CKernel.Queue.List)
                {
                    if (Client.UploadElement == Element)
                    {
                        if (toRemove == null)
                        {
                            toRemove = new ArrayList();
                        }
                        toRemove.Add(Client);
                    }
                }
                if (toRemove != null)
                {
                    foreach (CClient Client in toRemove)
                    {
                        CKernel.Queue.List.Remove(Client);
                        //Debug.WriteLine(Client.UserName+" cleaned from queue due to deleted file");
                        CKernel.ClientsList.IsClientNeeded(Client);
                    }
                }
            }
        }
Exemple #7
0
 private bool m_AddFileToPacket(BinaryWriter writer, CElement element)
 {
     try
     {
         if (!element.File.Empty)
         {
             writer.Write(element.File.FileHash);
             if (element.File.Completed)
             {
                 writer.Write((uint)0xfbfbfbfb);
                 writer.Write((ushort)0xfbfb);
             }
             else
             {
                 writer.Write((uint)0xfcfcfcfc);
                 writer.Write((ushort)0xfcfc);
             }
             uint nParameters = 2;
             if (element.File.Details.ListDetails.ContainsKey(Constants.Avi.Length))
             {
                 nParameters++;
             }
             if (element.File.Details.ListDetails.ContainsKey(Constants.Avi.VBitrate))
             {
                 nParameters++;
             }
             if (element.File.Details.ListDetails.ContainsKey(Constants.Avi.VCodec))
             {
                 nParameters++;
             }
             writer.Write(nParameters);
             // name
             new ParameterWriter((byte)Protocol.FileTag.Name, element.File.FileName, writer);
             // size
             new ParameterWriter((byte)Protocol.FileTag.Size, element.File.FileSize, writer);
             if (element.File.Details.Type == (byte)Constants.FileType.Avi)
             {
                 if (element.File.Details.ListDetails.ContainsKey(Constants.Avi.Length))
                 {
                     new ParameterWriter(Protocol.FileExtraTags.length.ToString(), (string)element.File.Details.ListDetails[Constants.Avi.Length], writer);
                 }
                 if (element.File.Details.ListDetails.ContainsKey(Constants.Avi.VBitrate))
                 {
                     new ParameterWriter(Protocol.FileExtraTags.bitrate.ToString(), Convert.ToUInt32(((string)element.File.Details.ListDetails[Constants.Avi.VBitrate]).Replace(" Kbps", "")), writer);
                 }
                 if (element.File.Details.ListDetails.ContainsKey(Constants.Avi.VCodec))
                 {
                     new ParameterWriter(Protocol.FileExtraTags.codec.ToString(), (string)element.File.Details.ListDetails[Constants.Avi.VCodec], writer);
                 }
             }
             return(true);
         }
     }
     catch (Exception e)
     {
         Debug.WriteLine(e.ToString());
     }
     return(false);
 }
Exemple #8
0
 private void m_StopFile(CElement Element)
 {
     if ((Element != null) && (Element.SourcesList != null))
     {
         Element.SourcesList.Clean();
         Element.SourcesList = null;
     }
 }
Exemple #9
0
 public void Clean()
 {
     m_Element = null;
     while (m_ArrayList.Count > 0)
     {
         CClient Client = (CClient)m_ArrayList[0];
         RemoveSource(Client);
     }
 }
Exemple #10
0
        public void AddSource(byte[] FileHash, ref CClient client)
        {
            CElement Element = (CElement)this[FileHash];

            if ((Element != null) && (Element != null) && (!Element.File.Completed))
            {
                Element.SourcesList.AddSource(client);
            }
        }
Exemple #11
0
        public void StopFile(byte[] FileHash)
        {
            CElement Element = (CElement)this[FileHash];

            if ((Element != null) && (Element.File.FileStatus == Protocol.FileState.Ready))
            {
                m_StopFile(Element);
                Element.File.FileStatus = Protocol.FileState.Stopped;
            }
        }
Exemple #12
0
        public void SetDownloadPriority(string strFileHash, Constants.Priority priority)
        {
            CElement ChangedElement = (CElement)this[CKernel.StringToHash(strFileHash)];

            if ((ChangedElement == null) || (ChangedElement.File.DownPriority == priority) || (ChangedElement.File.FileStatus == Protocol.FileState.Complete))
            {
                return;
            }
            ChangedElement.File.DownPriority = (Constants.Priority)priority;
            CKernel.ClientsList.SwapClientsToHigherPriorityFile();
        }
Exemple #13
0
        public CSourcesList(CElement in_Element)
        {
            m_ArrayList=ArrayList.Synchronized(new ArrayList());
            m_Element=in_Element;
            m_Avaibility=null;
            Random rnd=new Random();
            m_LastTCPSearch=DateTime.MinValue; //-TimeSpan.FromSeconds(rnd.Next(60));
            m_LastSourceExchangeRequest=DateTime.MinValue;

            m_DownloadSpeed=0;
        }
Exemple #14
0
        public CSourcesList(CElement in_Element)
        {
            m_ArrayList  = ArrayList.Synchronized(new ArrayList());
            m_Element    = in_Element;
            m_Avaibility = null;
            Random rnd = new Random();

            m_LastTCPSearch             = DateTime.MinValue; //-TimeSpan.FromSeconds(rnd.Next(60));
            m_LastSourceExchangeRequest = DateTime.MinValue;

            m_DownloadSpeed = 0;
        }
Exemple #15
0
        internal static void RemovedSharedFile(CElement element)
        {
            InterfaceFile file = InterfaceGateway[0].FileToInterfaceFile(element);

            for (int i = 0; i <= InterfaceGateway.Length - 1; i++)
            {
                if (CKernel.InterfaceGateway[i] != null)
                {
                    InterfaceGateway[i].RemovedSharedFile(file);
                }
            }
        }
Exemple #16
0
        public void EmptyFileToSharedFile(CFile file)
        {
            CElement Element = this[file.FileHash];

            if (Element != null)
            {
                CKernel.NewSharedFile(Element);
            }
            //TODO publish the file on the conected server
            if (CKernel.ServersList.ActiveServer != null)
            {
                CKernel.ServersList.ActiveServer.PublishSharedFile(Element);
            }
        }
Exemple #17
0
        //constructor to publish one file
        public CServerPublishFiles(MemoryStream buffer, CElement element)
        {
            DonkeyHeader header;
            BinaryWriter writer = new BinaryWriter(buffer);

            header = new DonkeyHeader((byte)Protocol.ServerCommand.OfferFiles, writer);
            writer.Write(1);
            m_AddFileToPacket(writer, element);
            header.Packetlength = (uint)writer.BaseStream.Length - header.Packetlength + 1;
            writer.Seek(0, SeekOrigin.Begin);
            header.Serialize(writer);
            writer.Write(1);
            CLog.Log(Types.Constants.Log.Info, "FIL_PUBLISHED", 1);
        }
Exemple #18
0
        /// <summary>
        /// Publish one new shared file (only one)
        /// </summary>
        public void PublishSharedFile(CElement Element)
        {
            MemoryStream        buffer             = new MemoryStream();
            CServerPublishFiles ServerPublishFiles = new CServerPublishFiles(buffer, Element);

            //if server supports compression we send it compressed
            if (SupportCompression)
            {
                CCompressedPacket CompressedPacket = new CCompressedPacket(ref buffer);
            }
            if (m_ServerConnection != null)
            {
                m_ServerConnection.SendPacket(buffer);
            }
        }
Exemple #19
0
        private bool m_LoadFilesFromFolder(string folder /*,bool refreshing*/)
        {
            if (!Directory.Exists(folder))
            {
                return(false);
            }
            string [] ficheros = Directory.GetFiles(folder);
            DateTime  date;
            string    name;

            if (m_EdonkeyHash == null)
            {
                m_EdonkeyHash = new CHash();
            }
            foreach (string file in ficheros)
            {
                // 0 Kb file are ignored, avoid a crash
                FileInfo filInfo = new FileInfo(file);
                if ((filInfo.Length == 0) ||
                    ((filInfo.Attributes & (FileAttributes.Hidden | FileAttributes.System)) != 0))
                {
                    continue;
                }

                date = File.GetLastWriteTime(file).ToUniversalTime();
                name = Path.GetFileName(file);
                CKnownFileAttributes Atributos;
                if ((Atributos = m_IsKnown(name, date)) != null)
                {
                    //if (refreshing) continue;
                    if (!m_Contains(Atributos.FileHash))
                    {
                        CElement Element = new CElement();
                        Element.File        = new CFile(Atributos.FileHash, Atributos.Date, folder, name, Atributos.Size, Atributos.Priority, Atributos.Permisions, Atributos.HashSet, Atributos.Comment, Atributos.Rating);
                        Element.SourcesList = null;
                        Element.Statistics  = new CFileStatistics();
                        this.m_FileList.Add(Element);
                        CKernel.NewSharedFile(Element);
                    }
                    //if (!m_Contains(Atributos.FileHash))this.m_FileList.Add(Element);
                }
                else                 //new file
                {
                    m_EdonkeyHash.AddFile(file);
                }
            }
            return(true);
        }
Exemple #20
0
        public void CompleteFile(string strFileHash)
        {
            CElement Element = (CElement)this[CKernel.StringToHash(strFileHash)];

            if (Element != null)
            {
                m_StopFile(Element);
                Element.File.FileStatus = Protocol.FileState.Complete;
                Element.File.UpPriority = Constants.Priority.Normal;
                CLog.Log(Constants.Log.Notify, "FIL_COMPLETED", Element.File.FileName);
                Element.Statistics.TimeCompleted = DateTime.Now;
                if (CKernel.Preferences.GetBool("StartNextStoppedFile"))
                {
                    m_StartNextPausedFile(Element.File.CategoryID);
                }
            }
        }
Exemple #21
0
        public void SetFileCategory(string strFileHash, string category)
        {
            CElement Element = (CElement)this[CKernel.StringToHash(strFileHash)];

            if (Element != null)
            {
                CCategory cat = CKernel.CategoriesList.GetCategoryByName(category);
                if (cat != null)
                {
                    Element.File.CategoryID = cat.ID;
                }
                else
                {
                    Element.File.CategoryID = 0;
                }
            }
        }
Exemple #22
0
        public void CancelFile(string strFileHash)
        {
            CElement Element = (CElement)this[CKernel.StringToHash(strFileHash)];

            if ((Element != null) && (Element.File.FileStatus != Protocol.FileState.Complete))
            {
                Element.File.FileStatus = Protocol.FileState.Stopped;
                if (Element.SourcesList != null)
                {
                    m_StopFile(Element);
                }
                if (Element.Comments != null)
                {
                    Element.Comments.Element = null;
                }
                Element.Comments = null;
                Element.File.CancelFile();
                Element.File = null;
                m_FileList.Remove(Element);
                Element = null;
            }
        }
Exemple #23
0
        public void AddSourcesToFile()
        {
            if ((Sources == null) || (Sources.Count == 0))
            {
                return;
            }
            CElement element = CKernel.FilesList[CKernel.StringToHash(this.Hash)];
            int      i;

            if ((element != null) && (element.File.FileStatus == Protocol.FileState.Ready))
            {
                stDatosFuente[] sourcesList = new stDatosFuente[Sources.Count];
                i = 0;
                foreach (uint ip in Sources.Keys)
                {
                    sourcesList[i].IP   = ip;
                    sourcesList[i].Port = (ushort)Sources[ip];
                    i++;
                }
                CKernel.ClientsList.AddClientsToFile(sourcesList, CKernel.StringToHash(this.Hash));
            }
        }
Exemple #24
0
 public void UpdateFile(uint in_Avaibility, string in_Name, string in_codec, string in_length, uint in_bitrate, bool in_complete, uint in_ip, ushort in_port)
 {
     this.Avaibility += in_Avaibility;
     Complete         = Complete || in_complete;
     if (!this.OtherNames.Contains(in_Name))
     {
         this.OtherNames.Add(in_Name);
     }
     if (((Length == null) || (Length.Length == 0)) && (in_length.Length > 0))
     {
         Length = in_length;
     }
     if ((Codec.Length == 0) && (in_codec.Length > 0))
     {
         Codec = in_codec;
     }
     if ((BitRate == 0) && (in_bitrate > 0))
     {
         BitRate = in_bitrate;
     }
     if ((in_ip > Protocol.LowIDLimit) && (in_port > 0) && (in_port < ushort.MaxValue))
     {
         if (Sources == null)
         {
             Sources = new Hashtable();
         }
         if (!Sources.Contains(in_ip))
         {
             Sources.Add(in_ip, in_port);
         }
         //Debug.WriteLine(in_ip.ToString()+":"+in_port.ToString());
         CElement element = CKernel.FilesList[CKernel.StringToHash(Hash)];
         if ((element != null) && (element.File.FileStatus == Protocol.FileState.Ready))
         {
             CKernel.ClientsList.AddClientToFile(in_ip, in_port, 0, 0, element.File.FileHash);
         }
     }
 }
Exemple #25
0
        private void m_StartNextPausedFile(uint category)
        {
            CElement elementCandidate = null;

            lock (m_FileList.SyncRoot)
            {
                foreach (CElement element in m_FileList)
                {
                    if ((element.File.FileStatus == Protocol.FileState.Stopped) ||
                        (element.File.FileStatus == Protocol.FileState.Pause))
                    {
                        if (elementCandidate == null)                       //no one selected, select first
                        {
                            elementCandidate = element;
                        }
                        else if (element.File.CategoryID == category)                       //same category
                        {
                            if (elementCandidate.File.CategoryID != category)               //selected from other category
                            {
                                elementCandidate = element;
                            }
                            else if (elementCandidate.File.DownPriority < element.File.DownPriority)                           //selected from same category lower priority
                            {
                                elementCandidate = element;
                            }
                        }
                        else if ((elementCandidate.File.CategoryID != category) && (elementCandidate.File.DownPriority < element.File.DownPriority))
                        {
                            elementCandidate = element;
                        }
                    }
                }
            }
            if (elementCandidate != null)
            {
                this.ResumeFile(CKernel.HashToString(elementCandidate.File.FileHash));
            }
        }
Exemple #26
0
 public void CloseDownloads(string strFileHash, bool stop)
 {
     if (strFileHash.Length == 0)           //stop all downloads
     {
         foreach (CElement Elemento in this.Values)
         {
             if (Elemento.SourcesList != null)
             {
                 Elemento.SourcesList.Clean();
             }
             Elemento.SourcesList = null;
         }
         if (stop)
         {
             m_FileListThread.Abort();
         }
     }
     else              //stop specified download
     {
         CElement Elemento = (CElement)this[CKernel.StringToHash(strFileHash)];
         m_StopFile(Elemento);
     }
 }
Exemple #27
0
        public CFileFound(string in_Hash, string in_Name, uint in_Size, uint in_Avaibility, string in_codec, string in_length, uint in_bitrate, bool in_complete, uint in_ip, ushort in_port)
        {
            this.Hash       = in_Hash;
            this.Name       = in_Name;
            this.Size       = in_Size;
            this.Avaibility = in_Avaibility;
            Codec           = in_codec;
            BitRate         = in_bitrate;
            Length          = in_length;
            Complete        = in_complete;
            this.OtherNames = new StringCollection();
            this.OtherNames.Add(Name);
            CElement element = CKernel.FilesList[CKernel.StringToHash(in_Hash)];

            if (element == null)
            {
                ResultState = Types.Constants.SearchResultState.New;
            }
            else if (element.File.FileStatus == Protocol.FileState.Complete)
            {
                ResultState = Types.Constants.SearchResultState.AlreadyDownloaded;
            }
            else
            {
                ResultState = Types.Constants.SearchResultState.AlreadyDownloading;
            }
            if ((in_ip > Protocol.LowIDLimit) && (in_port > 0) && (in_port < ushort.MaxValue))
            {
                Sources = new Hashtable();
                Sources.Add(in_ip, in_port);
                //Debug.WriteLine(in_ip.ToString()+":"+in_port.ToString());
                if ((element != null) && (element.File.FileStatus == Protocol.FileState.Ready))
                {
                    CKernel.ClientsList.AddClientToFile(in_ip, in_port, 0, 0, element.File.FileHash);
                }
            }
        }
Exemple #28
0
        public void SwapToOtherFile()
        {
            if ((m_OtherDownFiles==null)||(m_OtherDownFiles.Count==0))
            {
                return;
            }

            byte highestPriority=0;
            CElement tmpElement=null;
            CElement Element=null;
            int i=0;
            do
            {
                tmpElement=(CElement)CKernel.FilesList[CKernel.StringToHash(m_OtherDownFiles[i])];

                if ((tmpElement!=null)
                    &&(tmpElement.SourcesList!=null)
                    &&(!tmpElement.File.Completed)
                    &&(tmpElement.File.FileStatus==Protocol.FileState.Ready))
                {
                    if((byte)tmpElement.File.DownPriority>=highestPriority)
                    {
                        Element=tmpElement;
                        highestPriority=(byte)tmpElement.File.DownPriority;
                    }
                    i++;
                }
                else
                {
                    m_OtherDownFiles.RemoveAt(i);
                }
            }
            while ((i<m_OtherDownFiles.Count)&&(m_OtherDownFiles.Count>0));

            // element selected to download
            if (Element!=null)
            {
                m_OtherDownFiles.Remove(CKernel.HashToString(Element.File.FileHash));
                DownFileHash=new byte[16];
                Buffer.BlockCopy(Element.File.FileHash,0,DownFileHash,0,16);
                m_DownloadElement=Element;
                m_ClientFileName="";
                m_DownloadElement.SourcesList.AddSource(this);
                if ((connection!=null)&&connection.Connected)
                {
                    m_DownloadState=Protocol.DownloadState.Connected;
                    TryDownload();
                }
                else
                {
                    m_DownloadState=Protocol.DownloadState.None;
                }
            }
        }
Exemple #29
0
        public void SwapToHigherPriorityFile()
        {
            if ((m_OtherDownFiles==null)||
                (m_OtherDownFiles.Count==0)||
                (DownFileHash==null)||
                (m_DownloadState!=Protocol.DownloadState.OnQueue)&&(m_DownloadState!=Protocol.DownloadState.None))
            {
                return;
            }

            if (m_DownloadElement==null) m_DownloadElement=CKernel.FilesList[DownFileHash];
            if (m_DownloadElement==null) return;

            bool swapNeeded=false;
            foreach (string strFileHash in m_OtherDownFiles)
            {
                CElement newElement=CKernel.FilesList[CKernel.StringToHash(strFileHash)];
                if ((newElement!=null)&&
                    ((byte)m_DownloadElement.File.DownPriority<(byte)newElement.File.DownPriority))
                {
                    swapNeeded=true;
                    break;
                }
            }
            if (!swapNeeded) return;
            //Debug.Write("Swapping "+this.UserName+m_DownloadElement.File.FileName);
            string previousDownloadHash=CKernel.HashToString(DownFileHash);
            m_DownloadElement.SourcesList.RemoveSource(this); //this will swap the source to the highest priority alternative file
            //add the previous file to the alternative files
            m_OtherDownFiles.Add(previousDownloadHash);
            //Debug.WriteLine(" to "+ m_DownloadElement.File.FileName);
        }
Exemple #30
0
        public void RequestBlocks()
        {
            #if VERBOSE
            CKernel.LogClient.AddLog("RequestBlocks,download blocks.count:"+Convert.ToString(m_DownloadBlocks.Count),m_ID);
            #endif
            if (m_DownloadElement==null)
            {
                if (DownFileHash!=null)
                {
                    m_DownloadElement=(CElement)CKernel.FilesList[DownFileHash];

                    if ((m_DownloadElement!=null)&&(m_DownloadElement.SourcesList!=null))
                    {
                        m_DownloadElement.SourcesList.AddSource(this);
                    }
                    else
                    {
                        // probablemente el fichero ya se ha completado
                        return;
                    }
                }
                else
                {
                    return;
                }
            }
            m_DownloadState=Protocol.DownloadState.Downloading;

            //CElement Element=(CElement)CKernel.FilesList[CKernel.HashToString(DownFileHash)];
            uint start=0;
            uint end=0;
            int chunk=0;
            CFileBlock[] blocks=new CFileBlock[3];

            for (uint i=0;i!=3;i++)
            {
                blocks[i]=new CFileBlock();
                //Debug.Write("LastChunk:"+m_LastChunkRequested.ToString());
                chunk=m_DownloadElement.SourcesList.SelectChunk(m_DownFileChunks,m_LastChunkRequested);
                m_LastChunkRequested=chunk;
                //Debug.WriteLine("NewChunk:"+m_LastChunkRequested.ToString());
                if (chunk>=0)
                {
                    if (m_DownloadElement.File.GetNewBlockInChunk((uint)chunk,ref start,ref end))
                    {
                        blocks[i].start=start;
                        blocks[i].end=end;
                        blocks[i].FileHash=DownFileHash;
                        blocks[i].position=start;
                        //blocks[i].buffer=new Byte[fin+1-inicio];
                        m_DownloadBlocks.Add(blocks[i]);

                        if ((end==0)&&(start==0))
                        {
                            Debug.WriteLine("no more blocks to request "+Convert.ToString(chunk));
                        }
                        else
                        {
                            //Debug.WriteLine(m_UserName+", ChunksStatus = "+Convert.ToString(m_DownloadElement.File.ChunksStatus[0])/*+Convert.ToString(m_DownloadElement.File.GetChunksStatus()[1])*/);
            #if VERBOSE
                            CKernel.LogClient.AddLog("RequestBlocks-chunk requested "+Convert.ToString(chunk)+" block: "+Convert.ToString(start)+"-"+Convert.ToString(end)+"\n",m_ID);
            #endif
                        }
                    }
                }
            }

            if ((blocks[0].start==0)&&(blocks[0].end==0))
            {
            #if VERBOSE
                CKernel.LogClient.AddLog("RequestBlocks-first block is null,no request blocks",m_ID);
            #endif
            #if DEBUG
                Debug.WriteLine(m_UserName+" Parte: "+Convert.ToString(chunk)+" first block is null,no request blocks");

                for (int j=0;j<m_DownloadElement.File.ChunksStatus.Length;j++)
                {
                    if (((m_DownloadElement.File.ChunksStatus[j]==(byte)Protocol.ChunkState.Empty)||
                        (m_DownloadElement.File.ChunksStatus[j]==(byte)Protocol.ChunkState.InProgress))&&
                        (m_DownFileChunks[j]==(byte)Protocol.ChunkState.Complete))
                    Debug.WriteLine("Chunk not selected when available");
                }
            #endif
                if (m_DownloadBlocks.Count==0)
                {
                    //no needed new blocks to download and nothing pending for receiving
                    bool willBeChangedToOtherFile=((m_OtherDownFiles!=null)&&(m_OtherDownFiles.Count>0));
                    CancelDownloadTransfer(false);
                    if (!willBeChangedToOtherFile)
                    {
                        m_DownloadState=Protocol.DownloadState.NoNeededParts;
                    }
                }
            }
            else
            {
                MemoryStream packet=new MemoryStream();
                CFileBlockRequest fileBlockRequest=new CFileBlockRequest(packet,DownFileHash,ref blocks[0],ref blocks[1],ref blocks[2]);

                if (connection!=null)
                {
                    connection.SendPacket(packet);
                }
            }
        }
Exemple #31
0
        public void RemoveDownload()
        {
            #if VERBOSE
            CKernel.LogClient.AddLog("RemoveDownload",m_ID);
            #endif

            if (m_DownloadState==Protocol.DownloadState.Downloading)
            {
                CancelDownloadTransfer(true);
            }
            CKernel.SourcesOld.AddClient(this);
            //			DownFileHash=null;
            //			m_DownFileChunks=null;
            m_DownloadElement=null;
            m_DownloadState=Protocol.DownloadState.None;
        }
Exemple #32
0
 public CedonkeyComments(CElement in_Element)
 {
     Element = in_Element;
 }
Exemple #33
0
        public void ProcessChunksStatus(MemoryStream packet, bool udpConnection)
        {
            #if VERBOSE
            CKernel.LogClient.AddLog("ProcessChunksStatus",m_ID);
            #endif
            if ((DownFileHash==null)||(m_DownloadElement==null)) return;

            CFileStatus fileStatus=new CFileStatus(packet,!udpConnection);

            if ((!udpConnection)&&(!CKernel.SameHash(ref DownFileHash,ref fileStatus.FileHash)))
            {
                Exception e=new Exception("Chunks status: invalid fileHash");
                throw(e);
            }

            if (!CKernel.SameHash(ref DownFileHash,ref m_DownloadElement.File.FileHash))
            {
                m_DownloadElement=CKernel.FilesList[DownFileHash];
            }

            if ((CHash.GetChunksCount(m_DownloadElement.File.FileSize)!=fileStatus.nChunks)
                && (fileStatus.nChunks!=0))
            {
                m_DownFileChunks=null;
                Exception e=new Exception("Received chunks numer does not match with file chunks number\n");
                throw(e);
            }
            if (m_DownloadElement.SourcesList!=null) m_DownloadElement.SourcesList.RemoveChunksAvaibility(m_DownFileChunks);
            uint nChunks=CHash.GetChunksCount(m_DownloadElement.File.FileSize);
            if (fileStatus.Chunks==null)
            {
                if ((m_DownFileChunks==null)||(m_DownFileChunks.Length!=nChunks))
                {
                    m_DownFileChunks=new byte[nChunks];
                }

                for(int i=0; i!=m_DownFileChunks.Length; i++)
                {
                    m_DownFileChunks[i]=(byte)Protocol.ChunkState.Complete;
                }
                //TODO hay alguna función para hacer esto en .NET equivalente a memset?
            }
            else
            {
                if ((m_DownFileChunks==null)||(m_DownFileChunks.Length!=nChunks))
                {
                    m_DownFileChunks=new byte[nChunks];
                }
                Buffer.BlockCopy(fileStatus.Chunks,0,m_DownFileChunks,0,fileStatus.Chunks.Length);
            }

            if (fileStatus.nChunks>0)
            {
                m_DownloadState=Protocol.DownloadState.NoNeededParts;

                for (int i=0; i!=m_DownFileChunks.Length; i++)
                {
                    if (((Protocol.ChunkState)m_DownFileChunks[i]==Protocol.ChunkState.Complete)
                        &&((m_DownloadElement.File.ChunksStatus.Length==0)
                        ||((Protocol.ChunkState)m_DownloadElement.File.ChunksStatus[i]!=Protocol.ChunkState.Complete)))
                    {
                        m_DownloadState=Protocol.DownloadState.OnQueue;
                        break;
                    }
                }
            }
            else
            {
                m_DownloadState=Protocol.DownloadState.OnQueue;
            }

            //m_DownloadElement.SourcesList.UpdateChunksAvaibility();
            if (m_DownloadElement.SourcesList!=null) m_DownloadElement.SourcesList.AddChunksAvaibility(m_DownFileChunks);

            if (udpConnection) return;

            packet.Close();
            packet=null;
            // ver si necesitamos el hashset del fichero(si no lo tenemos aun lo pedimos)
            // CElement Element=(CElement)CKernel.FilesList[CKernel.HashToString(DownFileHash)];
            // TODO no es necesario pedir hashSets de ficheros de una única parte
            if ((m_DownloadElement.File.HashSetNeeded())&&(m_DownloadState!=Protocol.DownloadState.NoNeededParts))
            {
            #if VERBOSE
                CKernel.LogClient.AddLog("ProcesarInformacionPartesFichero-Pide HashSet",m_ID);
            #endif
                m_DownloadState=Protocol.DownloadState.ReqestHashSet;

                MemoryStream responsePacket=new MemoryStream();
                CHashSetRequest hashSet=new CHashSetRequest(DownFileHash,responsePacket);

                if (connection!=null)
                {
                    connection.SendPacket(responsePacket);
                }
            }
            else
            {
                if (m_DownloadState!=Protocol.DownloadState.NoNeededParts)
                {
            #if VERBOSE
                    CKernel.LogClient.AddLog("ProcesarInformacionPartesFichero-Envía IniciarDescarga",m_ID);
            #endif
                    MemoryStream responsePacket=new MemoryStream();
                    CStartDownload startDonwload=new CStartDownload(responsePacket,DownFileHash);

                    if (connection!=null)
                    {
                        connection.SendPacket(responsePacket);
                    }
                }
            }
        }
Exemple #34
0
 private void AddFile(CFile file)
 {
     if (!m_Contains(file.FileHash))
     {
         CElement Element=new CElement();
         Element.File=file;
         Element.Statistics=new CFileStatistics();
         m_FileList.Add(Element);
         if (((file.FileStatus==Protocol.FileState.Ready)||(Element.File.FileStatus==Protocol.FileState.Completing))&&(!file.Completed))
         {
             Element.SourcesList=new CSourcesList(Element);
             Element.Comments=new CedonkeyComments(Element);
         }
         if (!file.Completed)
             CKernel.NewFile(Element);
         else
             CKernel.NewSharedFile(Element);
     }
     else
     {
         CLog.Log(Constants.Log.Notify, "FIL_DUP",CKernel.HashToString(file.FileHash));
         file=null;
     }
 }
Exemple #35
0
        private void m_SendRequestFile()
        {
            #if VERBOSE
            CKernel.LogClient.AddLog("SendRequestFile",m_ID);
            #endif
            m_LastDownloadRequest=DateTime.Now;
            m_DownloadTries++;

            if (DownFileHash==null) return;

            m_DownloadElement=(CElement)CKernel.FilesList[DownFileHash];

            if (m_DownloadElement==null) return;

            MemoryStream packet=new MemoryStream();
            CFileRequest fileRequest;

            if ((m_EmuleProtocol)&&(m_VersionExtendedRequest>0))
            {
                fileRequest=new CFileRequest(DownFileHash,m_DownloadElement.File.ChunksStatus,packet);
            }
            else
            {
                fileRequest=new CFileRequest(DownFileHash,null,packet);
            }

            //			if (connection!=null)
            //			{
            //				connection.SendPacket(packet);
            //			}

            //packet=new MemoryStream();
            packet.Seek(0,SeekOrigin.End);
            CIDFileChange IDFileChange=new CIDFileChange(DownFileHash,packet);

            //			if (connection!=null)
            //			{
            //				connection.SendPacket(packet);
            //			}

            if ((m_supportsHorde)&&(m_DownloadElement.File.CrumbsHashSetNeeded()))
            {
                //packet.Seek(0,SeekOrigin.End);
                //CHordeSlotRequest HordeSlotRequest=new CHordeSlotRequest(DownFileHash,packet);
                CLog.Log(Constants.Log.Verbose,"Requesting crumhashset to "+m_UserName+" for "+m_DownloadElement.File.FileName);
                packet.Seek(0,SeekOrigin.End);
                CCrumbSetRequest CrumbSetRequest=new CCrumbSetRequest(DownFileHash,packet);
            }

            // Request sources if allowed
            if (m_AllowSourceExchangeRequest())
            {
            #if VERBOSE
                CKernel.LogClient.AddLog("m_SendRequestFile-RequestSources",m_ID);
            #endif
                Debug.WriteLine(DateTime.Now.ToLongTimeString()+" : Requesting SourceExchange "+m_DownloadElement.File.FileName+" to "+ m_UserName+" | FileHash = "+ CKernel.HashToString(DownFileHash));

                //MemoryStream sourcesPacket=new MemoryStream();
                packet.Seek(0,SeekOrigin.End);
                CRequestSourceExchange requestSourceExchange=new CRequestSourceExchange(packet,DownFileHash);

                if (connection!=null)
                {
                    m_LastSourcesRequest=DateTime.Now;
                    m_DownloadElement.SourcesList.SetLastSourceExchangeRequest();
                    //connection.SendPacket(sourcesPacket);
                }
            }
            if (connection!=null)
            {
                connection.SendPacket(packet);
            }
        }
Exemple #36
0
        public void FileNotFound(byte[] packet)
        {
            // delete source
            #if VERBOSE
            CKernel.LogClient.AddLog("FileNotFound",m_ID);
            #endif
            m_ClientFileName=CKernel.Globalization["FILE_NOT_FOUND"];
            Protocol.DownloadState prevState=m_DownloadState;
            m_DownloadState=Protocol.DownloadState.None;

            if (packet.Length!=16)
            {
                //raise exception
                Exception e=new Exception("Invalid packet size");
                throw(e);
            }

            if (!CKernel.SameHash(ref DownFileHash,ref packet))
            {
                DownFileHash=packet;
            }

            if ((DownFileHash!=null)&&(m_DownloadElement==null))
            {
                m_DownloadElement=(CElement)CKernel.FilesList[DownFileHash];
            }

            if ((m_DownloadElement!=null)&&(m_DownloadElement.SourcesList!=null))
            {
                if (prevState==Protocol.DownloadState.Downloading)
                {
                    m_CleanDownloadBlocks();
                    m_LastDownloadRequest=DateTime.Now;
                    m_DownloadSpeeds.Clear();
                    m_DownloadSpeed=0;
                    m_QRDownload=0;
                }
                m_DownloadElement.SourcesList.RemoveSource(this);
            }
        }
Exemple #37
0
 private bool m_AllowSourceExchangeRequest()
 {
     long nextReask;
     if ((!m_EmuleProtocol)||(DownFileHash==null)) return false;
     if (m_DownloadElement==null) m_DownloadElement=CKernel.FilesList[DownFileHash];
     if ((m_DownloadElement==null)||(m_DownloadElement.SourcesList==null)) return false;
     if (DateTime.Now.Ticks-m_DownloadElement.Statistics.StartTime.Ticks<Protocol.StartUpPeriod)
         nextReask = Protocol.ReaskSourceAtStartUp;
     else
         nextReask = Protocol.ReaskSource;
     return ((DateTime.Now.Ticks-m_LastSourcesRequest.Ticks>Protocol.ReaskSameSource)
         && (DateTime.Now.Ticks-m_DownloadElement.SourcesList.GetLastSourceExchangeRequest().Ticks>nextReask)
         && (m_SourceExchangeVersion>=1)
         && (CKernel.Preferences.GetBool("UseEmuleProtocol"))
         && (m_DownloadElement.File.MaxSources>m_DownloadElement.SourcesList.Count()-5));
 }
Exemple #38
0
 public CedonkeyComments(CElement in_Element)
 {
     Element=in_Element;
 }
Exemple #39
0
 public void AddFile(string name, uint size, byte[] Hash, stDatosFuente[] sources)
 {
     CElement Element;
     if (this.m_Contains(Hash))
     {
         CLog.Log(Constants.Log.Notify,"FIL_DUP",name);
         Element=(CElement)this[Hash];
     }
     else
     {
         CFile file=new CFile(Hash,name,size);
         Element=new CElement();
         Element.File=file;
         Element.Statistics=new CFileStatistics();
         m_FileList.Add(Element);
         CKernel.NewFile(Element);
         CLog.Log(Constants.Log.Notify,"FIL_ADDED",name);
     }
     if ((Element.SourcesList==null)&&((Element.File.FileStatus==Protocol.FileState.Ready)||(Element.File.FileStatus==Protocol.FileState.Completing)))
     {
         CSourcesList sourcesList=new CSourcesList(Element);
         Element.SourcesList=sourcesList;
         if (CKernel.ServersList.ActiveServer!=null) CKernel.ServersList.ActiveServer.RequestSources(Element.File.FileHash);
     }
     if ((Element.SourcesList!=null)&&
         ((Element.File.FileStatus==Protocol.FileState.Ready)||(Element.File.FileStatus==Protocol.FileState.Completing))&&
         (sources!=null))
         CKernel.ClientsList.AddClientsToFile(sources,Hash);
 }
Exemple #40
0
        public void TryUDPDownload()
        {
            m_AskingUDP=true;

            if ((m_EmuleProtocol)&&
                (m_VersionUDP>=1)&&
                (m_ID>Protocol.LowIDLimit)&&
                (m_UDPPort>0)&&
                (DownFileHash!=null)&&
                ((m_QRDownload>50)||(m_QRDownload==0))&&
                ((!m_SupportsPartner)||(!CKernel.Queue.AllowNewParner()))&&
                !m_AllowSourceExchangeRequest())
            {
            #if VERBOSE
                CKernel.LogClient.AddLog("Intentar Descarga UDP");
            #endif
                MemoryStream buffer=new MemoryStream();
                if (m_DownloadElement==null) m_DownloadElement=CKernel.FilesList[DownFileHash];
                if (m_DownloadElement==null) return;
                CFileReaskUDP PeticionUDP=new CFileReaskUDP(buffer,DownFileHash,m_VersionUDP,m_DownloadElement.File.ChunksStatus);

                IPEndPoint hostRemote=new IPEndPoint(m_ID,m_UDPPort);
                CKernel.UDPListener.SendPacketUDP(buffer.GetBuffer(),hostRemote);
            }
        }
Exemple #41
0
 /// <summary>
 /// Publish one new shared file (only one)
 /// </summary>
 public void PublishSharedFile(CElement Element)
 {
     MemoryStream buffer=new MemoryStream();
     CServerPublishFiles ServerPublishFiles=new CServerPublishFiles(buffer, Element);
     //if server supports compression we send it compressed
     if (SupportCompression)
     {
         CCompressedPacket CompressedPacket=new CCompressedPacket(ref buffer);
     }
     if (m_ServerConnection!=null) m_ServerConnection.SendPacket(buffer);
 }
Exemple #42
0
 private void InitializeClient(ushort in_Port,uint in_IP,uint in_ServerIP,ushort in_ServerPort,byte[] in_DownFileHash)
 {
     m_Port=in_Port;
     m_strIP=in_IP.ToString();
     m_ID=in_IP;
     m_ServerIP=in_ServerIP;
     m_ServerPort=in_ServerPort;
     m_ClientFileName="";
     m_LastDownloadRequest=DateTime.MinValue;
     m_LastSourcesRequest=DateTime.MinValue;
     m_SourceExchangeVersion=1;
     m_DownloadTries=0;
     m_Software=(byte)Protocol.Client.Unknown;
     if (in_DownFileHash!=null)
     {
         DownFileHash=in_DownFileHash;
     }
     else
     {
         DownFileHash=null;
     }
     m_DownloadState=Protocol.DownloadState.None;
     m_UploadState=Protocol.UploadState.None;
     m_UploadBlocks=new ArrayList();
     m_UploadDataPackets=new ArrayList();
     m_DownloadBlocks=new ArrayList();
     m_UploadElement=null;
     m_ConexionTries=0;
     #if DEBUG
     IPAddress DirectionIP=new IPAddress(in_IP);
     m_UserName=DirectionIP.ToString()+":"+Convert.ToString(m_Port);
     #else
     m_UserName="******";
     #endif
     m_DownloadSpeeds=new ArrayList();
     m_UploadSpeeds=new ArrayList();
     m_LastChunkRequested=-1;
     m_SentComment=false;
     m_AskingUDP=true;
     m_SharedFilesRequested=false;
     m_CallBackTime=DateTime.MinValue;
     m_FriendLevel=Types.Constants.FriendLevel.NoFriend;
     m_FirstMessage=true;
     m_IsSpammer=false;
     m_IsPartner=false;
     m_PartnerAllowed=false;
     m_SupportsPartner=false;
     m_BadPartnerTime=DateTime.MinValue;
     m_PartnerStartedTime=DateTime.MinValue;
     m_supportsHorde=false;
     m_TimesPartnerSlow=0;
 }
Exemple #43
0
        private bool m_LoadFilesFromFolder(string folder/*,bool refreshing*/)
        {
            if (!Directory.Exists(folder)) return false;
            string [] ficheros=Directory.GetFiles(folder);
            DateTime date;
            string name;
            if (m_EdonkeyHash==null) m_EdonkeyHash=new CHash();
            foreach (string file in ficheros)
            {
                // 0 Kb file are ignored, avoid a crash
                FileInfo filInfo = new FileInfo(file);
                if((filInfo.Length == 0)||
                    ((filInfo.Attributes&(FileAttributes.Hidden|FileAttributes.System))!=0)) continue;

                date=File.GetLastWriteTime(file).ToUniversalTime();
                name=Path.GetFileName(file);
                CKnownFileAttributes Atributos;
                if ((Atributos=m_IsKnown(name,date))!=null)
                {
                    //if (refreshing) continue;
                    if (!m_Contains(Atributos.FileHash))
                    {
                    CElement Element=new CElement();
                    Element.File=new CFile(Atributos.FileHash,Atributos.Date,folder,name,Atributos.Size, Atributos.Priority, Atributos.Permisions, Atributos.HashSet, Atributos.Comment, Atributos.Rating);
                    Element.SourcesList=null;
                    Element.Statistics=new CFileStatistics();
                    this.m_FileList.Add(Element);
                    CKernel.NewSharedFile(Element);
                    }
                    //if (!m_Contains(Atributos.FileHash))this.m_FileList.Add(Element);
                }
                else //new file
                {
                    m_EdonkeyHash.AddFile(file);
                }
            }
            return true;
        }
Exemple #44
0
        private bool m_CreateDataPackets()
        {
            CFileBlock sendBlock;
            sendBlock=(CFileBlock)m_UploadBlocks[0];
            byte[] Datos=null;
            CElement element=(CElement)CKernel.FilesList[sendBlock.FileHash];

            m_UploadElement=element;

            if (CKernel.SameHash(ref m_UpFileHash,ref sendBlock.FileHash))
            {
                Buffer.BlockCopy(sendBlock.FileHash,0,m_UpFileHash,0,16);
            }

            if ((element!=null)&&(sendBlock.end-sendBlock.start<185000))
            {
                Datos=element.File.ReadBlock(sendBlock.start,sendBlock.end-1,false);
            }

            if ((Datos==null)||(element==null))
            {
                // cancel upload
                Debug.Write("Part not found in file\n");
                CancelUploadTransfer(false);
                return false;
            }

            MemoryStream DatosStream=new MemoryStream(Datos);

            //if you uncoment this upload compression will be enabled (not so tested)
            //if (bEsMula)
            //{
            //	CCompressedBlockSend EnvioBloque=new CCompressedBlockSend(Datos,sendBlock.inicio,sendBlock.fin,sendBlock.FileHash,ref m_UploadDataPackets);
            //}
            //else
            //{
            CSendBlock EnvioBloque=new CSendBlock(DatosStream,sendBlock.start,sendBlock.end,sendBlock.FileHash,ref m_UploadDataPackets);
            //}
            Datos=null;
            m_UploadBlocks.Remove(sendBlock);
            //GC.Collect();
            return true;
        }
 //constructor to publish one file
 public CServerPublishFiles(MemoryStream buffer,CElement element)
 {
     DonkeyHeader header;
     BinaryWriter writer=new BinaryWriter(buffer);
     header=new DonkeyHeader((byte)Protocol.ServerCommand.OfferFiles,writer);
     writer.Write(1);
     m_AddFileToPacket(writer,element);
     header.Packetlength=(uint)writer.BaseStream.Length-header.Packetlength+1;
     writer.Seek(0,SeekOrigin.Begin);
     header.Serialize(writer);
     writer.Write(1);
     CLog.Log(Types.Constants.Log.Info,"FIL_PUBLISHED",1);
 }
Exemple #46
0
        public void AddOtherDownloadFile(string strDownloadFileHash)
        {
            if (m_OtherDownFiles==null)
            {
                m_OtherDownFiles=new StringCollection();
            }

            if (!m_OtherDownFiles.Contains(strDownloadFileHash))
            {
                m_OtherDownFiles.Add(strDownloadFileHash);
            }

            //if the alternative file has higher priority then swap
            CElement newElement=CKernel.FilesList[CKernel.StringToHash(strDownloadFileHash)];
            if (m_DownloadElement==null) m_DownloadElement=CKernel.FilesList[DownFileHash];
            if ((newElement!=null)&&
                (m_DownloadElement!=null)&&
                ((byte)m_DownloadElement.File.DownPriority<(byte)newElement.File.DownPriority)&&
                ((m_DownloadState==Protocol.DownloadState.OnQueue)||(m_DownloadState==Protocol.DownloadState.None)))
            {
                string previousDownloadHash=CKernel.HashToString(m_DownloadElement.File.FileHash);
                m_DownloadElement.SourcesList.RemoveSource(this); //this will swap the source to the highest priority alternative file
                //add the previous file to the alternative files
                m_OtherDownFiles.Add(previousDownloadHash);
            }
        }
 private bool m_AddFileToPacket(BinaryWriter writer,CElement element)
 {
     try
     {
         if (!element.File.Empty)
         {
             writer.Write(element.File.FileHash);
             if (element.File.Completed)
             {
                 writer.Write((uint)0xfbfbfbfb);
                 writer.Write((ushort)0xfbfb);
             }
             else
             {
                 writer.Write((uint)0xfcfcfcfc);
                 writer.Write((ushort)0xfcfc);
             }
             uint nParameters=2;
             if (element.File.Details.ListDetails.ContainsKey(Constants.Avi.Length)) nParameters++;
             if (element.File.Details.ListDetails.ContainsKey(Constants.Avi.VBitrate)) nParameters++;
             if (element.File.Details.ListDetails.ContainsKey(Constants.Avi.VCodec)) nParameters++;
             writer.Write(nParameters);
             // name
             new ParameterWriter((byte)Protocol.FileTag.Name,element.File.FileName,writer);
             // size
             new ParameterWriter((byte)Protocol.FileTag.Size,element.File.FileSize,writer);
             if (element.File.Details.Type==(byte)Constants.FileType.Avi)
             {
                 if (element.File.Details.ListDetails.ContainsKey(Constants.Avi.Length))
                     new ParameterWriter(Protocol.FileExtraTags.length.ToString(),(string)element.File.Details.ListDetails[Constants.Avi.Length],writer);
                 if (element.File.Details.ListDetails.ContainsKey(Constants.Avi.VBitrate))
                     new ParameterWriter(Protocol.FileExtraTags.bitrate.ToString(), Convert.ToUInt32(((string)element.File.Details.ListDetails[Constants.Avi.VBitrate]).Replace(" Kbps","")), writer);
                 if (element.File.Details.ListDetails.ContainsKey(Constants.Avi.VCodec))
                     new ParameterWriter(Protocol.FileExtraTags.codec.ToString(),(string)element.File.Details.ListDetails[Constants.Avi.VCodec],writer);
             }
             return true;
         }
     }
     catch(Exception e)
     {
         Debug.WriteLine(e.ToString());
     }
     return false;
 }
Exemple #48
0
        public void OnDisconnect(byte reason)
        {
            connection=null;
            if (m_SharedFilesRequested) CLog.Log(Constants.Log.Notify,"CLI_DONT_SEND_SHARED",m_UserName);
            m_SharedFilesRequested=false;
            #if VERBOSE
            CKernel.LogClient.AddLog("OnDisconnect-Client",m_ID);
            #endif
            #if DEBUG
            string strReason=CKernel.Globalization["UNK_REASON"];

            switch((Protocol.ConnectionReason)reason)
            {
                case Protocol.ConnectionReason.CannotConnect:
                    strReason=CKernel.Globalization["CANT_CONNECT"];
                    break;
                case Protocol.ConnectionReason.ClosedConnection:
                    strReason=CKernel.Globalization["CONNECTION_CLOSED"];
                    break;
                case Protocol.ConnectionReason.NullPacket:
                    strReason=CKernel.Globalization["NULL_PACKET"];
                    break;
                case Protocol.ConnectionReason.NullID:
                    strReason=CKernel.Globalization["NULL_ID"];
                    break;
                case Protocol.ConnectionReason.InvalidHeader:
                    strReason=CKernel.Globalization["INVALID_HEADER"];
                    break;
                case Protocol.ConnectionReason.TimeOut:
                    strReason=CKernel.Globalization["TIMEOUT"];
                    break;
            }
            #endif
            #if VERBOSE
            CKernel.LogClient.AddLog("OnDisconnect-"+strReason,m_ID);
            #endif
            if (m_ChatMessages!=null)
            {
                m_ChatMessages.Clear();
                m_ChatMessages=null;
            }

            if (m_UploadState==Protocol.UploadState.Uploading)
            {
                CancelUploadTransfer(true);
            }

            if ((m_UploadState==Protocol.UploadState.Connecting)
                || (m_UploadState==Protocol.UploadState.WaitCallBack))
            {
                CancelUploadTransfer(false);
            }

            if ((m_DownloadState==Protocol.DownloadState.Connecting)
                ||(m_DownloadState==Protocol.DownloadState.WaitCallBack))
            {
                if ((m_ConexionTries<Protocol.ConnectionRetries)
                    &&(reason==(byte)Protocol.ConnectionReason.CannotConnect))
                {
            #if DEBUG
                    m_UserName=strReason;
            #endif
                    Connect();
                }
                else
                {
                    //quitar la fuente
                    m_ConexionTries=0;
                    m_DownloadState=Protocol.DownloadState.None;

                    if (DownFileHash!=null)
                    {
                        if (m_OtherDownFiles!=null)
                        {
                            m_OtherDownFiles.Clear();
                        }

                        m_OtherDownFiles=null;

                        if (m_DownloadElement==null)
                        {
                            m_DownloadElement=(CElement)CKernel.FilesList[DownFileHash];
                        }
                        if ((m_DownloadElement!=null)&&(m_DownloadElement.SourcesList!=null)) m_DownloadElement.SourcesList.RemoveSource(this);
                    }
                    else
                    {
                        Debug.WriteLine(m_UserName+"Never should enter here-> null DownFileHash");
                    }
            #if DEBUG
                    m_UserName=strReason;
            #endif
                }
            }

            if (m_DownloadState==Protocol.DownloadState.Connected)
            {
                m_DownloadState=Protocol.DownloadState.None;

                if (m_DownloadElement==null)
                {
                    m_DownloadElement=(CElement)CKernel.FilesList[DownFileHash];
                }

                m_DownloadElement.SourcesList.RemoveSource(this);
            }

            //free all pending blocks
            if (m_DownloadState==Protocol.DownloadState.Downloading)
            {
                //CLog.Log(Constants.Log.Verbose,"Transfer interrrupted,reason: {0}",strReason);
                m_CleanDownloadBlocks();

                m_LastDownloadRequest=DateTime.Now;
                m_DownloadSpeeds.Clear();
                m_DownloadSpeed=0;
                m_QRDownload=0;
                m_DownloadState=Protocol.DownloadState.OnQueue;
            }
            //for eny reason some clients (edonkeys mainly) have pending blocks but their downloadstate!=Downloading
            if (m_DownloadBlocks.Count>0)
            {
                m_CleanDownloadBlocks();
            //					Debug.WriteLine(m_DownloadState.ToString());
            //					Debug.WriteLine("Disconnected leaving pending blocks!!!");
            }
            CKernel.ClientsList.IsClientNeeded(this);
        }
Exemple #49
0
        public void ProcessFileRequest(byte[] packet)
        {
            #if VERBOSE
            CKernel.LogClient.AddLog("ProcessFileRequest",m_ID);
            #endif
            CFileRequest fileRequest=new CFileRequest(new MemoryStream(packet));

            if (fileRequest.FileHash==null)
                return;

            m_UpFileHash=fileRequest.FileHash;
            byte[] tmp_UploadFileHash=fileRequest.FileHash;
            m_UploadElement=(CElement)CKernel.FilesList[m_UpFileHash];
            CElement tmpUploadElement=m_UploadElement;

            if ((m_UploadElement==null)||(m_UploadElement.File.Empty))
            {
                /*	Dont need to send no file found,we have sent it already in ProcessRequestFileID
                *	MemoryStream buffer=new MemoryStream();
                *	CNoFile noFile=new CNoFile(buffer,m_UpFileHash);
                *	m_UpFileHash=null;
                *	m_UploadElement=null;
                *	if (connection!=null) connection.SendPacket(buffer);
                */
            }
            else
            {
            #if VERBOSE
                CKernel.LogClient.AddLog("ProcessFileRequest-send file info",m_ID);
            #endif
                m_UploadElement.Statistics.IncSessionRequests();
                if ((fileRequest.Partes!=null)
                    &&(fileRequest.Partes.Length==m_UploadElement.File.NumChunks))
                {
                    m_UpFileChunks=fileRequest.Partes;
                }

                MemoryStream fileInfoPacket=new MemoryStream();
                CFileInfo fileInfo=new CFileInfo(m_UpFileHash,m_UploadElement.File.FileName,fileInfoPacket);
                if (connection!=null)
                {
                    connection.SendPacket(fileInfoPacket);
                }
                m_SendComment();
            }

            // it can be a new source for downloads
            if ((tmpUploadElement!=null)
                &&(tmpUploadElement.SourcesList!=null)
                &&(!tmpUploadElement.File.Completed)
                &&(tmpUploadElement.File.FileStatus==Protocol.FileState.Ready))
            {
                if (DownFileHash==null)
                {
            #if VERBOSE
                    CKernel.LogClient.AddLog("ProcessFileRequest-add client to downloads",m_ID);
            #endif
                    DownFileHash=new byte[16];
                    Buffer.BlockCopy(tmpUploadElement.File.FileHash,0,DownFileHash,0,16);
                    m_DownloadElement=tmpUploadElement;
                    m_DownloadState=Protocol.DownloadState.Connected;
                    if (tmpUploadElement.SourcesList.AddSource(this))
                    {
                        TryDownload();
                    }
                    else
                    {
                        m_DownloadState=Protocol.DownloadState.None;
                    }
                }
                else
                {
                    if (!CKernel.SameHash(ref DownFileHash,ref tmpUploadElement.File.FileHash))
                        AddOtherDownloadFile(CKernel.HashToString(tmp_UploadFileHash));
                }
            }
        }
Exemple #50
0
        public void ProcessComment(byte[] packet)
        {
            CComment commentCMD=new CComment(new MemoryStream(packet));

            m_Comment=commentCMD.comment;
            m_Rating=commentCMD.rating;

            if ((m_DownloadElement==null)&&(DownFileHash!=null))
            {
                m_DownloadElement=CKernel.FilesList[DownFileHash];
            }

            if ((m_DownloadElement!=null)&&(m_DownloadElement.Comments!=null))
            {
                m_DownloadElement.Comments.NewComment(m_UserName,m_Rating,m_Comment);
            }
        }
Exemple #51
0
 public CClient(CConnection in_connection)
 {
     connection=in_connection;
     m_UploadBlocks=new ArrayList();
     m_UploadDataPackets=new ArrayList();
     m_DownloadBlocks=new ArrayList();
     m_DownloadState=Protocol.DownloadState.None;
     m_UploadState=Protocol.UploadState.None;
     m_UploadElement=null;
     m_LastSourcesRequest=DateTime.MinValue;
     m_DownloadTries=0;
     m_ClientFileName="";
     m_Software=(byte)Protocol.Client.Unknown;
     m_DownloadSpeeds=new ArrayList();
     m_UploadSpeeds=new ArrayList();
     m_SentComment=false;
     m_LastChunkRequested=-1;
     m_AskingUDP=true;
     m_SharedFilesRequested=false;
     m_CallBackTime=DateTime.MinValue;
     m_FriendLevel=Types.Constants.FriendLevel.NoFriend;
     m_FirstMessage=true;
     m_IsSpammer=false;
     m_IsPartner=false;
     m_PartnerAllowed=false;
     m_SupportsPartner=false;
     m_BadPartnerTime=DateTime.MinValue;
     m_PartnerStartedTime=DateTime.MinValue;
     m_supportsHorde=false;
     m_TimesPartnerSlow=0;
 }
        internal InterfaceFile FileToInterfaceFile(CElement Element)
        {
            if (apw)
            {
                if (Element==null) return null;
                InterfaceFile response=new InterfaceFile();
                response.Name=Element.File.FileName;
                response.CompleteName=Element.File.CompleteName;
                response.Size=Element.File.FileSize;
                response.BytesDownloaded=Element.File.Transferred;
                response.RemainingBytes=Element.File.GetRemainingBytes();
                response.Status=(byte)Element.File.FileStatus;
                response.ChunksStatus=Element.File.ChunksStatus;
                response.UploadPriority=Element.File.UpPriority;
                response.DownloadPriority=Element.File.DownPriority;
                response.Gaps=Element.File.Gaps;
                response.RequestingBlocks=Element.File.RequestingBlocks;
                response.UploadChunksAvaibility=Element.Statistics.UploadAvaibility;
                if (response.ChunksStatus.Length==0)
                {
                    response.ChunksStatus=new byte[CHash.GetChunksCount(Element.File.FileSize)];
                    for (int i=0; i < response.ChunksStatus.Length; i++)
                    {
                        response.ChunksStatus[i]=(byte)Protocol.ChunkState.Empty;
                    }
                }
                response.MaxSources=Element.File.MaxSourcesInt;
                if (Element.SourcesList!=null)
                {
                    response.nSources=(ushort)Element.SourcesList.Count();
                    response.DownSpeed=Element.SourcesList.GetDownloadSpeed();
                    response.ChunksAvaibility=Element.SourcesList.GetChunksAvaibility();
                    response.nValidSources=Element.SourcesList.GetUsableClients();
                    response.nTransferringSources=Element.SourcesList.GetDownloadingClients();
                }
                else
                {
                    response.DownSpeed=0;
                    response.nSources=0;
                }
                response.strHash=CKernel.HashToString(Element.File.FileHash);

                if(response.Size!=0)
                    response.PercentCompleted=(decimal)(response.Size-response.RemainingBytes)/response.Size;
                else
                    response.PercentCompleted=0;

                response.CategoryID=Element.File.CategoryID;
                if (Element.File.FileStatus!=Protocol.FileState.Complete)
                    response.Category=CKernel.CategoriesList[Element.File.CategoryID];
                else
                    response.Category="";

                return response;
            }
            else return null;
        }
Exemple #53
0
        public void ProcessRequestFileID(byte[] packet)
        {
            #if VERBOSE
            CKernel.LogClient.AddLog("ProcessRequestFileID",m_ID);
            #endif
            CIDFileChange IDFileChange=new CIDFileChange(new MemoryStream(packet));

            if (!CKernel.SameHash(ref m_UpFileHash,ref IDFileChange.FileHash))
            {
                m_UpFileHash=IDFileChange.FileHash;
                m_UploadElement=(CElement)CKernel.FilesList[m_UpFileHash];
            }

            if ((m_UploadElement==null)||(m_UploadElement.File.Empty))
            {
                //Debug.Write("No se encontro fichero (Cambio ID) \n");
                MemoryStream buffer=new MemoryStream();
                CNoFile noFile=new CNoFile(buffer,m_UpFileHash);
                m_UpFileHash=null;
                if (connection!=null)
                {
                    connection.SendPacket(buffer);
                }
            #if VERBOSE
                CKernel.LogClient.AddLog("ProcessRequestFileID-No found",m_ID);
            #endif
            }
            else
            {
            #if VERBOSE
                CKernel.LogClient.AddLog("ProcessRequestFileID-send file status",m_ID);
            #endif
                MemoryStream packetState=new MemoryStream();
                CFileStatus fileState;

                if (m_UploadElement.File.Completed)
                {
                    fileState=new CFileStatus(m_UpFileHash,null,packetState);
                }
                else
                {
                    fileState=new CFileStatus(m_UpFileHash,m_UploadElement.File.ChunksStatus,packetState);
                }

                if (connection!=null)
                {
                    connection.SendPacket(packetState);
                }
            }
        }
Exemple #54
0
 private void m_StopFile(CElement Element)
 {
     if ((Element!=null)&& (Element.SourcesList!=null))
     {
         Element.SourcesList.Clean();
         Element.SourcesList=null;
     }
 }
Exemple #55
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);
            }
        }
Exemple #56
0
        internal static void RemovedSharedFile(CElement element)
        {
            InterfaceFile file=InterfaceGateway[0].FileToInterfaceFile(element);

            for (int i=0;i<=InterfaceGateway.Length-1;i++)
            {
                if (CKernel.InterfaceGateway[i]!=null)
                {
                    InterfaceGateway[i].RemovedSharedFile(file);
                }
            }
        }
Exemple #57
0
 public void Clean()
 {
     m_Element=null;
     while (m_ArrayList.Count>0)
     {
         CClient Client=(CClient)m_ArrayList[0];
         RemoveSource(Client);
     }
 }