public void Start() { Stop(); lock (_startStopSequence) { _adapters.ForEach(adapter => { _runningTasks.Add(adapter.StartCapturing()); }); _timer.Start(); Started?.Invoke(this, EventArgs.Empty); _capturingStartedAt = DateTime.Now; KaTaLyzerLogger.Log(LogLevel.Trace, "Worker started").Wait(); } lock (_tasksLock) { _runningTasks.ForEach(x => { x.Wait(); }); } _timer.Stop(); Stopped?.Invoke(this, EventArgs.Empty); KaTaLyzerLogger.Log(LogLevel.Trace, "Worker stopped").Wait(); }
private static void Main(string[] arguments) { Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); AppDomain.CurrentDomain.UnhandledException += (sender, args) => { KaTaLyzerLogger.Log(LogLevel.Fatal, (Exception)args.ExceptionObject).Wait(); }; new ArgumentsResolver().ResolveArguments(arguments, new LinuxPlatform()); }
public KaTaLyzerWorker(PlatformDependencies platformDependencies) { if (!ConfigurationManager.GetInstance().HasConfiguration()) { throw new InvalidOperationException("Can't start KaTaLyzer without configuration"); } _platformDependencies = platformDependencies; _networkAdaptersStatistics = new List <NetworkAdapterStatistics>(); _runningTasks = new List <Task>(); _adapters = ConfigurationManager.GetInstance().GetNetworkAdapterConfiguration().Select(configuration => { NetworkAdapter adapter = null; adapter = new NetworkAdapter(configuration, platformDependencies); adapter.PacketCaptured += ProcessPacket; adapter.ErrorOccured += AdapterErrorOccured; return(adapter); }).ToList(); ulong uploadedCount = 0; _timer = new Timer { Interval = ConfigurationManager.GetInstance().GetUploadInterval() * 1000 }; _timer.Elapsed += async(sender, eventArgs) => { var statisticsRepository = new StatisticsRepository(); try { await statisticsRepository.PersistStatistics(TakeNetworkAdaptersStatistics()); uploadedCount++; StatisticsPersisted?.Invoke(new StatisticsPersistedEventArgs(_capturingStartedAt, DateTime.Now, uploadedCount)); } catch (Exception e) { await KaTaLyzerLogger.Log(LogLevel.Error, e); Error?.Invoke(this, e); } }; }
public override List <PcapDevice> GetCurrentDevices() { try { LibPcapLiveDeviceList.Instance.Refresh(); return(new List <PcapDevice>(LibPcapLiveDeviceList.Instance.ToList()) .Where(device => device?.Interface?.FriendlyName != null).ToList()); } catch (Exception e) { KaTaLyzerLogger.Log(LogLevel.Fatal, e).Wait(); throw new Exception("Could not load network adapters. Check if you have installed libpcap library and you run KaTaLyzer as root."); } }
public async Task Start() { Stop(); if (!ConfigurationManager.GetInstance().IsConfigLoaded()) { await KaTaLyzerLogger.Log(LogLevel.Info, "No configuration file specified. Loading \"config.json\"."); ConfigurationManager.GetInstance().LoadDefaultConfig(); } _kaTaLyzerWorker = new KaTaLyzerWorker(_dependencies); _kaTaLyzerWorker.Start(); }
protected async void ProcessPacket(object networkAdapter, RawCapture rawCapture) { try { StatisticsRecord capturedPacket = rawCapture.ConvertToStatistics(); if (capturedPacket != null) { IncreaseStatistics(networkAdapter, capturedPacket); } } catch (Exception e) { await KaTaLyzerLogger.Log(LogLevel.Error, e, new KeyValuePair <string, object>("CapturedData", rawCapture.Data)); } }
public void LoadConfiguration(string filename) { if (File.Exists(filename)) { using (var reader = new StreamReader(filename)) { string json = reader.ReadToEnd(); _settings = JsonConvert.DeserializeObject <Settings>(json); _isConfigLoaded = true; _pathToCurrentConfig = filename; KaTaLyzerLogger.Log(LogLevel.Trace, "Configuration loaded").Wait(); } } else { throw new FileNotFoundException($"File \"{filename}\" was not found."); } }
public async Task StartCapturing() { _stopped = false; await Task.Run(() => { _device = _dependencies.GetActualDevice(_configuration.InterfaceFriendlyName); _device?.Open(DeviceMode.Promiscuous, 1000); while (!_stopped) { try { RawCapture rawPacket = _device.GetNextPacket(); if (rawPacket != null) { PacketCaptured?.Invoke(this, rawPacket); } } catch (Exception e) { //try refresh device if something has changed in pc settings var refreshedDevice = _dependencies.GetActualDevice(_configuration.InterfaceFriendlyName); if (refreshedDevice != null) { _device = refreshedDevice; _device.Open(DeviceMode.Promiscuous, 1000); } ErrorOccured?.Invoke(this, e); KaTaLyzerLogger.Log(LogLevel.Error, e, new KeyValuePair <string, object>("Adapter", this)).Wait(); } } _device?.Close(); }); }
public void ResolveArguments(string[] commandLineArguments, PlatformDependencies platform) { KaTaLyzerLogger.Log(LogLevel.Trace, "KaTaLyzer started", new KeyValuePair <string, object>("Arguments", commandLineArguments)).Wait(); if (commandLineArguments.Length == 0) { ConsoleUi.ConsoleUi consoleUi = new ConsoleUi.ConsoleUi(platform); consoleUi.ShowMainMenu(); } else { Parser parser = new Parser(settings => { settings.AutoHelp = false; }); parser.ParseArguments <CommandLineOptions>(commandLineArguments).WithParsed(options => { if (options.Help) { ConsoleUi.ConsoleUi consoleUi = new ConsoleUi.ConsoleUi(platform); consoleUi.ShowHelp(); Environment.Exit(0); } if (options.CreateConfigTemplate) { Settings templateSetting = new Settings() { DeviceName = "<DeviceName>", ServerAddress = "<http://localhost:31311>", MonitoredNetworkAdapters = platform.GetCurrentDevices().Select(x => new NetworkAdapterConfiguration { CustomName = x.Interface.FriendlyName, InterfaceFriendlyName = x.Interface.FriendlyName }).ToList(), UploadInterval = 60, MonitoredProtocols = ProtocolsLists.AllProtocols.ToDictionary(x => x, x => true) }; ConfigurationManager.GetInstance().SaveConfiguration(templateSetting, ConfigurationManager.DefaultConfigurationFilePath, true, null); Console.WriteLine($"Configuration \"{ConfigurationManager.DefaultConfigurationFilePath}\" created successful"); Environment.Exit(0); } else { if (!string.IsNullOrEmpty(options.PathToConfig)) { ConfigurationManager.GetInstance().LoadConfiguration(options.PathToConfig); } } if (options.RunInBackground) { platform.RunInBackground(); } else { ConsoleUi.ConsoleUi consoleUi = new ConsoleUi.ConsoleUi(platform); consoleUi.ShowMainMenu(); } }).WithNotParsed(errors => { ConsoleUi.ConsoleUi consoleUi = new ConsoleUi.ConsoleUi(platform); consoleUi.InvalidArgumentsWerePassed(); consoleUi.ShowHelp(); }); } }