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.Downloading) || ((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); }
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; }
/// <summary> /// Search sources for the 15 next files using TCP /// </summary> public void SearchNextSourcesTCP() { if ((ActiveServer != null) && (!ActiveServer.AllFilesPublished) && (DateTime.Now - ActiveServer.LastPublishedTime > new TimeSpan(0, 1, 0))) { ActiveServer.PublishSharedFiles(); } if ((m_NextTCPSourcesSearch > DateTime.Now) || (ActiveServer == null) || (CKernel.FilesList.Count == 0)) { return; } if (m_TimesshownUDPClosedMessage < 8) { m_TimesshownUDPClosedMessage++; } if ((!CKernel.UDPListener.PortIsAccesible) && (m_TimesshownUDPClosedMessage < 8) && (m_TimesshownUDPClosedMessage > 2) && //ignore first 2 pass (CKernel.Preferences.GetUInt("ID") > Protocol.LowIDLimit)) { if (m_TimesshownUDPClosedMessage < 7) { CLog.Log(Types.Constants.Log.Info, "UDP_PORT_NOT_OPEN"); } else { CLog.Log(Types.Constants.Log.Notify, "UDP_PORT_NOT_OPEN"); } } ArrayList hashes = new ArrayList(); CElement Element; do { if (CKernel.FilesList.Count <= m_TCPSourceSearchFileIndex) { m_TCPSourceSearchFileIndex = 0; break; } else { Element = CKernel.FilesList[m_TCPSourceSearchFileIndex]; m_TCPSourceSearchFileIndex++; } if ((Element.SourcesList != null) && (Element.File.FileStatus != Protocol.FileState.Stopped) && (Element.File.MaxSources > Element.SourcesList.Count() - 5)) { hashes.Add(Element.File.FileHash); } }while (hashes.Count < Protocol.SourcesPerTCPFrame); if ((m_TCPSourceSearchFileIndex == 0) || (hashes.Count == 0)) { m_NextTCPSourcesSearch = DateTime.Now + new TimeSpan(0, Protocol.ReaskServerTCP, 0); } else { m_NextTCPSourcesSearch = DateTime.Now + new TimeSpan(0, 0, Protocol.ReaskNextTCPFile * hashes.Count); } if (hashes.Count > 0) { ActiveServer.RequestSources(hashes); } }
/// <summary> /// Load a list of servers from binary file (server.met). /// </summary> /// <param name="fullpathfile">The full Path to the file.</param> /// <param name="clear">Set clear to true if the list should be cleared before read.</param> /// <returns>Count of servers which could be loaded.</returns> public int Load(string fullpathfile, bool clear) { if (clear) { Clear(); } FileStream servermet; if (fullpathfile.Length == 0) { //fullpathfile=Application.StartupPath + Path.DirectorySeparatorChar + "server.met"; fullpathfile = Path.Combine(CKernel.DllDirectory, "server.met"); } try { servermet = File.OpenRead(fullpathfile); } catch { return(0); } byte version; BinaryReader reader = new BinaryReader(servermet); int added = 0; try { version = reader.ReadByte(); if (!Enum.IsDefined(typeof(Protocol.ServerMet), version)) { servermet.Close(); CLog.Log(Constants.Log.Notify, "SRVMET_INVALID"); return(0); } uint nServers = reader.ReadUInt32(); uint ip; ushort port; CServer server; while (nServers > 0) { ip = reader.ReadUInt32(); port = reader.ReadUInt16(); server = Add(ip, port); if (server != null) { added++; } else { server = this[ip, 0]; } server.Load(reader); nServers--; } Sort(); } catch (EndOfStreamException eose) { Debug.WriteLine(eose.ToString()); } catch (Exception e) { Debug.WriteLine(e.ToString()); CLog.Log(Constants.Log.Notify, "SRVMET_INVALID"); } servermet.Close(); CLog.Log(Constants.Log.Info, "SRV_ADDED", added); return(added); }
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.Ant.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; }
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); } } } }
/// <summary> /// Process incomming eDonkey packet. /// </summary> /// <param name="packet">Packet which need to be processed.</param> protected virtual void ProcessDonkeyPacket(ref byte[] packet) { try { switch ((Protocol.ClientCommand)m_DonkeyHeader.Command) { case Protocol.ClientCommand.Hello: if (m_Client == null) { CReceiveHello HelloPacket = new CReceiveHello(false, new MemoryStream(packet)); m_Client = CKernel.ClientsList.GetClient(HelloPacket.UserID, HelloPacket.UserPort, HelloPacket.ServerIP, HelloPacket.Hash); if (m_Client == null) { m_Client = new CClient(this); CKernel.ClientsList.AddClient(m_Client); } else { if ((m_Client.connection != null) && (m_Client.connection.Connected) && (m_Client.connection != this)) { m_Client.connection.CloseConnection(); Debug.WriteLine("Client conexion!=null"); } m_Client.connection = this; } } CClient cant = m_Client; CConnection conant = m_Client.connection; bool NeedExtendRequest = !m_Client.ProcessHello(false, packet); if ((NeedExtendRequest) && (m_Client.EmuleProtocol) && (CKernel.Preferences.GetBool("UseEmuleProtocol"))) { m_Client.SendEmuleHello(false); } m_Client.ResponseHello(); break; case Protocol.ClientCommand.FileRequest: m_Client.ProcessFileRequest(packet); break; case Protocol.ClientCommand.HelloAnswer: m_Client.ProcessHello(true, packet); break; case Protocol.ClientCommand.SetRequestFileID: m_Client.ProcessRequestFileID(packet); break; case Protocol.ClientCommand.FileRequestAnswer: m_Client.ProcessFileInfo(packet); break; case Protocol.ClientCommand.FileState: m_Client.ProcessChunksStatus(packet, false /*tcp*/); break; case Protocol.ClientCommand.HashSetAnswer: m_Client.ProcessHashSet(packet); break; case Protocol.ClientCommand.HashSetRequest: m_Client.SendHashSet(); break; case Protocol.ClientCommand.AcceptUploadRequest: if (m_Client.DownloadState == Protocol.DownloadState.OnQueue) { m_Client.RequestBlocks(); } else { if (m_Client.DownFileHash != null) { // CLog.Log(Constants.Log.Verbose,"Trying to resume download {2}: {0},hashdescarga=null? {1}",m_Client.DownloadState,(m_Client.DownFileHash==null),m_Client.UserName); m_Client.RequestBlocks(); } else { if (m_Client.UpFileHash != null) { #if DEBUG CLog.Log(Constants.Log.Verbose, "Recovering source to download " + m_Client.UserName); #endif m_Client.DownFileHash = m_Client.UpFileHash; m_Client.RequestBlocks(); } else { CSourceOld sourceRecovered = CKernel.SourcesOld.GetSourceOld(m_Client.UserHash); if (sourceRecovered != null) { m_Client.DownFileHash = sourceRecovered.FileHash; m_Client.DownFileChunks = sourceRecovered.FileChunks; m_Client.RequestBlocks(); #if DEBUG CLog.Log(Constants.Log.Verbose, "RECOVERED SOURCE from sources cache " + m_Client.UserName); #endif } #if DEBUG else { CLog.Log(Constants.Log.Verbose, "download lost: {0}", m_Client.UserName); } #endif } } } break; case Protocol.ClientCommand.OutOfPartRequest: m_Client.ProcessOutOfParts(); break; case Protocol.ClientCommand.StartUploadRequest: m_Client.ProcessStartUploadRequest(packet); break; case Protocol.ClientCommand.RequestParts: m_Client.ProcessRequestParts(packet); break; case Protocol.ClientCommand.EndOfDownload: case Protocol.ClientCommand.CancelTransfer: m_Client.CancelUploadTransfer(false); break; case Protocol.ClientCommand.SendingPart: m_Client.ReceiveBlock(packet); break; case Protocol.ClientCommand.QueueRank: m_Client.ProcessQR(packet); break; case Protocol.ClientCommand.FileRequestAnswerNoFile: m_Client.FileNotFound(packet); break; case Protocol.ClientCommand.ChangeClientID: m_Client.ProcessIDChange(packet); break; case Protocol.ClientCommand.ChangeSlot: break; case Protocol.ClientCommand.AskSharedFiles: Constants.AllowViewShared allow = (Constants.AllowViewShared)CKernel.Preferences.GetEnum("AllowViewShared", Constants.AllowViewShared.Nobody); if (allow == Constants.AllowViewShared.All) { m_Client.ProcessSharedListRequest(); } if ((allow == Constants.AllowViewShared.All) && (m_Client.IsFriend)) { m_Client.ProcessSharedListRequest(); } break; case Protocol.ClientCommand.AskSharedFilesAnswer: m_Client.ProcessSharedListResponse(packet); break; case Protocol.ClientCommand.Message: m_Client.ProcessChatMessage(packet); break; case Protocol.ClientCommand.CrumbSetResponse: m_Client.ProcessCrumbSetResponse(packet); break; default: CLog.Log(Constants.Log.Verbose, "CLI_UNK_DONK_TCP_PACKET", m_DonkeyHeader.Command); break; } } catch (Exception e) { Debug.WriteLine(e.ToString()); #if DEBUG if (m_DonkeyHeader != null) { CLog.Log(Constants.Log.Verbose, "CLI_PAQ_DONK_ERROR", m_DonkeyHeader.Command); } #endif } packet = null; return; }
private void m_ProcessRequest() { base.m_ResetTimeOut(); this.m_ReceptionStream.Seek((long)0, SeekOrigin.Begin); StreamReader reader1 = new StreamReader(this.m_ReceptionStream); string text1 = ""; bool flag1 = true; this.m_Headers = new StringCollection(); try { text1 = reader1.ReadLine(); string text2 = ""; while ((text1 != null) && (text1.Length > 0)) { this.m_Headers.Add(text1); this.m_HeaderLength += (text1.Length + 2); if (text1.IndexOf("Pragma: IDs=") == 0) { string text3 = text1.Substring(text1.IndexOf('=') + 1); char[] chArray1 = new char[1] { '|' }; string[] textArray1 = text3.Split(chArray1); uint num1 = Convert.ToUInt32(textArray1[0]); if (textArray1[1].IndexOf(',') >= 0) { text2 = textArray1[1].Substring(0, textArray1[1].IndexOf(',')); } else { text2 = textArray1[1]; } this.m_Client = CKernel.ClientsList.GetClientByWebCacheUpId(num1); } try { text1 = reader1.ReadLine(); if (text1 == null) { flag1 = false; } continue; } catch { flag1 = false; break; } } if (!flag1) { this.m_ReceptionStream.Seek((long)0, SeekOrigin.End); this.ReceivePacket(); } else if (this.m_Client != null) { Regex regex1 = new Regex("GET /encryptedData/(?<start>[0-9]+)-(?<end>[0-9]+)/(?<encHash>.*).htm HTTP/(?<major>[0-9]+).(?<minor>[0-9]+)"); Match match1 = regex1.Match(this.m_Headers[0]); string text4 = match1.Result("${start}"); string text5 = match1.Result("${end}"); string text6 = match1.Result("${encHash}"); uint num2 = Convert.ToUInt32(text4); uint num3 = Convert.ToUInt32(text5); if (num2 > num3) { this.OnConnectionFail(0x1a0); } if (!this.m_Client.ProcessRequestPartsWebCache(this, num2, num3, text6, text2)) { this.OnConnectionFail(0x194); } else { this.m_ReceptionStream.Close(); this.m_ReceptionStream = new MemoryStream(); this.ReceivePacket(); } } else { bool flag2 = false; if (CKernel.Preferences.GetBool("WebInterfaceEnabled")) { try { string text7 = ""; string text8 = ""; string text9 = ""; if (this.m_Headers[0] == "GET / HTTP/1.1") { text7 = "logon"; text8 = "asp"; text9 = ""; } else if (this.m_Headers[0] == "GET /favicon.ico HTTP/1.1") { text7 = "favicon"; text8 = "ico"; text9 = ""; } else { Regex regex2 = new Regex(@"GET /WebInterface/(?<requestPath>\w+)\.(?<requestExtension>\w+)(?<queryString>.*) HTTP/(?<major>[0-9]+).(?<minor>[0-9]+)"); Match match2 = regex2.Match(this.m_Headers[0]); text7 = match2.Result("${requestPath}"); text8 = match2.Result("${requestExtension}"); text9 = match2.Result("${queryString}"); } string text10 = ""; foreach (string text11 in this.m_Headers) { if (text11.Substring(0, 6) == "Cookie") { text10 = text11.Substring(8); } } flag2 = true; CLog.Log(Constants.Log.Verbose, "Requested:" + this.m_Headers[0]); CKernel.WebServer.ProcessRequest(text7, text8, text10, text9, this); } catch (Exception exception1) { Console.WriteLine(exception1.ToString()); CLog.Log(Constants.Log.Verbose, "Requested object not found: " + this.m_Headers[0]); this.OnConnectionFail(0x194); } } if (!flag2 && flag1) { this.OnConnectionFail(0x194); } this.m_ReceptionStream.Close(); this.m_ReceptionStream = new MemoryStream(); this.ReceivePacket(); } } catch (Exception exception2) { CLog.Log(Constants.Log.Info, exception2.ToString()); this.OnConnectionFail(400); } }
private void m_ProcessCacheReceivedBlock(CReceivedBlock receivedBlock) { int num1 = 0; CKernel.GlobalStatistics.IncSessionDownWebCache(receivedBlock.Data.Length); lock (this.m_DownloadBlocks) { while (num1 < this.m_DownloadBlocks.Count) { CFileBlock block1 = (CFileBlock)this.m_DownloadBlocks[num1]; if ((block1.start <= receivedBlock.Start) && ((block1.end + 1) >= receivedBlock.End)) { if (block1.buffer == null) { block1.buffer = new byte[(block1.end + 1) - block1.start]; } block1.position = receivedBlock.End; System.Buffer.BlockCopy(receivedBlock.Data, 0, block1.buffer, (int)(receivedBlock.Start - block1.start), (int)(receivedBlock.End - receivedBlock.Start)); if ((block1.end + 1) == receivedBlock.End) { bool flag1; uint num2; receivedBlock.Data = null; receivedBlock = null; if ((this.m_CachedBlock.RealStartOffset == block1.start) && (this.m_CachedBlock.RealEndOffset == block1.end)) { num2 = (this.m_CachedBlock.RealEndOffset - this.m_CachedBlock.RealStartOffset) + 1; CLog.Log(Constants.Log.Verbose, "Writted complete webcache block " + this.m_DownloadElement.File.FileName + " size:" + num2.ToString()); flag1 = this.m_DownloadElement.File.WriteBlock(this.m_CachedBlock.RealStartOffset, this.m_CachedBlock.RealEndOffset, block1.buffer); this.m_Completado = 2; this.m_DownloadState = Protocol.DownloadState.None; } else { num2 = (this.m_CachedBlock.RealEndOffset - this.m_CachedBlock.RealStartOffset) + 1; CLog.Log(Constants.Log.Verbose, "Writted webcache truncated block " + this.m_DownloadElement.File.FileName + " size:" + num2.ToString()); byte[] buffer1 = new byte[(this.m_CachedBlock.RealEndOffset - this.m_CachedBlock.RealStartOffset) + 1]; System.Buffer.BlockCopy(block1.buffer, (int)(this.m_CachedBlock.RealStartOffset - block1.start), buffer1, 0, buffer1.Length); flag1 = this.m_DownloadElement.File.WriteBlock(this.m_CachedBlock.RealStartOffset, this.m_CachedBlock.RealEndOffset, buffer1); this.m_Completado = 2; this.m_DownloadState = Protocol.DownloadState.None; } if (!flag1) { this.m_DownloadElement.File.RemoveRequestedBlock(block1.start, block1.end); CKernel.FilesList.StopFile(this.m_DownloadElement.File.FileHash); } if (this.m_DownloadElement != null) { this.m_DownloadElement.Statistics.IncSessionDownloadWebCache((block1.end - block1.start) + 1); } block1.buffer = null; block1 = null; if (this.m_DownloadBlocks.Count > 0) { this.m_DownloadBlocks.RemoveAt(num1); } } return; } num1++; } } }
/// <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 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); } }
private bool SetValueFromXmlElement(XmlElement element) { try { XmlNodeList nodes = element.ChildNodes; foreach (XmlElement el in nodes) { if (el.Name == "Friend") { SFriend my_Friend = new SFriend(); my_Friend.FriendSlot = false; //load Friend.UserHash if (el.Attributes["UserHash"].InnerText != "") { byte[] x = null; switch (_currentversion) { case "0.1": x = new byte[el.Attributes["UserHash"].InnerText.Length]; x = Encoding.Default.GetBytes(el.Attributes["UserHash"].InnerText); break; case "0.2": x = Convert.FromBase64String(el.Attributes["UserHash"].InnerText); break; } my_Friend.UserHash = (byte[])x; } else { my_Friend.UserHash = null; } //load Friend.ID my_Friend.ID = uint.Parse(el.Attributes["ID"].InnerText); //load Friend.OurName my_Friend.OurName = el.Attributes["OurName"].InnerText; //load Friend.Name my_Friend.Name = el.Attributes["Name"].InnerText; //load Friend.Port my_Friend.Port = ushort.Parse(el.Attributes["Port"].InnerText); //load Friend.Software my_Friend.Software = el.Attributes["Software"].InnerText; //load Friend.Version my_Friend.Version = uint.Parse(el.Attributes["Version"].InnerText); //load Friend.LastOnline my_Friend.LastOnline = new DateTime(long.Parse(el.Attributes["LastOnline"].InnerText)); //load friendSlot if (el.Attributes["FriendSlot"] != null) { my_Friend.FriendSlot = bool.Parse(el.Attributes["FriendSlot"].InnerText); } List.Add(my_Friend); Constants.FriendLevel friendSlot; if (my_Friend.FriendSlot) { friendSlot = Constants.FriendLevel.FriendSlot; } else { friendSlot = Constants.FriendLevel.Friend; } CKernel.ClientsList.AddClient(my_Friend.ID, my_Friend.Port, 0, my_Friend.UserHash, my_Friend.Port, null, friendSlot); //switch ( el.Attributes["type"].InnerText ) } } } catch { CLog.Log(Constants.Log.Info, "Error loading friends list"); return(false); } return(true); }