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; }
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); } } } }
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); }
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; }
/// <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; }
/// <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); } }
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); } }
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); } }