From ec320a732d7e2fbe6eb7b5339bef434fbd80787d Mon Sep 17 00:00:00 2001 From: easly1989 Date: Mon, 11 Nov 2019 14:25:58 +0100 Subject: [PATCH] Using Machine.FFXIV from @ravahn - Removed unused network handling classes - Fixed status update message during matching in FFXIVPacketHandler - Removed unused methods from IPacketHandler - Removed state enum as it was only used locally --- DFAssist.Contracts/DFAssist.Contracts.csproj | 1 - DFAssist.Contracts/Duty/MatchingState.cs | 11 - DFAssist.Contracts/IPacketHandler.cs | 9 +- DFAssist.Core/DFAssist.Core.csproj | 10 +- DFAssist.Core/Network/Connection.cs | 37 -- DFAssist.Core/Network/FFXIVPacketHandler.cs | 150 +------- DFAssist.Core/Network/IpPacket.cs | 55 --- DFAssist.Core/Network/Network.cs | 345 ------------------ DFAssist.Core/Network/ProcessNetwork.cs | 16 - DFAssist.Core/Network/TcpFlags.cs | 23 -- DFAssist.Core/Network/TcpPacket.cs | 48 --- DFAssist.Core/Network/TcpRow.cs | 16 - DFAssist.Core/Network/TcpTable.cs | 11 - DFAssist/DFAssist.Plugin.csproj | 5 +- DFAssist/Helpers/FFXIVNetworkProcessHelper.cs | 129 ++----- 15 files changed, 48 insertions(+), 818 deletions(-) delete mode 100644 DFAssist.Contracts/Duty/MatchingState.cs delete mode 100644 DFAssist.Core/Network/Connection.cs delete mode 100644 DFAssist.Core/Network/IpPacket.cs delete mode 100644 DFAssist.Core/Network/Network.cs delete mode 100644 DFAssist.Core/Network/ProcessNetwork.cs delete mode 100644 DFAssist.Core/Network/TcpFlags.cs delete mode 100644 DFAssist.Core/Network/TcpPacket.cs delete mode 100644 DFAssist.Core/Network/TcpRow.cs delete mode 100644 DFAssist.Core/Network/TcpTable.cs diff --git a/DFAssist.Contracts/DFAssist.Contracts.csproj b/DFAssist.Contracts/DFAssist.Contracts.csproj index 55d34ed..913767d 100644 --- a/DFAssist.Contracts/DFAssist.Contracts.csproj +++ b/DFAssist.Contracts/DFAssist.Contracts.csproj @@ -65,7 +65,6 @@ - diff --git a/DFAssist.Contracts/Duty/MatchingState.cs b/DFAssist.Contracts/Duty/MatchingState.cs deleted file mode 100644 index 2ab5428..0000000 --- a/DFAssist.Contracts/Duty/MatchingState.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace DFAssist.Contracts.Duty -{ - public enum MatchingState - { - // ReSharper disable UnusedMember.Global - IDLE, - QUEUED, - MATCHED, - // ReSharper restore UnusedMember.Global - } -} \ No newline at end of file diff --git a/DFAssist.Contracts/IPacketHandler.cs b/DFAssist.Contracts/IPacketHandler.cs index 9d7dd91..3b260e6 100644 --- a/DFAssist.Contracts/IPacketHandler.cs +++ b/DFAssist.Contracts/IPacketHandler.cs @@ -1,13 +1,10 @@ -using DFAssist.Contracts.Duty; +using System; +using DFAssist.Contracts.Duty; namespace DFAssist.Contracts { - public delegate void PacketDelegate(int pid, EventType eventType, int[] args); - public interface IPacketHandler { - event PacketDelegate OnEventReceived; - - void Analyze(int processId, byte[] payload, ref MatchingState state); + void HandleMessage(byte[] message, Action fireEvent); } } diff --git a/DFAssist.Core/DFAssist.Core.csproj b/DFAssist.Core/DFAssist.Core.csproj index 97d9129..bf52dd2 100644 --- a/DFAssist.Core/DFAssist.Core.csproj +++ b/DFAssist.Core/DFAssist.Core.csproj @@ -68,15 +68,7 @@ - - - - - - - - @@ -95,7 +87,7 @@ - 12.0.2 + 12.0.3 9.1.1 diff --git a/DFAssist.Core/Network/Connection.cs b/DFAssist.Core/Network/Connection.cs deleted file mode 100644 index 891a539..0000000 --- a/DFAssist.Core/Network/Connection.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System.Net; - -namespace DFAssist.Core.Network -{ - public class Connection - { - public IPEndPoint LocalEndPoint { get; set; } - public IPEndPoint RemoteEndPoint { get; set; } - - public override bool Equals(object obj) - { - if (obj == null || GetType() != obj.GetType()) - { - return false; - } - - var connection = obj as Connection; - - return LocalEndPoint.Equals(connection?.LocalEndPoint) && RemoteEndPoint.Equals(connection?.RemoteEndPoint); - } - - public override int GetHashCode() - { - // ReSharper disable NonReadonlyMemberInGetHashCode - if (LocalEndPoint == null | RemoteEndPoint == null) - return -1; - - return (LocalEndPoint.GetHashCode() + 0x0609) ^ RemoteEndPoint.GetHashCode(); - // ReSharper restore NonReadonlyMemberInGetHashCode - } - - public override string ToString() - { - return $"{LocalEndPoint} -> {RemoteEndPoint}"; - } - } -} \ No newline at end of file diff --git a/DFAssist.Core/Network/FFXIVPacketHandler.cs b/DFAssist.Core/Network/FFXIVPacketHandler.cs index e229b99..1b2e9e7 100644 --- a/DFAssist.Core/Network/FFXIVPacketHandler.cs +++ b/DFAssist.Core/Network/FFXIVPacketHandler.cs @@ -1,6 +1,4 @@ using System; -using System.IO; -using System.IO.Compression; using System.Linq; using DFAssist.Contracts; using DFAssist.Contracts.Duty; @@ -13,12 +11,9 @@ namespace DFAssist.Core.Network public class FFXIVPacketHandler : IPacketHandler // ReSharper restore InconsistentNaming { - public event PacketDelegate OnEventReceived; - private readonly ILogger _logger; private readonly IDataRepository _dataRepository; - private int _lastMember; private byte _rouletteCode; public FFXIVPacketHandler() @@ -27,111 +22,7 @@ public FFXIVPacketHandler() _dataRepository = Locator.Current.GetService(); } - public void Analyze(int processId, byte[] payload, ref MatchingState state) - { - try - { - while (true) - { - if (payload.Length < 4) - break; - - var type = BitConverter.ToUInt16(payload, 0); - if (type == 0x0000 || type == 0x5252) - { - if (payload.Length < 28) - break; - - var length = BitConverter.ToInt32(payload, 24); - if (length <= 0 || payload.Length < length) - break; - - using (var messages = new MemoryStream(payload.Length)) - { - using (var stream = new MemoryStream(payload, 0, length)) - { - stream.Seek(40, SeekOrigin.Begin); - - if (payload[33] == 0x00) - { - stream.CopyTo(messages); - } - else - { - // .Net DeflateStream (Force the previous 2 bytes) - stream.Seek(2, SeekOrigin.Current); - using (var z = new DeflateStream(stream, CompressionMode.Decompress)) - { - z.CopyTo(messages); - } - } - } - - messages.Seek(0, SeekOrigin.Begin); - - var messageCount = BitConverter.ToUInt16(payload, 30); - for (var i = 0; i < messageCount; i++) - { - try - { - var buffer = new byte[4]; - var read = messages.Read(buffer, 0, 4); - if (read < 4) - { - _logger.Write( - $"A: Length Error while analyzing Message: {read} {i}/{messageCount}", - LogLevel.Error); - break; - } - - var messageLength = BitConverter.ToInt32(buffer, 0); - - var message = new byte[messageLength]; - messages.Seek(-4, SeekOrigin.Current); - messages.Read(message, 0, messageLength); - - HandleMessage(processId, message, ref state); - } - catch (Exception ex) - { - _logger.Write(ex, "A: Error while analyzing Message", LogLevel.Error); - } - } - } - - if (length < payload.Length) - { - // Packets still need to be processed - payload = payload.Skip(length).ToArray(); - continue; - } - } - else - { - // Forward-Cut packet workaround - // Discard one truncated packet and find just the next packet - for (var offset = 0; offset < payload.Length - 2; offset++) - { - var possibleType = BitConverter.ToUInt16(payload, offset); - if (possibleType != 0x5252) - continue; - - payload = payload.Skip(offset).ToArray(); - Analyze(processId, payload, ref state); - break; - } - } - - break; - } - } - catch (Exception ex) - { - _logger.Write(ex, "A: Error while handling Message", LogLevel.Error); - } - } - - private void HandleMessage(int pid, byte[] message, ref MatchingState state) + public void HandleMessage(byte[] message, Action fireEvent) { try { @@ -177,14 +68,6 @@ private void HandleMessage(int pid, byte[] message, ref MatchingState state) } else if (opcode == 0x008F) // 5.1 Duties { - // ReSharper disable UnusedVariable - var status = data[0]; - var reason = data[4]; - // ReSharper restore UnusedVariable - - state = MatchingState.QUEUED; - - _rouletteCode = data[20]; _rouletteCode = data[8]; if (_rouletteCode != 0 && (data[15] == 0 || data[15] == 64)) // Roulette, on Korean Server || on Global Server @@ -210,8 +93,7 @@ private void HandleMessage(int pid, byte[] message, ref MatchingState state) var matchedRoulette = BitConverter.ToUInt16(data, 2); var matchedCode = BitConverter.ToUInt16(data, 20); - state = MatchingState.MATCHED; - FireEvent(pid, EventType.MATCH_ALERT, new int[] { matchedRoulette, matchedCode }); + fireEvent?.Invoke(EventType.MATCH_ALERT, new int[] { matchedRoulette, matchedCode }); var instanceString = $"{matchedCode} - {_dataRepository.GetInstance(matchedCode).Name}"; _logger.Write(matchedRoulette != 0 @@ -226,8 +108,6 @@ private void HandleMessage(int pid, byte[] message, ref MatchingState state) { if (data[3] != 0) return; - state = MatchingState.IDLE; - _logger.Write("Duty Canceled!", LogLevel.Debug); } else if (opcode == 0x0121) @@ -246,25 +126,8 @@ private void HandleMessage(int pid, byte[] message, ref MatchingState state) var dps = data[12]; var dpsMax = data[13]; // ReSharper restore UnusedVariable - - var member = tank * 10000 + dps * 100 + healer; - - switch (state) - { - case MatchingState.MATCHED when _lastMember != member: - // Plugin started with duty finder in progress - case MatchingState.IDLE: - // We get here when the queue is stopped by someone else (?) - state = MatchingState.QUEUED; - break; - case MatchingState.QUEUED: - // in queue - break; - } - - _lastMember = member; - - var memberinfo = $"Tanks: {tank}, Healers: {healer}, Dps: {dps} | Total Members: {member}"; + + var memberinfo = $"Tanks: {tank}/{tankMax}, Healers: {healer}/{healerMax}, Dps: {dps}/{dpsMax}"; _logger.Write($"Q: Matching State Updated [{memberinfo}]", LogLevel.Debug); } else if (opcode == 0x00AE) // Participant check status packet (received after matching) @@ -287,10 +150,5 @@ private void HandleMessage(int pid, byte[] message, ref MatchingState state) _logger.Write(ex, "A: Error while analyzing Message", LogLevel.Error); } } - - private void FireEvent(int pid, EventType eventType, int[] args) - { - OnEventReceived?.Invoke(pid, eventType, args); - } } } \ No newline at end of file diff --git a/DFAssist.Core/Network/IpPacket.cs b/DFAssist.Core/Network/IpPacket.cs deleted file mode 100644 index d937c08..0000000 --- a/DFAssist.Core/Network/IpPacket.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Linq; -using System.Net; -using System.Net.Sockets; -using Splat; - -namespace DFAssist.Core.Network -{ - public struct IpPacket - { - public byte HeaderLength { get; } - public ProtocolType Protocol { get; } - public ProtocolFamily Version { get; } - public IPAddress SourceIpAddress { get; } - public IPAddress DestinationIpAddress { get; } - - public byte[] Data { get; } - - public bool IsValid { get; } - - public IpPacket(byte[] buffer) - { - try - { - var versionAndHeaderLength = buffer[0]; - Version = versionAndHeaderLength >> 4 == 4 ? ProtocolFamily.InterNetwork : ProtocolFamily.InterNetworkV6; - HeaderLength = (byte)((versionAndHeaderLength & 15) * 4); // 0b1111 = 15 - - Protocol = (ProtocolType)buffer[9]; - - SourceIpAddress = new IPAddress(BitConverter.ToUInt32(buffer, 12)); - DestinationIpAddress = new IPAddress(BitConverter.ToUInt32(buffer, 16)); - - Data = buffer.Skip(HeaderLength).ToArray(); - - IsValid = true; - } - catch (Exception ex) - { - Version = ProtocolFamily.Unknown; - HeaderLength = 0; - - Protocol = ProtocolType.Unknown; - - SourceIpAddress = null; - DestinationIpAddress = null; - - Data = null; - - IsValid = false; - Locator.Current.GetService().Write(ex, "N: IP Packet Parsing Error", LogLevel.Error); - } - } - } -} diff --git a/DFAssist.Core/Network/Network.cs b/DFAssist.Core/Network/Network.cs deleted file mode 100644 index 8449648..0000000 --- a/DFAssist.Core/Network/Network.cs +++ /dev/null @@ -1,345 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Management; -using System.Net; -using System.Net.Sockets; -using System.Runtime.InteropServices; -using DFAssist.Contracts; -using DFAssist.Contracts.Duty; -using NetFwTypeLib; -using Splat; - -namespace DFAssist.Core.Network -{ - public class Network - { - [DllImport("Iphlpapi.dll", SetLastError = true)] - public static extern uint GetExtendedTcpTable( - IntPtr tcpTable, - ref int tcpTableLength, - bool sort, - AddressFamily ipVersion, - int tcpTableType, - int reserved); - - public const int TcpTableOwnerPidConnections = 4; - - private readonly string _exePath; - private readonly byte[] _recvBuffer; - private readonly object _lockAnalyse; - - private readonly ILogger _logger; - private readonly IPacketHandler _packetHandler; - - private int _pid; - private MatchingState _state; - private Socket _socket; - private List _connections; - public byte[] RcvallIplevel { get; } - public bool IsRunning { get; private set; } - - public Network() - { - _state = MatchingState.IDLE; - _connections = new List(); - _lockAnalyse = new object(); - _recvBuffer = new byte[0x20000]; - _logger = Locator.Current.GetService(); - _packetHandler = Locator.Current.GetService(); - - RcvallIplevel = new byte[] { 3, 0, 0, 0 }; - var processModule = System.Diagnostics.Process.GetCurrentProcess().MainModule; - if (processModule != null) - _exePath = processModule.FileName; - } - - public bool StartCapture(System.Diagnostics.Process process) - { - _pid = process.Id; - try - { - _logger.Write("N: Starting Network Reading...", LogLevel.Debug); - - if(IsRunning) - { - _logger.Write("N: Already Reading Network Packets", LogLevel.Error); - return false; - } - - UpdateGameConnections(process); - - var localConnection = _connections.FirstOrDefault(x => x.LocalEndPoint.Address.ToString() != "127.0.0.1"); - if(_connections.Count < 2 || localConnection == null) - { - _logger.Write("N: Could not find Game Server Connection", LogLevel.Error); - return false; - } - - var localAddress = localConnection.LocalEndPoint.Address; - _logger.Write($"N: Local EndPoint Found: {localAddress}", LogLevel.Info); - - RegisterToFirewall(); - - _socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); - _socket.Bind(new IPEndPoint(localAddress, 0)); - _socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true); - _socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AcceptConnection, true); - _socket.IOControl(IOControlCode.ReceiveAll, RcvallIplevel, null); - _socket.ReceiveBufferSize = _recvBuffer.Length * 4; - - _socket.BeginReceive(_recvBuffer, 0, _recvBuffer.Length, 0, OnReceive, null); - IsRunning = true; - - _logger.Write("N: Started Reading Network Packets", LogLevel.Info); - return true; - } - catch(Exception ex) - { - _logger.Write(ex, "N: Failed to Start", LogLevel.Error); - return false; - } - } - - public void StopCapture() - { - try - { - if(!IsRunning) - { - _logger.Write("N: Already Stopped", LogLevel.Error); - return; - } - - _socket.Close(); - _connections.Clear(); - _logger.Write("N: Stopping Reading Network Packets...", LogLevel.Debug); - } - catch(Exception ex) - { - _logger.Write(ex, "N: Failed to Stop", LogLevel.Error); - } - } - - public void UpdateGameConnections(System.Diagnostics.Process process) - { - var update = _connections.Count < 2; - var currentConnections = GetConnections(process); - - foreach(var connection in _connections) - { - if(currentConnections.Contains(connection)) - continue; - - // Connection was lost, a new update is requested - update = true; - _logger.Write("N: Detected Game Server Disconnection", LogLevel.Debug); - break; - } - - if(!update) - return; - - var lobbyEndPoint = GetLobbyEndPoint(process); - _connections = currentConnections.Where(x => !x.RemoteEndPoint.Equals(lobbyEndPoint)).ToList(); - - foreach(var connection in _connections) - { - _logger.Write($"N: Detected Game Server Connection: {connection}", LogLevel.Debug); - } - } - - private void OnReceive(IAsyncResult ar) - { - try - { - var length = _socket.EndReceive(ar); - var buffer = _recvBuffer.Take(length).ToArray(); - _socket.BeginReceive(_recvBuffer, 0, _recvBuffer.Length, 0, OnReceive, null); - - FilterAndProcessPacket(buffer); - } - catch(Exception ex) when(ex is ObjectDisposedException || ex is NullReferenceException) - { - IsRunning = false; - _socket = null; - _logger.Write("N: Stopped Reading Network Packets", LogLevel.Warn); - } - catch(Exception ex) - { - _logger.Write(ex, "N: Error while Receiving Packets", LogLevel.Error); - } - } - - private void FilterAndProcessPacket(byte[] buffer) - { - try - { - var ipPacket = new IpPacket(buffer); - if(!ipPacket.IsValid || ipPacket.Protocol != ProtocolType.Tcp) - return; - - var tcpPacket = new TcpPacket(ipPacket.Data); - if(!tcpPacket.IsValid) - return; - - if(!tcpPacket.Flags.HasFlag(TcpFlags.ACK | TcpFlags.PSH)) - return; - - var sourceEndPoint = new IPEndPoint(ipPacket.SourceIpAddress, tcpPacket.SourcePort); - var destinationEndPoint = new IPEndPoint(ipPacket.DestinationIpAddress, tcpPacket.DestinationPort); - var connection = new Connection { LocalEndPoint = sourceEndPoint, RemoteEndPoint = destinationEndPoint }; - var reverseConnection = new Connection { LocalEndPoint = destinationEndPoint, RemoteEndPoint = sourceEndPoint }; - - if(!(_connections.Contains(connection) || _connections.Contains(reverseConnection))) - return; - - if(!_connections.Contains(reverseConnection)) - return; - - lock(_lockAnalyse) - { - _packetHandler.Analyze(_pid, tcpPacket.Payload, ref _state); - } - } - catch(Exception ex) - { - _logger.Write(ex, "N: Error while Filtering PacketsS", LogLevel.Error); - } - } - - private void RegisterToFirewall() - { - try - { - var netFwMgr = GetInstance("HNetCfg.FwMgr"); - var netAuthApps = netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications; - - var exists = false; - foreach(var netAuthAppObject in netAuthApps) - { - if(netAuthAppObject is INetFwAuthorizedApplication netAuthApp && netAuthApp.ProcessImageFileName == _exePath && netAuthApp.Enabled) - { - exists = true; - } - } - - if(exists) - return; - - var networkApp = GetInstance("HNetCfg.FwAuthorizedApplication"); - - networkApp.Enabled = true; - networkApp.Name = "FFXIV_DFAssist"; - networkApp.ProcessImageFileName = _exePath; - networkApp.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL; - - netAuthApps.Add(networkApp); - - _logger.Write("N: Firewall exception Registered", LogLevel.Info); - } - catch(Exception ex) - { - _logger.Write(ex, "N: Unable to register Firewall exception", LogLevel.Error); - } - } - - private IPEndPoint GetLobbyEndPoint(System.Diagnostics.Process process) - { - IPEndPoint ipep = null; - string lobbyHost = null; - var lobbyPort = 0; - - try - { - using(var managementObjectSearcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id)) - { - foreach(var managementBaseObject in managementObjectSearcher.Get()) - { - var commandline = managementBaseObject["CommandLine"].ToString(); - var args = commandline.Split(' '); - - foreach(var arg in args) - { - var splitted = arg.Split('='); - if(splitted.Length != 2) - continue; - - switch(splitted[0]) - { - case "DEV.LobbyHost01": - lobbyHost = splitted[1]; - break; - case "DEV.LobbyPort01": - lobbyPort = int.Parse(splitted[1]); - break; - } - } - } - } - - if(lobbyHost != null && lobbyPort > 0) - { - var address = Dns.GetHostAddresses(lobbyHost)[0]; - ipep = new IPEndPoint(address, lobbyPort); - } - } - catch(Exception ex) - { - _logger.Write(ex, "N: Error while receeving lobby server information", LogLevel.Error); - } - - return ipep; - } - - private static List GetConnections(System.Diagnostics.Process process) - { - var connections = new List(); - - var tcpTable = IntPtr.Zero; - var tcpTableLength = 0; - - if(GetExtendedTcpTable(tcpTable, ref tcpTableLength, false, AddressFamily.InterNetwork, TcpTableOwnerPidConnections, 0) == 0) - return connections; - - try - { - tcpTable = Marshal.AllocHGlobal(tcpTableLength); - if(GetExtendedTcpTable(tcpTable, ref tcpTableLength, false, AddressFamily.InterNetwork, TcpTableOwnerPidConnections, 0) == 0) - { - var table = (TcpTable)Marshal.PtrToStructure(tcpTable, typeof(TcpTable)); - var rowPointer = new IntPtr(tcpTable.ToInt64() + Marshal.SizeOf(typeof(uint))); - - for(var i = 0; i < table.length; i++) - { - var row = (TcpRow)Marshal.PtrToStructure(rowPointer, typeof(TcpRow)); - - if(row.owningPid == process.Id) - { - var local = new IPEndPoint(row.localAddr, (ushort)IPAddress.NetworkToHostOrder((short)row.localPort)); - var remote = new IPEndPoint(row.remoteAddr, (ushort)IPAddress.NetworkToHostOrder((short)row.remotePort)); - - connections.Add(new Connection() { LocalEndPoint = local, RemoteEndPoint = remote }); - } - - rowPointer = new IntPtr(rowPointer.ToInt64() + Marshal.SizeOf(typeof(TcpRow))); - } - } - } - finally - { - if(tcpTable != IntPtr.Zero) - { - Marshal.FreeHGlobal(tcpTable); - } - } - - return connections; - } - - private static T GetInstance(string typeName) - { - return (T)Activator.CreateInstance(Type.GetTypeFromProgID(typeName)); - } - } -} diff --git a/DFAssist.Core/Network/ProcessNetwork.cs b/DFAssist.Core/Network/ProcessNetwork.cs deleted file mode 100644 index e6450f5..0000000 --- a/DFAssist.Core/Network/ProcessNetwork.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Diagnostics; - -namespace DFAssist.Core.Network -{ - public class ProcessNetwork - { - public Network Network { get; } - public Process Process { get; } - - public ProcessNetwork(Process process, Network network) - { - Process = process; - Network = network; - } - } -} \ No newline at end of file diff --git a/DFAssist.Core/Network/TcpFlags.cs b/DFAssist.Core/Network/TcpFlags.cs deleted file mode 100644 index 4856611..0000000 --- a/DFAssist.Core/Network/TcpFlags.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; - -namespace DFAssist.Core.Network -{ - [Flags] - public enum TcpFlags - { - // ReSharper disable InconsistentNaming - // ReSharper disable UnusedMember.Global - NONE = 0, - FIN = 1, - SYN = 2, - RST = 4, - PSH = 8, - ACK = 16, - URG = 32, - ECE = 64, - CWR = 128, - NS = 256, - // ReSharper restore UnusedMember.Global - // ReSharper restore InconsistentNaming - } -} \ No newline at end of file diff --git a/DFAssist.Core/Network/TcpPacket.cs b/DFAssist.Core/Network/TcpPacket.cs deleted file mode 100644 index 24c8899..0000000 --- a/DFAssist.Core/Network/TcpPacket.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Linq; -using System.Net; -using Splat; - -namespace DFAssist.Core.Network -{ - public struct TcpPacket - { - public ushort SourcePort; - public ushort DestinationPort; - public byte DataOffset; - public TcpFlags Flags; - - public byte[] Payload; - - public bool IsValid; - - public TcpPacket(byte[] buffer) - { - try - { - SourcePort = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, 0)); - DestinationPort = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, 2)); - - var offsetAndFlags = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, 12)); - DataOffset = (byte)((offsetAndFlags >> 12) * 4); - Flags = (TcpFlags)(offsetAndFlags & 511); // 0b111111111 = 511 - - Payload = buffer.Skip(DataOffset).ToArray(); - - IsValid = true; - } - catch (Exception ex) - { - SourcePort = 0; - DestinationPort = 0; - DataOffset = 0; - Flags = TcpFlags.NONE; - - Payload = null; - IsValid = false; - - Locator.Current.GetService().Write(ex, "N: TCP Packet Parsing Error", LogLevel.Error); - } - } - } -} \ No newline at end of file diff --git a/DFAssist.Core/Network/TcpRow.cs b/DFAssist.Core/Network/TcpRow.cs deleted file mode 100644 index 7d9e994..0000000 --- a/DFAssist.Core/Network/TcpRow.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Net.NetworkInformation; -using System.Runtime.InteropServices; - -namespace DFAssist.Core.Network -{ - [StructLayout(LayoutKind.Sequential)] - public struct TcpRow - { - public TcpState state; - public uint localAddr; - public uint localPort; - public uint remoteAddr; - public uint remotePort; - public uint owningPid; - } -} \ No newline at end of file diff --git a/DFAssist.Core/Network/TcpTable.cs b/DFAssist.Core/Network/TcpTable.cs deleted file mode 100644 index 2be6c04..0000000 --- a/DFAssist.Core/Network/TcpTable.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Runtime.InteropServices; - -namespace DFAssist.Core.Network -{ - [StructLayout(LayoutKind.Sequential)] - public struct TcpTable - { - public uint length; - public TcpRow row; - } -} \ No newline at end of file diff --git a/DFAssist/DFAssist.Plugin.csproj b/DFAssist/DFAssist.Plugin.csproj index 0233561..d63451e 100644 --- a/DFAssist/DFAssist.Plugin.csproj +++ b/DFAssist/DFAssist.Plugin.csproj @@ -129,8 +129,11 @@ 1.0.4 + + 2.1.1 + - 12.0.2 + 12.0.3 3.1.0 diff --git a/DFAssist/Helpers/FFXIVNetworkProcessHelper.cs b/DFAssist/Helpers/FFXIVNetworkProcessHelper.cs index 5b43973..a3d5957 100644 --- a/DFAssist/Helpers/FFXIVNetworkProcessHelper.cs +++ b/DFAssist/Helpers/FFXIVNetworkProcessHelper.cs @@ -1,15 +1,11 @@ using System; -using System.Collections.Concurrent; -using System.Collections.Generic; using System.Diagnostics; -using System.Linq; using Advanced_Combat_Tracker; using DFAssist.Contracts; using DFAssist.Contracts.Duty; using DFAssist.Contracts.Repositories; -using DFAssist.Core.Network; +using Machina.FFXIV; using Splat; -using Timer = System.Timers.Timer; namespace DFAssist.Helpers { @@ -22,95 +18,52 @@ public class FFXIVNetworkProcessHelper : IDisposable private IActLogger _logger = Locator.Current.GetService(); private IPacketHandler _packetHandler = Locator.Current.GetService(); private IDataRepository _dataRepository = Locator.Current.GetService(); - private Timer _timer = new Timer { Interval = 10000 }; - private ConcurrentDictionary _networks = new ConcurrentDictionary(); - public Process ActiveProcess; + private FFXIVNetworkMonitor _ffxivNetworkMonitor; - public FFXIVNetworkProcessHelper() + public Process ActiveProcess { - _timer.Elapsed += Timer_Tick; + get + { + if (_ffxivNetworkMonitor == null) + return default; + + var pid = Convert.ToInt32(_ffxivNetworkMonitor.ProcessID); + if(pid == 0) + return default; + + var activeProcess = Process.GetProcessById(pid); + return activeProcess; + } } - public void Subscribe() + public FFXIVNetworkProcessHelper() { - UpdateProcesses(); - _timer.Start(); + _ffxivNetworkMonitor = new FFXIVNetworkMonitor + { + MessageReceived = (connection, epoch, message) => _packetHandler.HandleMessage(message, OnMessageReceived) + }; } - private void Timer_Tick(object sender, EventArgs e) + public void Subscribe() { - if (!DFAssistPlugin.Instance.IsPluginEnabled) - return; - - UpdateProcesses(); + _ffxivNetworkMonitor.Start(); + _logger.Write("N: FFXIV Network Monitor Started!", LogLevel.Info); } - private void UpdateProcesses() + private void OnMessageReceived(EventType eventType, int[] args) { - lock (this) - { - var process = Process.GetProcessesByName("ffxiv_dx11").FirstOrDefault(); - if (process == null) - return; - - ActiveProcess = process; - - try - { - if (!_networks.ContainsKey(process.Id)) - { - var pn = new ProcessNetwork(process, new Network()); - _packetHandler.OnEventReceived += Network_onReceiveEvent; - _networks.TryAdd(process.Id, pn); - _logger.Write($"P: FFXIV Process Selected: {process.Id}", LogLevel.Info); - } - } - catch (Exception e) - { - _logger.Write(e, "P: Failed to set FFXIV Process", LogLevel.Error); - } - - var toDelete = new List(); - foreach (var entry in _networks) - { - if (entry.Value.Process.HasExited) - { - entry.Value.Network.StopCapture(); - toDelete.Add(entry.Key); - } - else - { - if (entry.Value.Network.IsRunning) - entry.Value.Network.UpdateGameConnections(entry.Value.Process); - else - { - if (!entry.Value.Network.StartCapture(entry.Value.Process)) - toDelete.Add(entry.Key); - } - } - } + _logger.Write("N: FFXIV Network packet received...", LogLevel.Debug); - foreach (var t in toDelete) - { - try - { - _networks.TryRemove(t, out _); - _packetHandler.OnEventReceived -= Network_onReceiveEvent; - } - catch (Exception e) - { - _logger.Write(e, "P: Failed to remove FFXIV Process", LogLevel.Error); - } - } + var text = string.Empty; + if (ActiveProcess != null) + { + var processMainModule = ActiveProcess.MainModule; + var server = processMainModule != null && processMainModule.FileName.Contains("KOREA") ? "KOREA" : "GLOBAL"; + text = ActiveProcess.Id + "|" + server + "|"; } - } - private void Network_onReceiveEvent(int pid, EventType eventType, int[] args) - { - var processMainModule = _networks[pid].Process.MainModule; - var server = processMainModule != null && processMainModule.FileName.Contains("KOREA") ? "KOREA" : "GLOBAL"; - var text = pid + "|" + server + "|" + eventType + "|"; + text += eventType + "|"; var pos = 0; switch (eventType) @@ -177,23 +130,13 @@ private void Network_onReceiveEvent(int pid, EventType eventType, int[] args) public void Dispose() { - if (_timer != null) - { - if (_timer.Enabled) - _timer.Stop(); - - _timer.Elapsed -= Timer_Tick; - _timer.Dispose(); - _timer = null; - } - - foreach (var entry in _networks) + if (_ffxivNetworkMonitor != null) { - entry.Value.Network.StopCapture(); + _ffxivNetworkMonitor.Stop(); + _ffxivNetworkMonitor.MessageReceived = null; } - _networks.Clear(); - _networks = null; + _ffxivNetworkMonitor = null; _packetHandler = null; _logger = null; _dataRepository = null;