Ejemplo n.º 1
0
        public void Process()
        {
            if (m_UploadStatistics.Count == 60)
            {
                m_UploadStatistics.RemoveAt(59);
            }
            m_UploadStatistics.Insert(0, m_Uploaded);
            m_Uploaded = 0;
            long upstream = 0;

            foreach (int n in m_UploadStatistics)
            {
                upstream += n;
            }
            m_Upstream       = (int)(upstream / m_UploadStatistics.Count);
            m_UpstreamString = Core.TransferVolumeToString(m_Upstream);
        }
Ejemplo n.º 2
0
        public static void Load()
        {
            SetUILanguage();

            m_ShareManager = new ShareManager();

            Constants.SetMaximumDownloadsCount(int.Parse(Settings.Instance["MaximumDownloadsCount"]));
            if (!Directory.Exists(Settings.Instance["PreferencesDirectory"]))
                Directory.CreateDirectory(Settings.Instance["PreferencesDirectory"]);
            Settings.Instance["PreferencesDirectory"] = new DirectoryInfo(Settings.Instance["PreferencesDirectory"]).FullName;
            if (!Directory.Exists(Settings.Instance["LogDirectory"]))
                Directory.CreateDirectory(Settings.Instance["LogDirectory"]);
            Settings.Instance["LogDirectory"] = new DirectoryInfo(Settings.Instance["LogDirectory"]).FullName;
            if (!Directory.Exists(Settings.Instance["IncomingDirectory"]))
                Directory.CreateDirectory(Settings.Instance["IncomingDirectory"]);
            Settings.Instance["IncomingDirectory"] = new DirectoryInfo(Settings.Instance["IncomingDirectory"]).FullName;
            if (!Directory.Exists(Settings.Instance["TemporaryDirectory"]))
                Directory.CreateDirectory(Settings.Instance["TemporaryDirectory"]);
            Settings.Instance["TemporaryDirectory"] = new DirectoryInfo(Settings.Instance["TemporaryDirectory"]).FullName;
            if (!Directory.Exists(Settings.Instance["CorruptDirectory"]))
                Directory.CreateDirectory(Settings.Instance["CorruptDirectory"]);
            Settings.Instance["CorruptDirectory"] = new DirectoryInfo(Settings.Instance["CorruptDirectory"]).FullName;
            m_WebCachesFilePath = Path.Combine(Settings.Instance["PreferencesDirectory"], m_WebCachesFilePath);
            //2009-01-25 Nochbaer
            m_SearchDBFilePath = Path.Combine(Settings.Instance["PreferencesDirectory"], m_SearchDBFilePath);
            m_SharedDirectoriesFilePath = Path.Combine(Settings.Instance["PreferencesDirectory"], m_SharedDirectoriesFilePath);
            m_SharedFilesFilePath = Path.Combine(Settings.Instance["PreferencesDirectory"], m_SharedFilesFilePath);
            m_SharedFilesStatsFilePath = Path.Combine(Settings.Instance["PreferencesDirectory"], m_SharedFilesStatsFilePath);
            m_MetaDataFilePath = Path.Combine(Settings.Instance["PreferencesDirectory"], m_MetaDataFilePath);
            m_CommentsFilePath = Path.Combine(Settings.Instance["PreferencesDirectory"], m_CommentsFilePath);
            m_RatingsFilePath = Path.Combine(Settings.Instance["PreferencesDirectory"], m_RatingsFilePath);
            m_StatisticsFilePath = Path.Combine(Settings.Instance["PreferencesDirectory"], m_StatisticsFilePath);
            m_DownloadsFilePath = Path.Combine(Settings.Instance["PreferencesDirectory"], m_DownloadsFilePath);

            // initialize logger with log directory
            // Changed 2007-05-06 by T.Norad
            if (bool.Parse(Settings.Instance["WriteLogfile"]))
            {
                Logger.Instance.initialize(Settings.Instance["LogDirectory"]);
            }

            // 2007-05-16 T.Norad
            ResumeDownloads();

            m_Logger.Log(Properties.Resources_Core.StealthNetLoading, String.Format(Constants.Software, Core.Version));
            m_Logger.Log(Properties.Resources_Core.DownloadSourcesAllowed, Constants.MaximumDownloadsCount, Constants.MaximumSourcesCount);
            m_Logger.Log(Properties.Resources_Core.NETFrameworkVersion, Environment.Version.ToString());
            m_Logger.Log(Properties.Resources_Core.OSVersion, Environment.OSVersion.ToString());

            m_DropChainTailCount = 0;
            if (GenerateIDOrHash()[47] > 192)
                while (GenerateIDOrHash()[47] <= 128)
                    m_DropChainTailCount++;

            m_PeerID = GenerateIDOrHash();

            try
            {
                UpdateWebServiceProxy update = new UpdateWebServiceProxy();
                if (bool.Parse(Settings.Instance["SynchronizeWebCaches"]))
                {
                    string webCaches = update.GetWebCaches();
                    if (File.Exists(m_WebCachesFilePath))
                    {
                        string backupFilePath = string.Format("{0}.bak", m_WebCachesFilePath);
                        if (File.Exists(backupFilePath))
                        {
                            string backupBackupFilePath = string.Format("{0}.bak", backupFilePath);
                            if (File.Exists(backupBackupFilePath))
                                File.Delete(backupBackupFilePath);
                            File.Move(backupFilePath, backupBackupFilePath);
                        }
                        File.Move(m_WebCachesFilePath, backupFilePath);
                    }
                    StreamWriter webCachesFileStreamWriter = new StreamWriter(new FileStream(m_WebCachesFilePath, FileMode.Create, FileAccess.Write, FileShare.None));
                    webCachesFileStreamWriter.Write(webCaches);
                    webCachesFileStreamWriter.Flush();
                    webCachesFileStreamWriter.Close();
                }
                m_IsUpdateAvailable = update.IsUpdateAvailable(String.Format(Constants.Software, Core.Version));
                update.Dispose();
            }
            catch (Exception ex)
            {
                m_Logger.Log(ex, "An exception was thrown while updating the list of WebCaches!");
            }

            m_Keys = RSAGenerateKeys();

            try
            {
                if (File.Exists(m_WebCachesFilePath))
                {
                    XmlDocument webCachesXmlDocument = new XmlDocument();
                    webCachesXmlDocument.Load(m_WebCachesFilePath);
                    foreach (XmlNode webCacheNode in webCachesXmlDocument.SelectSingleNode("webcaches").SelectNodes("webcache"))
                        m_WebCaches.Add(webCacheNode.Attributes["url"].Value);
                }
                else if (bool.Parse(Settings.Instance["SynchronizeWebCaches"]))
                {
                    m_WebCaches.Add("http://rshare.de/rshare.asmx");
                    m_WebCaches.Add("http://webcache.stealthnet.at/rwpmws.php");
                }
            }
            catch (Exception ex)
            {
                m_Logger.Log(ex, "An exception was thrown while reading WebCaches file!");
            }
            m_ShareManager.LoadConfiguration(m_SharedDirectoriesFilePath, m_SharedFilesFilePath, m_SharedFilesStatsFilePath, m_MetaDataFilePath, m_CommentsFilePath, m_RatingsFilePath);

            //2009-01-25 Nochbaer
            if (bool.Parse(Settings.Instance["ActivateSearchDB"]))
            {
                m_SearchDBManager = new SearchDBManager(m_SearchDBFilePath);
            }

            try
            {
                if (File.Exists(m_StatisticsFilePath))
                {
                    XmlDocument statisticsXmlDocument = new XmlDocument();
                    statisticsXmlDocument.Load(m_StatisticsFilePath);
                    XmlNode statisticsXmlNode = statisticsXmlDocument.SelectSingleNode("statistics");
                    m_CumulativeDownloaded = long.Parse(statisticsXmlNode.SelectSingleNode("downloaded").InnerText);
                    m_CumulativeUploaded = long.Parse(statisticsXmlNode.SelectSingleNode("uploaded").InnerText);
                    m_CumulativeUptime = TimeSpan.Parse(statisticsXmlNode.SelectSingleNode("uptime").InnerText);
                }
            }
            catch (Exception ex)
            {
                m_Logger.Log(ex, "An exception was thrown while reading statistics file!");
            }

            // [MONO] the variable 'downloadsXmlNode' seems to be never used
            /*
            try
            {
                if (File.Exists(m_DownloadsFilePath))
                {
                    XmlDocument downloadsXmlDocument = new XmlDocument();
                    downloadsXmlDocument.Load(m_DownloadsFilePath);
                    XmlNode downloadsXmlNode = downloadsXmlDocument.SelectSingleNode("downloads");
                }
            }
            catch (Exception ex)
            {
                m_Logger.Log(ex, "An exception was thrown while reading downloads file!");
            }
            */

            Thread statisticsThread = new Thread(delegate()
            {
                RList<int> downloadStatistics = new RList<int>();
                int downloadStatisticsRestCount = 0;
                long downloadStatisticsRest = 0;
                long averageDownloadStatistics;
                RList<int> uploadStatistics = new RList<int>();
                int uploadStatisticsRestCount = 0;
                long uploadStatisticsRest = 0;
                long averageUploadStatistics;
                while (!m_IsClosing)
                {
                    m_Downstream = m_CurrentDownstream;
                    m_CurrentDownstream = 0;
                    m_Upstream = m_CurrentUpstream;
                    m_CurrentUpstream = 0;

                    int downstream = m_Downstream;
                    int upstream = m_Upstream;
                    m_Downloaded += downstream;
                    m_Uploaded += upstream;
                    m_CumulativeDownloaded += downstream;
                    m_CumulativeUploaded += upstream;
                    m_Uptime = m_Uptime.Add(TimeSpan.FromSeconds(1));
                    m_CumulativeUptime = m_CumulativeUptime.Add(TimeSpan.FromSeconds(1));

                    if (downloadStatistics.Count == 300)
                    {
                        downloadStatisticsRestCount++;
                        downloadStatisticsRest += downloadStatistics[downloadStatistics.Count - 1];
                        downloadStatistics.RemoveAt(downloadStatistics.Count - 1);
                    }
                    downloadStatistics.Insert(0, downstream);
                    if (m_MinuteAverageDownloadStatistics.Count != 0)
                    {
                        averageDownloadStatistics = 0;
                        for (int n = 0; n < Math.Min(60, downloadStatistics.Count); n++)
                            averageDownloadStatistics += downloadStatistics[n];
                        if (m_MinuteAverageDownloadStatistics.Count == 300)
                            m_MinuteAverageDownloadStatistics.RemoveAt(m_MinuteAverageDownloadStatistics.Count - 1);
                        m_MinuteAverageDownloadStatistics.Insert(0, (int)(averageDownloadStatistics / Math.Min(60, m_MinuteAverageDownloadStatistics.Count)));
                    }
                    else
                        m_MinuteAverageDownloadStatistics.Insert(0, 0);
                    averageDownloadStatistics = 0;
                    foreach (int item in downloadStatistics)
                        averageDownloadStatistics += item;
                    if (m_AverageDownloadStatistics.Count == 300)
                        m_AverageDownloadStatistics.RemoveAt(m_AverageDownloadStatistics.Count - 1);
                    m_AverageDownloadStatistics.Insert(0, (int)((averageDownloadStatistics + downloadStatisticsRest) / (downloadStatistics.Count + downloadStatisticsRestCount)));

                    if (uploadStatistics.Count == 300)
                    {
                        uploadStatisticsRestCount++;
                        uploadStatisticsRest += uploadStatistics[uploadStatistics.Count - 1];
                        uploadStatistics.RemoveAt(uploadStatistics.Count - 1);
                    }
                    uploadStatistics.Insert(0, upstream);
                    if (m_MinuteAverageUploadStatistics.Count != 0)
                    {
                        averageUploadStatistics = 0;
                        for (int n = 0; n < Math.Min(60, uploadStatistics.Count); n++)
                            averageUploadStatistics += uploadStatistics[n];
                        if (m_MinuteAverageUploadStatistics.Count == 300)
                            m_MinuteAverageUploadStatistics.RemoveAt(m_MinuteAverageUploadStatistics.Count - 1);
                        m_MinuteAverageUploadStatistics.Insert(0, (int)(averageUploadStatistics / Math.Min(60, m_MinuteAverageUploadStatistics.Count)));
                    }
                    else
                        m_MinuteAverageUploadStatistics.Insert(0, 0);
                    averageUploadStatistics = 0;
                    foreach (int item in uploadStatistics)
                        averageUploadStatistics += item;
                    if (m_AverageUploadStatistics.Count == 300)
                        m_AverageUploadStatistics.RemoveAt(m_AverageUploadStatistics.Count - 1);
                    m_AverageUploadStatistics.Insert(0, (int)((averageUploadStatistics + uploadStatisticsRest) / (uploadStatistics.Count + uploadStatisticsRestCount)));

                    if (m_ConnectionsStatistics.Count == 300)
                        m_ConnectionsStatistics.RemoveAt(m_ConnectionsStatistics.Count - 1);
                    m_ConnectionsStatistics.Insert(0, m_Connections.Count);

                    Thread.Sleep(1000);
                }
            });
            statisticsThread.Name = "statisticsThread";
            statisticsThread.IsBackground = true;
            statisticsThread.Start();

            Thread lastCommandIDThread = new Thread(delegate()
            {
                while (!m_IsClosing)
                {
                    try
                    {
                        m_LastCommandID.Lock();
                        for (int n = m_LastCommandID.Count - 1; n >= 0; n--)
                            if (DateTime.Now.Subtract(m_LastCommandID[n].Value).TotalSeconds >= Constants.LastCommandIDTimeout)
                                m_LastCommandID.RemoveAt(n);
                    }
                    catch
                    {
                    }
                    finally
                    {
                        m_LastCommandID.Unlock();
                    }
                    Thread.Sleep(1000);
                }
            });
            lastCommandIDThread.Name = "lastCommandIDThread";
            lastCommandIDThread.IsBackground = true;
            lastCommandIDThread.Start();

            Thread connectionsThread = new Thread(delegate()
            {
                while (!m_IsClosing)
                {
                    try
                    {
                        m_Connections.Lock();
                        Connection connection;

                        /* Sum up the total bandwidth used during the last second and
                         * calculate an adjustment, so that the predicted bandwidth for this second
                         * will not exceeded the allowed bandwidth limit.
                         */
                        int uploadAdjustment = 0;
                        int downloadAdjustment = 0;

                        if ((bool.Parse(Settings.Instance["HasUploadLimit"]) ||
                            bool.Parse(Settings.Instance["HasDownloadLimit"])) &&
                            Core.Connections.Count != 0)
                        {
                            int totalUp = 0;
                            int totalDown = 0;
                            for (int n = m_Connections.Count - 1; n >= 0; n--)
                            {
                                connection = m_Connections[n].Value;
                                totalUp += connection.UploadLimitUsed;
                                totalDown += connection.DownloadLimitUsed;
                            }
                            uploadAdjustment = (int)((float)(int.Parse(Settings.Instance["UploadLimit"]) - totalUp) / Core.Connections.Count);
                            downloadAdjustment = (int)((float)(int.Parse(Settings.Instance["DownloadLimit"]) - totalDown) / Core.Connections.Count);
                        }

                        for (int n = m_Connections.Count - 1; n >= 0; n--)
                        {
                            connection = m_Connections[n].Value;
                            if (connection.IsDisconnected)
                                m_Connections.RemoveAt(n);
                            else
                            {
                                connection.UploadAdjustment = uploadAdjustment;
                                connection.DownloadAdjustment = downloadAdjustment;
                                connection.Process();
                            }
                        }
                    }
                    catch
                    {
                    }
                    finally
                    {
                        m_Connections.Unlock();
                    }
                    Thread.Sleep(1000);
                }
            });
            connectionsThread.Name = "connectionsThread";
            connectionsThread.IsBackground = true;
            connectionsThread.Start();

            Thread peersThread = new Thread(delegate()
            {
                while (!m_IsClosing)
                {
                    try
                    {
                        m_Peers.Lock();
                        Peer peer;
                        for (int n = m_Peers.Count - 1; n >= 0; n--)
                        {
                            peer = m_Peers[n].Value;
                            if (DateTime.Now.Subtract(peer.LastReceived).TotalSeconds >= Constants.PeerTimeout)
                                m_Peers.RemoveAt(n);
                            else
                                peer.Process();
                        }
                    }
                    catch
                    {
                    }
                    finally
                    {
                        m_Peers.Unlock();
                    }
                    Thread.Sleep(1000);
                }
            });
            peersThread.Name = "peersThread";
            peersThread.IsBackground = true;
            peersThread.Start();

            Thread searchesThread = new Thread(delegate()
            {
                while (!m_IsClosing)
                {
                    try
                    {
                        foreach (Search search in m_Searches.Values)
                            search.Process();
                    }
                    catch
                    {
                    }
                    Thread.Sleep(1000);
                }
            });
            searchesThread.Name = "searchesThread";
            searchesThread.IsBackground = true;
            searchesThread.Start();

            // 06.07.2009 Auto-Move re-implemented (Lars)
            Thread downloadsThread = new Thread(delegate()
            {
                int moveIntervall = 60;
                bool moveDownloads = false;
                try
                {
                    moveIntervall = Int32.Parse(Settings.Instance["AutoMoveDownloadsIntervall"]);
                    if (moveIntervall < 60)
                        moveIntervall = 60;
                    moveDownloads = bool.Parse(Settings.Instance["AutoMoveDownloads"]);
                }
                catch (Exception ex)
                {
                    m_Logger.Log(ex, "An exception was thrown while initializing Auto-Move!");
                }
                while (!m_IsClosing)
                {
                    try
                    {
                        m_DownloadsAndQueue.Lock();
                        Download download;
                        for (int n = Math.Min(m_DownloadsAndQueue.Count, Constants.MaximumDownloadsCount) - 1; n >= 0; n--)
                        {
                            download = m_DownloadsAndQueue[n].Value;
                            if (moveDownloads)
                            {
                                // Wir verschieben Downloads
                                if ((download.LastReception == null || !download.LastReception.HasValue || DateTime.Now.Subtract(download.LastReception.Value).TotalMinutes >= moveIntervall) &&
                                    (download.QueueStart != null && download.QueueStart.HasValue && DateTime.Now.Subtract(download.QueueStart.Value).TotalMinutes >= moveIntervall))
                                {
                                    // Unser Download hat länger als moveIntervall nichts empfangen und
                                    // ist bereits länger als moveIntervall gestartet
                                    bool flag = false;
                                    foreach (Download.Source source in download.Sources.Values)
                                        if (source.State == Download.SourceState.Active || source.State == Download.SourceState.Requested)
                                        {
                                            flag = true;
                                            break;
                                        }
                                    if (!flag && m_DownloadsAndQueue.Count > Constants.MaximumDownloadsCount)
                                    {
                                        // Der Download wird in die Queue verschoben
                                        MoveDownloadToQueue(download.DownloadIDString);
                                        m_Logger.Log("Auto-Move: The download of \"{0}\" has been moved to the queue!", download.FileName);
                                    }
                                    else
                                    {
                                        // Der Download hat geeignete Quellen und wird daher nicht verschoben
                                        download.Process();
                                    }
                                }
                                else
                                {
                                    // Unser Download empfängt oder das moveIntervall wurde noch nicht erreicht
                                    download.Process();
                                }
                            }
                            else
                            {
                                // Wir verschieben keine Downloads
                                download.Process();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        m_Logger.Log(ex, "An exception was thrown while processing downloads!");
                    }
                    finally
                    {
                        m_DownloadsAndQueue.Unlock();
                    }
                    Thread.Sleep(1000);
                }
            });
            downloadsThread.Name = "downloadsThread";
            downloadsThread.IsBackground = true;
            downloadsThread.Start();

            Thread uploadsThread = new Thread(delegate()
            {
                while (!m_IsClosing)
                {
                    try
                    {
                        m_Uploads.Lock();
                        Upload upload;
                        for (int n = m_Uploads.Count - 1; n >= 0; n--)
                        {
                            upload = m_Uploads[n].Value;
                            if (DateTime.Now.Subtract(upload.LastRequest).TotalSeconds >= Constants.UploadTimeout)
                                m_Uploads.RemoveAt(n);
                            upload.Process();
                        }
                    }
                    catch
                    {
                    }
                    finally
                    {
                        m_Uploads.Unlock();
                    }
                    Thread.Sleep(1000);
                }
            });
            uploadsThread.Name = "uploadsThread";
            uploadsThread.IsBackground = true;
            uploadsThread.Start();

            Thread listeningThread = new Thread(delegate()
            {
                try
                {
                    Socket listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    listeningSocket.Bind(new IPEndPoint(IPAddress.Any, int.Parse(Settings.Instance["Port"])));
                    listeningSocket.Listen(5);
                    while (!m_IsClosing)
                    {
                        try
                        {
                            Connection connection = new Connection(listeningSocket.Accept());
                            m_IsAccessible = true;
                            //2008-09-17 : Nochbaer
                            int avgConCount = int.Parse(Settings.Instance["AverageConnectionsCount"]);
                            if (avgConCount > 10) avgConCount = 10;
                            if (m_Connections.Count < (int)((float)avgConCount * 1.25F) && !m_Connections.ContainsKey(connection.RemoteEndPoint.Address))
                            {
                                m_Connections.Add(connection.RemoteEndPoint.Address, connection);
                                (new Command10(m_Keys)).Send(connection);
                            }
                            else
                                connection.Disconnect();
                        }
                        catch
                        {
                        }
                    }
                    try
                    {
                        listeningSocket.Shutdown(SocketShutdown.Both);
                    }
                    catch
                    {
                    }
                    try
                    {
                        listeningSocket.Close();
                    }
                    catch
                    {
                    }
                }
                catch (Exception ex)
                {
                    m_Logger.Log(ex, "An exception was thrown while binding socket at port {0}!", Settings.Instance["Port"]);
                }
            });
            listeningThread.Name = "listeningThread";
            listeningThread.IsBackground = true;
            listeningThread.Start();

            if (!m_WebCaches.IsEmpty)
            {
                try
                {
                    WebCacheProvider webCacheProvider = new WebCacheProvider(m_WebCaches);
                    try
                    {
                        webCacheProvider.RemovePeer();
                    }
                    catch
                    {
                    }
                    Thread webCacheAddOrRemovePeerThread = new Thread(delegate()
                    {
                        while (!m_IsClosing)
                        {
                            try
                            {
                                //2009-06-02 : Lars
                                int avgConCount = int.Parse(Settings.Instance["AverageConnectionsCount"]);
                                if (avgConCount > 10) avgConCount = 10;
                                if (m_Connections.Count < avgConCount)
                                    webCacheProvider.AddPeer(int.Parse(Settings.Instance["Port"]));
                            }
                            catch
                            {
                            }
                            for (int n = 0; !m_IsClosing && n < 120; n++)
                                Thread.Sleep(500);
                        }
                        try
                        {
                            webCacheProvider.RemovePeer();
                        }
                        catch
                        {
                        }
                    });
                    webCacheAddOrRemovePeerThread.Name = "webCacheAddOrRemovePeerThread";
                    webCacheAddOrRemovePeerThread.Start();
                    Thread webCacheGetPeerThread = new Thread(delegate()
                    {
                        while (!m_IsClosing)
                        {
                            try
                            {
                                //2008-09-17 : Nochbaer
                                int avgConCount = int.Parse(Settings.Instance["AverageConnectionsCount"]);
                                if (avgConCount > 10) avgConCount = 10;
                                while (m_Connections.Count < avgConCount && !m_IsClosing)
                                {
                                    string node = webCacheProvider.GetPeer();
                                    if (node == string.Empty)
                                        break;
                                    string[] endPoint = node.Split(':');
                                    AddConnection(new IPEndPoint(IPAddress.Parse(endPoint[0]), Convert.ToInt32(endPoint[1])));
                                    if (m_Connections.Count < avgConCount - 1)
                                        Thread.Sleep(15000);
                                    else
                                        break;
                                }
                            }
                            catch
                            {
                            }
                            Thread.Sleep(60000);
                        }
                    });
                    webCacheGetPeerThread.Name = "webCacheGetPeerThread";
                    webCacheGetPeerThread.IsBackground = true;
                    webCacheGetPeerThread.Start();
                }
                catch (Exception ex)
                {
                    m_Logger.Log("The WebCache's client could not be initialized properly!", ex);
                }
            }

            Thread OnlineSignatureThread = new Thread(delegate()
            {
                SetUILanguage();
                while (bool.Parse(Settings.Instance["ActivateOnlineSignature"]))
                {
                    try
                    {
                        XmlWriterSettings onlineSignatureXmlWriterSettings = new XmlWriterSettings();
                        onlineSignatureXmlWriterSettings.CloseOutput = true;
                        onlineSignatureXmlWriterSettings.Indent = true;
                        MemoryStream memoryStream = new MemoryStream();
                        XmlWriter onlineSignatureXmlWriter = XmlWriter.Create(memoryStream, onlineSignatureXmlWriterSettings);
                        onlineSignatureXmlWriter.WriteStartDocument();
                        onlineSignatureXmlWriter.WriteStartElement("onlinesignature");
                        onlineSignatureXmlWriter.WriteStartElement("software");
                        onlineSignatureXmlWriter.WriteValue(String.Format(Constants.Software, Core.Version));
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("connections");
                        onlineSignatureXmlWriter.WriteValue(m_Connections.Count);
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("downloads");
                        onlineSignatureXmlWriter.WriteValue(m_DownloadsAndQueue.Count);
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("downloadqueue");
                        onlineSignatureXmlWriter.WriteValue("0");
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("activeuploads");
                        onlineSignatureXmlWriter.WriteValue(m_Uploads.Count > Constants.MaximumUploadsCount ? Constants.MaximumUploadsCount : m_Uploads.Count);
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("uploads");
                        onlineSignatureXmlWriter.WriteValue(m_Uploads.Count);
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("sharedfiles");
                        onlineSignatureXmlWriter.WriteValue(m_ShareManager.SharedFiles.Count);
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("downloadcapacity");
                        onlineSignatureXmlWriter.WriteValue(Settings.Instance["DownloadCapacity"]);
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("uploadcapacity");
                        onlineSignatureXmlWriter.WriteValue(Settings.Instance["UploadCapacity"]);
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("downloadlimit");
                        onlineSignatureXmlWriter.WriteValue(bool.Parse(Settings.Instance["HasDownloadLimit"]) ? Settings.Instance["DownloadLimit"] : "0");
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("uploadlimit");
                        onlineSignatureXmlWriter.WriteValue(bool.Parse(Settings.Instance["HasUploadLimit"]) ? Settings.Instance["UploadLimit"] : "0");
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("language");
                        onlineSignatureXmlWriter.WriteValue(Settings.Instance["UICulture"]);
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("cumulativedownloaded");
                        onlineSignatureXmlWriter.WriteValue(m_CumulativeDownloaded);
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("cumulativeuploaded");
                        onlineSignatureXmlWriter.WriteValue(m_CumulativeUploaded);
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("downloaded");
                        onlineSignatureXmlWriter.WriteValue(m_Downloaded);
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("uploaded");
                        onlineSignatureXmlWriter.WriteValue(m_Uploaded);
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("downstream");
                        onlineSignatureXmlWriter.WriteValue(m_MinuteAverageDownloadStatistics[0].ToString());
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("upstream");
                        onlineSignatureXmlWriter.WriteValue(m_MinuteAverageUploadStatistics[0].ToString());
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("cumulativeuptime");
                        onlineSignatureXmlWriter.WriteValue(m_CumulativeUptime.ToString());
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteStartElement("uptime");
                        onlineSignatureXmlWriter.WriteValue(m_Uptime.ToString());
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.WriteEndElement();
                        onlineSignatureXmlWriter.Flush();
                        FileStream fileStream = new FileStream(Path.Combine(Settings.Instance["PreferencesDirectory"], "onlinesignature.xml"), FileMode.Create, FileAccess.Write, FileShare.Read);
                        byte[] buffer = memoryStream.ToArray();
                        fileStream.Write(buffer, 0, buffer.Length);
                        onlineSignatureXmlWriter.Close();
                        fileStream.Flush();
                        fileStream.Close();
                    }
                    catch (Exception ex)
                    {
                        m_Logger.Log(ex, Properties.Resources_Core.Exception_OnlineSignature);
                    }
                    Thread.Sleep(int.Parse(Settings.Instance["OnlineSignatureUpdateIntervall"]) * 60 * 1000);
                }
            });
            OnlineSignatureThread.Name = "onlineSignatureThread";
            OnlineSignatureThread.IsBackground = true;
            OnlineSignatureThread.Start();

            //2008-05-22-Eroli: Writing downloads.xml every 5 minutes to prevent loosing the sectorsMap if StealthNet crashes
            //2009-02-16 Nochbaer: Also statistics.xml
            Thread backupThread = new Thread(delegate()
            {
                DateTime lastDownloads = DateTime.MinValue;
                DateTime lastStatistics = DateTime.MinValue;
                while (!m_IsClosing)
                {
                    if (DownloadsXmlWriter.IsReady && DateTime.Now.Subtract(lastDownloads).TotalMinutes >= 5)
                    {
                        DownloadsXmlWriter.Write(m_DownloadsFilePath, m_DownloadsAndQueue);
                        lastDownloads = DateTime.Now;
                    }
                    if (DateTime.Now.Subtract(lastStatistics).TotalMinutes >= 5)
                    {
                        try
                        {
                            StatisticsXmlWriter.write(m_StatisticsFilePath, m_CumulativeDownloaded.ToString(), m_CumulativeUploaded.ToString(), m_CumulativeUptime.ToString());
                        }
                        catch (Exception ex)
                        {
                            m_Logger.Log(ex, "An exception was thrown while writing statistics.xml!");
                        }
                        if (m_ShareManager.IsReady)
                        {
                            try
                            {
                                m_ShareManager.SaveConfiguration(m_SharedDirectoriesFilePath, m_SharedFilesFilePath, m_SharedFilesStatsFilePath, m_MetaDataFilePath, m_CommentsFilePath, m_RatingsFilePath);
                            }
                            catch (Exception ex)
                            {
                                m_Logger.Log(ex, "An exception was thrown while writing shared files index!");
                            }
                        }
                        lastStatistics = DateTime.Now;
                    }
                    Thread.Sleep(60000);
                }
            });
            backupThread.Name = "backupThread";
            backupThread.IsBackground = true;
            backupThread.Start();

            Thread collectingThread = new Thread(delegate()
            {
                while (!m_IsClosing)
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    Thread.Sleep(60000);
                }
            });
            collectingThread.Name = "collectingThread";
            collectingThread.IsBackground = true;
            collectingThread.Start();

            m_Logger.Log(Properties.Resources_Core.StealthNetLoaded, String.Format(Constants.Software, Core.Version));
        }
Ejemplo n.º 3
0
 private static void SendBroadcast(IRequestCommand command, IPAddress excludedConnection, int dropChainTailCount)
 {
     if (command == null)
         throw new ArgumentNullException("command");
     try
     {
         m_Connections.Lock();
         RList<Connection> connections = new RList<Connection>();
         foreach (Connection connection in m_Connections.Values)
             if (connection.IsEstablished && !connection.RemoteEndPoint.Address.Equals(excludedConnection))
                 connections.Add(connection);
         dropChainTailCount = Math.Min(dropChainTailCount, connections.Count);
         for (int n = 0; n < dropChainTailCount; n++)
         {
             int index = Randomizer.GenerateNumber(0, connections.Count);
             command.Send(connections[index]);
             connections.RemoveAt(index);
         }
     }
     finally
     {
         m_Connections.Unlock();
     }
 }