You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ShadowsocksController.cs 24 kB

7 years ago
11 years ago
7 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
7 years ago
7 years ago
11 years ago
11 years ago
11 years ago
7 years ago
7 years ago
7 years ago
11 years ago
7 years ago
11 years ago
11 years ago
7 years ago
11 years ago
7 years ago
7 years ago
7 years ago
11 years ago
11 years ago
11 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
10 years ago
10 years ago
7 years ago
10 years ago
7 years ago
11 years ago
10 years ago
7 years ago
7 years ago
7 years ago
7 years ago
11 years ago
11 years ago
11 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Web;
  11. using System.Windows.Forms;
  12. using NLog;
  13. using Shadowsocks.Controller.Service;
  14. using Shadowsocks.Controller.Strategy;
  15. using Shadowsocks.Model;
  16. using Shadowsocks.Util;
  17. namespace Shadowsocks.Controller
  18. {
  19. public class ShadowsocksController
  20. {
  21. private static Logger logger = LogManager.GetCurrentClassLogger();
  22. // controller:
  23. // handle user actions
  24. // manipulates UI
  25. // interacts with low level logic
  26. private Thread _ramThread;
  27. private Thread _trafficThread;
  28. private Listener _listener;
  29. private PACDaemon _pacDaemon;
  30. private PACServer _pacServer;
  31. private Configuration _config;
  32. private StrategyManager _strategyManager;
  33. private PrivoxyRunner privoxyRunner;
  34. private GFWListUpdater gfwListUpdater;
  35. private readonly ConcurrentDictionary<Server, Sip003Plugin> _pluginsByServer;
  36. public AvailabilityStatistics availabilityStatistics = AvailabilityStatistics.Instance;
  37. public StatisticsStrategyConfiguration StatisticsConfiguration { get; private set; }
  38. private long _inboundCounter = 0;
  39. private long _outboundCounter = 0;
  40. public long InboundCounter => Interlocked.Read(ref _inboundCounter);
  41. public long OutboundCounter => Interlocked.Read(ref _outboundCounter);
  42. public Queue<TrafficPerSecond> trafficPerSecondQueue;
  43. private bool stopped = false;
  44. public class PathEventArgs : EventArgs
  45. {
  46. public string Path;
  47. }
  48. public class UpdatedEventArgs : EventArgs
  49. {
  50. public string OldVersion;
  51. public string NewVersion;
  52. }
  53. public class TrafficPerSecond
  54. {
  55. public long inboundCounter;
  56. public long outboundCounter;
  57. public long inboundIncreasement;
  58. public long outboundIncreasement;
  59. }
  60. public event EventHandler ConfigChanged;
  61. public event EventHandler EnableStatusChanged;
  62. public event EventHandler EnableGlobalChanged;
  63. public event EventHandler ShareOverLANStatusChanged;
  64. public event EventHandler VerboseLoggingStatusChanged;
  65. public event EventHandler ShowPluginOutputChanged;
  66. public event EventHandler TrafficChanged;
  67. // when user clicked Edit PAC, and PAC file has already created
  68. public event EventHandler<PathEventArgs> PACFileReadyToOpen;
  69. public event EventHandler<PathEventArgs> UserRuleFileReadyToOpen;
  70. public event EventHandler<GFWListUpdater.ResultEventArgs> UpdatePACFromGFWListCompleted;
  71. public event ErrorEventHandler UpdatePACFromGFWListError;
  72. public event ErrorEventHandler Errored;
  73. // Invoked when controller.Start();
  74. public event EventHandler<UpdatedEventArgs> ProgramUpdated;
  75. public ShadowsocksController()
  76. {
  77. _config = Configuration.Load();
  78. StatisticsConfiguration = StatisticsStrategyConfiguration.Load();
  79. _strategyManager = new StrategyManager(this);
  80. _pluginsByServer = new ConcurrentDictionary<Server, Sip003Plugin>();
  81. StartReleasingMemory();
  82. StartTrafficStatistics(61);
  83. ProgramUpdated += (o, e) =>
  84. {
  85. logger.Info($"Updated from {e.OldVersion} to {e.NewVersion}");
  86. };
  87. }
  88. public void Start(bool regHotkeys = true)
  89. {
  90. if (_config.updated && regHotkeys)
  91. {
  92. _config.updated = false;
  93. ProgramUpdated.Invoke(this, new UpdatedEventArgs()
  94. {
  95. OldVersion = _config.version,
  96. NewVersion = UpdateChecker.Version,
  97. });
  98. Configuration.Save(_config);
  99. }
  100. Reload();
  101. if (regHotkeys)
  102. {
  103. HotkeyReg.RegAllHotkeys();
  104. }
  105. }
  106. protected void ReportError(Exception e)
  107. {
  108. Errored?.Invoke(this, new ErrorEventArgs(e));
  109. }
  110. public Server GetCurrentServer()
  111. {
  112. return _config.GetCurrentServer();
  113. }
  114. // always return copy
  115. public Configuration GetConfigurationCopy()
  116. {
  117. return Configuration.Load();
  118. }
  119. // always return current instance
  120. public Configuration GetCurrentConfiguration()
  121. {
  122. return _config;
  123. }
  124. public IList<IStrategy> GetStrategies()
  125. {
  126. return _strategyManager.GetStrategies();
  127. }
  128. public IStrategy GetCurrentStrategy()
  129. {
  130. foreach (var strategy in _strategyManager.GetStrategies())
  131. {
  132. if (strategy.ID == _config.strategy)
  133. {
  134. return strategy;
  135. }
  136. }
  137. return null;
  138. }
  139. public Server GetAServer(IStrategyCallerType type, IPEndPoint localIPEndPoint, EndPoint destEndPoint)
  140. {
  141. IStrategy strategy = GetCurrentStrategy();
  142. if (strategy != null)
  143. {
  144. return strategy.GetAServer(type, localIPEndPoint, destEndPoint);
  145. }
  146. if (_config.index < 0)
  147. {
  148. _config.index = 0;
  149. }
  150. return GetCurrentServer();
  151. }
  152. public EndPoint GetPluginLocalEndPointIfConfigured(Server server)
  153. {
  154. var plugin = _pluginsByServer.GetOrAdd(
  155. server,
  156. x => Sip003Plugin.CreateIfConfigured(x, _config.showPluginOutput));
  157. if (plugin == null)
  158. {
  159. return null;
  160. }
  161. try
  162. {
  163. if (plugin.StartIfNeeded())
  164. {
  165. logger.Info(
  166. $"Started SIP003 plugin for {server.Identifier()} on {plugin.LocalEndPoint} - PID: {plugin.ProcessId}");
  167. }
  168. }
  169. catch (Exception ex)
  170. {
  171. logger.Error("Failed to start SIP003 plugin: " + ex.Message);
  172. throw;
  173. }
  174. return plugin.LocalEndPoint;
  175. }
  176. public void SaveServers(List<Server> servers, int localPort, bool portableMode)
  177. {
  178. _config.configs = servers;
  179. _config.localPort = localPort;
  180. _config.portableMode = portableMode;
  181. Configuration.Save(_config);
  182. }
  183. public void SaveStrategyConfigurations(StatisticsStrategyConfiguration configuration)
  184. {
  185. StatisticsConfiguration = configuration;
  186. StatisticsStrategyConfiguration.Save(configuration);
  187. }
  188. public bool AskAddServerBySSURL(string ssURL)
  189. {
  190. var dr = MessageBox.Show(I18N.GetString("Import from URL: {0} ?", ssURL), I18N.GetString("Shadowsocks"), MessageBoxButtons.YesNo);
  191. if (dr == DialogResult.Yes)
  192. {
  193. if (AddServerBySSURL(ssURL))
  194. {
  195. MessageBox.Show(I18N.GetString("Successfully imported from {0}", ssURL));
  196. return true;
  197. }
  198. else
  199. {
  200. MessageBox.Show(I18N.GetString("Failed to import. Please check if the link is valid."));
  201. }
  202. }
  203. return false;
  204. }
  205. public bool AddServerBySSURL(string ssURL)
  206. {
  207. try
  208. {
  209. if (ssURL.IsNullOrEmpty() || ssURL.IsWhiteSpace())
  210. return false;
  211. var servers = Server.GetServers(ssURL);
  212. if (servers == null || servers.Count == 0)
  213. return false;
  214. foreach (var server in servers)
  215. {
  216. _config.configs.Add(server);
  217. }
  218. _config.index = _config.configs.Count - 1;
  219. SaveConfig(_config);
  220. return true;
  221. }
  222. catch (Exception e)
  223. {
  224. logger.LogUsefulException(e);
  225. return false;
  226. }
  227. }
  228. public void ToggleEnable(bool enabled)
  229. {
  230. _config.enabled = enabled;
  231. SaveConfig(_config);
  232. EnableStatusChanged?.Invoke(this, new EventArgs());
  233. }
  234. public void ToggleGlobal(bool global)
  235. {
  236. _config.global = global;
  237. SaveConfig(_config);
  238. EnableGlobalChanged?.Invoke(this, new EventArgs());
  239. }
  240. public void ToggleShareOverLAN(bool enabled)
  241. {
  242. _config.shareOverLan = enabled;
  243. SaveConfig(_config);
  244. ShareOverLANStatusChanged?.Invoke(this, new EventArgs());
  245. }
  246. public void SaveProxy(ProxyConfig proxyConfig)
  247. {
  248. _config.proxy = proxyConfig;
  249. SaveConfig(_config);
  250. }
  251. public void ToggleVerboseLogging(bool enabled)
  252. {
  253. _config.isVerboseLogging = enabled;
  254. SaveConfig(_config);
  255. NLogConfig.LoadConfiguration(); // reload nlog
  256. VerboseLoggingStatusChanged?.Invoke(this, new EventArgs());
  257. }
  258. public void ToggleShowPluginOutput(bool enabled)
  259. {
  260. _config.showPluginOutput = enabled;
  261. SaveConfig(_config);
  262. ShowPluginOutputChanged?.Invoke(this, new EventArgs());
  263. }
  264. public void SelectServerIndex(int index)
  265. {
  266. _config.index = index;
  267. _config.strategy = null;
  268. SaveConfig(_config);
  269. }
  270. public void SelectStrategy(string strategyID)
  271. {
  272. _config.index = -1;
  273. _config.strategy = strategyID;
  274. SaveConfig(_config);
  275. }
  276. public void Stop()
  277. {
  278. if (stopped)
  279. {
  280. return;
  281. }
  282. stopped = true;
  283. if (_listener != null)
  284. {
  285. _listener.Stop();
  286. }
  287. StopPlugins();
  288. if (privoxyRunner != null)
  289. {
  290. privoxyRunner.Stop();
  291. }
  292. if (_config.enabled)
  293. {
  294. SystemProxy.Update(_config, true, null);
  295. }
  296. Encryption.RNG.Close();
  297. }
  298. private void StopPlugins()
  299. {
  300. foreach (var serverAndPlugin in _pluginsByServer)
  301. {
  302. serverAndPlugin.Value?.Dispose();
  303. }
  304. _pluginsByServer.Clear();
  305. }
  306. public void TouchPACFile()
  307. {
  308. string pacFilename = _pacDaemon.TouchPACFile();
  309. PACFileReadyToOpen?.Invoke(this, new PathEventArgs() { Path = pacFilename });
  310. }
  311. public void TouchUserRuleFile()
  312. {
  313. string userRuleFilename = _pacDaemon.TouchUserRuleFile();
  314. UserRuleFileReadyToOpen?.Invoke(this, new PathEventArgs() { Path = userRuleFilename });
  315. }
  316. public string GetServerURLForCurrentServer()
  317. {
  318. Server server = GetCurrentServer();
  319. return GetServerURL(server);
  320. }
  321. public static string GetServerURL(Server server)
  322. {
  323. string tag = string.Empty;
  324. string url = string.Empty;
  325. if (string.IsNullOrWhiteSpace(server.plugin))
  326. {
  327. // For backwards compatiblity, if no plugin, use old url format
  328. string parts = $"{server.method}:{server.password}@{server.server}:{server.server_port}";
  329. string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(parts));
  330. url = base64;
  331. }
  332. else
  333. {
  334. // SIP002
  335. string parts = $"{server.method}:{server.password}";
  336. string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(parts));
  337. string websafeBase64 = base64.Replace('+', '-').Replace('/', '_').TrimEnd('=');
  338. string pluginPart = server.plugin;
  339. if (!string.IsNullOrWhiteSpace(server.plugin_opts))
  340. {
  341. pluginPart += ";" + server.plugin_opts;
  342. }
  343. url = string.Format(
  344. "{0}@{1}:{2}/?plugin={3}",
  345. websafeBase64,
  346. server.FormatHostName(server.server),
  347. server.server_port,
  348. HttpUtility.UrlEncode(pluginPart, Encoding.UTF8));
  349. }
  350. if (!server.remarks.IsNullOrEmpty())
  351. {
  352. tag = $"#{HttpUtility.UrlEncode(server.remarks, Encoding.UTF8)}";
  353. }
  354. return $"ss://{url}{tag}";
  355. }
  356. public void UpdatePACFromGFWList()
  357. {
  358. if (gfwListUpdater != null)
  359. {
  360. gfwListUpdater.UpdatePACFromGFWList(_config);
  361. }
  362. }
  363. public void UpdateStatisticsConfiguration(bool enabled)
  364. {
  365. if (availabilityStatistics != null)
  366. {
  367. availabilityStatistics.UpdateConfiguration(this);
  368. _config.availabilityStatistics = enabled;
  369. SaveConfig(_config);
  370. }
  371. }
  372. public void SavePACUrl(string pacUrl)
  373. {
  374. _config.pacUrl = pacUrl;
  375. SaveConfig(_config);
  376. ConfigChanged?.Invoke(this, new EventArgs());
  377. }
  378. public void UseOnlinePAC(bool useOnlinePac)
  379. {
  380. _config.useOnlinePac = useOnlinePac;
  381. SaveConfig(_config);
  382. ConfigChanged?.Invoke(this, new EventArgs());
  383. }
  384. public void ToggleSecureLocalPac(bool enabled)
  385. {
  386. _config.secureLocalPac = enabled;
  387. SaveConfig(_config);
  388. ConfigChanged?.Invoke(this, new EventArgs());
  389. }
  390. public void ToggleCheckingUpdate(bool enabled)
  391. {
  392. _config.autoCheckUpdate = enabled;
  393. Configuration.Save(_config);
  394. ConfigChanged?.Invoke(this, new EventArgs());
  395. }
  396. public void ToggleCheckingPreRelease(bool enabled)
  397. {
  398. _config.checkPreRelease = enabled;
  399. Configuration.Save(_config);
  400. ConfigChanged?.Invoke(this, new EventArgs());
  401. }
  402. public void SaveLogViewerConfig(LogViewerConfig newConfig)
  403. {
  404. _config.logViewer = newConfig;
  405. newConfig.SaveSize();
  406. Configuration.Save(_config);
  407. ConfigChanged?.Invoke(this, new EventArgs());
  408. }
  409. public void SaveHotkeyConfig(HotkeyConfig newConfig)
  410. {
  411. _config.hotkey = newConfig;
  412. SaveConfig(_config);
  413. ConfigChanged?.Invoke(this, new EventArgs());
  414. }
  415. public void UpdateLatency(object sender, SSTCPConnectedEventArgs args)
  416. {
  417. GetCurrentStrategy()?.UpdateLatency(args.server, args.latency);
  418. if (_config.availabilityStatistics)
  419. {
  420. availabilityStatistics.UpdateLatency(args.server, (int)args.latency.TotalMilliseconds);
  421. }
  422. }
  423. public void UpdateInboundCounter(object sender, SSTransmitEventArgs args)
  424. {
  425. GetCurrentStrategy()?.UpdateLastRead(args.server);
  426. Interlocked.Add(ref _inboundCounter, args.length);
  427. if (_config.availabilityStatistics)
  428. {
  429. availabilityStatistics.UpdateInboundCounter(args.server, args.length);
  430. }
  431. }
  432. public void UpdateOutboundCounter(object sender, SSTransmitEventArgs args)
  433. {
  434. GetCurrentStrategy()?.UpdateLastWrite(args.server);
  435. Interlocked.Add(ref _outboundCounter, args.length);
  436. if (_config.availabilityStatistics)
  437. {
  438. availabilityStatistics.UpdateOutboundCounter(args.server, args.length);
  439. }
  440. }
  441. protected void Reload()
  442. {
  443. Encryption.RNG.Reload();
  444. // some logic in configuration updated the config when saving, we need to read it again
  445. _config = Configuration.Load();
  446. NLogConfig.LoadConfiguration();
  447. StatisticsConfiguration = StatisticsStrategyConfiguration.Load();
  448. privoxyRunner = privoxyRunner ?? new PrivoxyRunner();
  449. _pacDaemon = _pacDaemon ?? new PACDaemon();
  450. _pacDaemon.PACFileChanged += PacDaemon_PACFileChanged;
  451. _pacDaemon.UserRuleFileChanged += PacDaemon_UserRuleFileChanged;
  452. _pacServer = _pacServer ?? new PACServer(_pacDaemon);
  453. _pacServer.UpdatePACURL(_config); // So PACServer works when system proxy disabled.
  454. gfwListUpdater = gfwListUpdater ?? new GFWListUpdater();
  455. gfwListUpdater.UpdateCompleted += PacServer_PACUpdateCompleted;
  456. gfwListUpdater.Error += PacServer_PACUpdateError;
  457. availabilityStatistics.UpdateConfiguration(this);
  458. _listener?.Stop();
  459. StopPlugins();
  460. // don't put PrivoxyRunner.Start() before pacServer.Stop()
  461. // or bind will fail when switching bind address from 0.0.0.0 to 127.0.0.1
  462. // though UseShellExecute is set to true now
  463. // http://stackoverflow.com/questions/10235093/socket-doesnt-close-after-application-exits-if-a-launched-process-is-open
  464. privoxyRunner.Stop();
  465. try
  466. {
  467. var strategy = GetCurrentStrategy();
  468. strategy?.ReloadServers();
  469. StartPlugin();
  470. privoxyRunner.Start(_config);
  471. TCPRelay tcpRelay = new TCPRelay(this, _config);
  472. tcpRelay.OnConnected += UpdateLatency;
  473. tcpRelay.OnInbound += UpdateInboundCounter;
  474. tcpRelay.OnOutbound += UpdateOutboundCounter;
  475. tcpRelay.OnFailed += (o, e) => GetCurrentStrategy()?.SetFailure(e.server);
  476. UDPRelay udpRelay = new UDPRelay(this);
  477. List<Listener.IService> services = new List<Listener.IService>
  478. {
  479. tcpRelay,
  480. udpRelay,
  481. _pacServer,
  482. new PortForwarder(privoxyRunner.RunningPort)
  483. };
  484. _listener = new Listener(services);
  485. _listener.Start(_config);
  486. }
  487. catch (Exception e)
  488. {
  489. // translate Microsoft language into human language
  490. // i.e. An attempt was made to access a socket in a way forbidden by its access permissions => Port already in use
  491. if (e is SocketException se)
  492. {
  493. if (se.SocketErrorCode == SocketError.AddressAlreadyInUse)
  494. {
  495. e = new Exception(I18N.GetString("Port {0} already in use", _config.localPort), e);
  496. }
  497. else if (se.SocketErrorCode == SocketError.AccessDenied)
  498. {
  499. e = new Exception(I18N.GetString("Port {0} is reserved by system", _config.localPort), e);
  500. }
  501. }
  502. logger.LogUsefulException(e);
  503. ReportError(e);
  504. }
  505. ConfigChanged?.Invoke(this, new EventArgs());
  506. UpdateSystemProxy();
  507. Utils.ReleaseMemory(true);
  508. }
  509. private void StartPlugin()
  510. {
  511. var server = _config.GetCurrentServer();
  512. GetPluginLocalEndPointIfConfigured(server);
  513. }
  514. protected void SaveConfig(Configuration newConfig)
  515. {
  516. Configuration.Save(newConfig);
  517. Reload();
  518. }
  519. private void UpdateSystemProxy()
  520. {
  521. SystemProxy.Update(_config, false, _pacServer);
  522. }
  523. private void PacDaemon_PACFileChanged(object sender, EventArgs e)
  524. {
  525. UpdateSystemProxy();
  526. }
  527. private void PacServer_PACUpdateCompleted(object sender, GFWListUpdater.ResultEventArgs e)
  528. {
  529. UpdatePACFromGFWListCompleted?.Invoke(this, e);
  530. }
  531. private void PacServer_PACUpdateError(object sender, ErrorEventArgs e)
  532. {
  533. UpdatePACFromGFWListError?.Invoke(this, e);
  534. }
  535. private static readonly IEnumerable<char> IgnoredLineBegins = new[] { '!', '[' };
  536. private void PacDaemon_UserRuleFileChanged(object sender, EventArgs e)
  537. {
  538. if (!File.Exists(Utils.GetTempPath("gfwlist.txt")))
  539. {
  540. UpdatePACFromGFWList();
  541. }
  542. else
  543. {
  544. GFWListUpdater.MergeAndWritePACFile(FileManager.NonExclusiveReadAllText(Utils.GetTempPath("gfwlist.txt")));
  545. }
  546. UpdateSystemProxy();
  547. }
  548. public void CopyPacUrl()
  549. {
  550. Clipboard.SetDataObject(_pacServer.PacUrl);
  551. }
  552. #region Memory Management
  553. private void StartReleasingMemory()
  554. {
  555. _ramThread = new Thread(new ThreadStart(ReleaseMemory))
  556. {
  557. IsBackground = true
  558. };
  559. _ramThread.Start();
  560. }
  561. private void ReleaseMemory()
  562. {
  563. while (true)
  564. {
  565. Utils.ReleaseMemory(false);
  566. Thread.Sleep(30 * 1000);
  567. }
  568. }
  569. #endregion
  570. #region Traffic Statistics
  571. private void StartTrafficStatistics(int queueMaxSize)
  572. {
  573. trafficPerSecondQueue = new Queue<TrafficPerSecond>();
  574. for (int i = 0; i < queueMaxSize; i++)
  575. {
  576. trafficPerSecondQueue.Enqueue(new TrafficPerSecond());
  577. }
  578. _trafficThread = new Thread(new ThreadStart(() => TrafficStatistics(queueMaxSize)))
  579. {
  580. IsBackground = true
  581. };
  582. _trafficThread.Start();
  583. }
  584. private void TrafficStatistics(int queueMaxSize)
  585. {
  586. TrafficPerSecond previous, current;
  587. while (true)
  588. {
  589. previous = trafficPerSecondQueue.Last();
  590. current = new TrafficPerSecond
  591. {
  592. inboundCounter = InboundCounter,
  593. outboundCounter = OutboundCounter
  594. };
  595. current.inboundIncreasement = current.inboundCounter - previous.inboundCounter;
  596. current.outboundIncreasement = current.outboundCounter - previous.outboundCounter;
  597. trafficPerSecondQueue.Enqueue(current);
  598. if (trafficPerSecondQueue.Count > queueMaxSize)
  599. trafficPerSecondQueue.Dequeue();
  600. TrafficChanged?.Invoke(this, new EventArgs());
  601. Thread.Sleep(1000);
  602. }
  603. }
  604. #endregion
  605. }
  606. }