Ejemplo n.º 1
0
 public BafPacket(PacketId id, byte[] data, PacketSource source = PacketSource.Server)
 {
     Id      = id;
     Data    = data;
     Source  = source;
     IdValue = (ushort)id;
 }
Ejemplo n.º 2
0
 public Packet(PacketSource _source, byte[] _data, DateTime _time)
 {
     data    = _data;
     source  = _source;
     gotTime = _time;
     RecalculatePreview();
 }
Ejemplo n.º 3
0
        public bool sendTimingReq(int dst, PacketSource destiny)
        {
            var pkt = buildTracerRequest(dst, destiny);

            pkt.linkDelay = Config.linkdelay_insp_to_tracetetcher;
            return(sendTimingReq(destiny, ref pkt));
        }
Ejemplo n.º 4
0
 public PonykartPacket(byte[] creator)
 {
     // Incoming packe
     Contents = GetContents(creator);
     Timestamp = GetTimestamp(creator);
     _Type = GetPType(creator);
     Source = PacketSource.Remote;
 }
        public void OnPacketEventData(ref PacketEventData pEventData, PacketSource packetSource)
        {
            if (packetSource == PacketSource.File)
            {
                return;
            }

            var sessionId = pEventData.Header.SessionUID;

            if (pEventData.EventStringCode == "SSTA")
            {
                if (_files.TryGetValue(sessionId, out var stream))
                {
                    Logger.Warn(
                        $"Received session start for SessionId {sessionId} that already exists in active session list, will overwrite");
                    stream.Dispose();
                    _files.Remove(sessionId);
                }

                var path = Path.Combine(_saveLocation, $"{_filePrefix}_{sessionId}.f1s.gz");
                try
                {
                    if (!Directory.Exists(_saveLocation))
                    {
                        Directory.CreateDirectory(_saveLocation);
                    }

                    var fileStream = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.Read);
                    var gzipStream = new GZipStream(fileStream, CompressionLevel.Optimal);
                    _files[sessionId] = gzipStream;
                    _ignoredSessions.Remove(sessionId);
                    stream = gzipStream;
                    Logger.Info($"Created save file for session {sessionId} at {path}");
                }
                catch (Exception ex)
                {
                    Logger.Error($"Exception while creating a save file for session {sessionId} at {path}", ex);
                }

                WritePacket(sessionId, ref pEventData, packetSource);
            }
            else if (pEventData.EventStringCode == "SEND")
            {
                if (_files.TryGetValue(sessionId, out var stream))
                {
                    WritePacket(sessionId, ref pEventData, packetSource);

                    Logger.Info($"Closing save file for session {sessionId}");
                    stream.Dispose();
                    _files.Remove(sessionId);
                }
                else
                {
                    Logger.Warn($"Received session end for session {sessionId}, but no file is opened for saving");
                }
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Binds the packet.
 /// </summary>
 /// <param name="encryptedData">The encrypted data.</param>
 /// <param name="interceptedDate">The intercepted date.</param>
 /// <param name="connection">The connection.</param>
 /// <param name="source">The source.</param>
 /// <param name="cripto">The cripto.</param>
 /// <returns></returns>
 public static Packet BindPacket(byte[] encryptedData, DateTime interceptedDate, ConnectionProvider connection, PacketSource source)
 {
     return new Packet {
         EncryptedData = encryptedData,
         ConnectionSource = connection,
         InterceptedDate = interceptedDate,
         PacketSource = source,
     };
 }
Ejemplo n.º 7
0
 public void OnPacketEventData(ref PacketEventData pEventData, PacketSource packetSource)
 {
     if (pEventData.EventStringCode == "SSTA")
     {
         _sessionLastTimes[pEventData.Header.SessionUID] = 0.0f;
     }
     else
     {
         _sessionLastTimes.Remove(pEventData.Header.SessionUID);
     }
 }
Ejemplo n.º 8
0
        private void RegisterScanner(
            string packetName,
            string tutorial,
            PacketSource source,
            Func <IpcPacket, string[], bool> del,
            string[] paramPrompts = null)
        {
            bool Fn(IpcPacket a, string[] b, Comment c) => del(a, b);

            RegisterScanner(packetName, tutorial, source, Fn, paramPrompts);
        }
        public void OnPacketEventData(ref PacketEventData pEventData, PacketSource source)
        {
            var   sc           = pEventData.EventStringCode;
            Event sessionEvent = sc switch
            {
                "SSTA" => (Event) new SessionStart(pEventData.Header.SessionUID, DateTime.Now, pEventData.Header.SessionTime),
                "SEND" => (Event) new SessionEnd(pEventData.Header.SessionUID, DateTime.Now, pEventData.Header.SessionTime),
                _ => throw new InvalidOperationException($"Invalid session type {sc}")
            };

            _newPacketRead?.Invoke(this, sessionEvent);
        }
Ejemplo n.º 10
0
 public BafPacket(ushort id, byte[] data, PacketSource source = PacketSource.Server)
 {
     IdValue = id;
     Data    = data;
     Source  = source;
     if (Enum.IsDefined(typeof(PacketId), id))
     {
         Id = (PacketId)id;
     }
     else
     {
         Id = PacketId.Unknown;
     }
 }
Ejemplo n.º 11
0
        public override bool sendFunctionalReq(PacketSource destiny, ref Packet pkt)
        {
            switch (destiny)
            {
            case PacketSource.TraceFetcher:
                DEBUG.Assert(pkt.isRequest() && pkt.isRead());
                pkt.ts_departure = GlobalTimer.tick;
                ins_port._masterPort.recvFunctionalReq(pkt);
                return(true);

            default:
                return(false);
            }
        }
Ejemplo n.º 12
0
        public Packet buildTracerRequest(int dst, PacketSource destiny)
        {
            switch (destiny)
            {
            case PacketSource.TraceFetcher:
                Packet pkt = new Packet(CMD.ReadReq);
                pkt.source = PacketSource.Insp;
                pkt.BuildData(dst);
                return(pkt);

            default:
                return(null);
            }
        }
Ejemplo n.º 13
0
        private void Delay(ulong sessionId, float sessionTime, PacketSource packetSource)
        {
            if (packetSource != PacketSource.File || !_delayScale.Enabled)
            {
                return;
            }

            var lastSessionTime = _sessionLastTimes[sessionId];
            var diff            = sessionTime - lastSessionTime;
            var scaledDiff      = diff * _delayScale;

            Thread.Sleep(TimeSpan.FromSeconds(scaledDiff));
            _sessionLastTimes[sessionId] = sessionTime;
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Adds a scanner to the scanner registry.
 /// </summary>
 /// <param name="packetName">The name (Sapphire-style) of the packet.</param>
 /// <param name="tutorial">How the packet's conditions are created.</param>
 /// <param name="source">Whether the packet originates on the client or the server.</param>
 /// <param name="del">A boolean function that returns true if a packet matches the contained heuristics.</param>
 /// <param name="paramPrompts">An array of requests for auxiliary data that will be passed into the detection delegate.</param>
 private void RegisterScanner(
     string packetName,
     string tutorial,
     PacketSource source,
     Func <IpcPacket, string[], Comment, bool> del,
     string[] paramPrompts = null)
 {
     this.scanners.Add(new Scanner
     {
         PacketName       = packetName,
         Tutorial         = tutorial,
         ScanDelegate     = del,
         Comment          = new Comment(),
         ParameterPrompts = paramPrompts ?? new string[] { },
         PacketSource     = source,
     });
 }
Ejemplo n.º 15
0
        private PacketModel GetPacketModel(PacketSource source, Server server, Client client, Packet packet)
        {
            var packetModel = new PacketModel
            {
                Client   = client,
                Server   = server,
                ID       = new Random().Next(999, 9999),
                EndPoint = (packet.UdpPacket) ? packet.EndPoint : client.EndPoint,
                Bytes    = packet.Buffer,
                Length   = packet.Buffer.Length,
                Type     = (packet.UdpPacket) ? PacketType.UDP : PacketType.TCP,
                Source   = source
            };

            packetModel.TypeHelp = string.Format
                                       ("{0}, {1}", packetModel.Type, packetModel.Source);

            return(packetModel);
        }
Ejemplo n.º 16
0
        private void WritePacket <T>(ulong sessionId, ref T packet, PacketSource source) where T : struct
        {
            if (source == PacketSource.File)
            {
                return;
            }


            if (_files.TryGetValue(sessionId, out var stream))
            {
                var readOnlySpan = MemoryMarshal.CreateReadOnlySpan(ref packet, 1);
                var onlySpan     = MemoryMarshal.AsBytes(readOnlySpan);
                stream.Write(onlySpan);
            }
            else if (!_ignoredSessions.Contains(sessionId))
            {
                Logger.Warn($"Ignoring this and further messages for session {sessionId} until session start event comes through and save file is created");
                _ignoredSessions.Add(sessionId);
            }
        }
Ejemplo n.º 17
0
        internal async void StartListenData(CancellationToken cancellationToken, PacketSource source, bool isListener)
        {
            _cancellationToken = cancellationToken;
            _source            = source;
            _isListener        = isListener;

            while (Connected && !cancellationToken.IsCancellationRequested)
            {
                if (!_socket.IsBound)
                {
                    break;
                }

                _socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), null);

                try
                {
                    if (_isListener)
                    {
                        if (!await _waiterData.WaitAsync(TimeSpan.FromSeconds(60), cancellationToken))
                        {
                            await Send(Ping.Default);

                            if (!await _waiterData.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken))
                            {
                                await Disconnect();
                            }
                        }
                    }
                    else
                    {
                        await _waiterData.WaitAsync(Timeout.Infinite, cancellationToken);
                    }
                }
                catch (OperationCanceledException)
                {
                    break;
                }
            }
        }
        public void OnPacketSessionData(ref PacketSessionData pSessionData, PacketSource _)
        {
            var timestamp   = DateTime.Now;
            var sessionId   = pSessionData.Header.SessionUID;
            var sessionTime = pSessionData.Header.SessionTime;

            var weather = new WeatherInfo(
                (Weather)pSessionData.Weather,
                pSessionData.TrackTemperature,
                pSessionData.AirTemperature,
                sessionId,
                timestamp,
                sessionTime);

            _newPacketRead?.Invoke(this, weather);

            var trackInfo = new TrackInfo(
                (Track)pSessionData.TrackId,
                pSessionData.TrackLength,
                sessionId,
                timestamp,
                sessionTime);

            _newPacketRead?.Invoke(this, trackInfo);

            var sessionPause = pSessionData.GamePaused != 0
                ? (Event) new SessionPause(sessionId, timestamp, sessionTime)
                : (Event) new SessionResume(sessionId, timestamp, sessionTime);

            _newPacketRead?.Invoke(this, sessionPause);

            var sessionDuration = new SessionDuration(TimeSpan.FromSeconds(pSessionData.SessionDuration), sessionId, timestamp, sessionTime);

            _newPacketRead?.Invoke(this, sessionDuration);

            var sessionTimeLeft = new SessionTimeLeft(TimeSpan.FromSeconds(pSessionData.SessionTimeLeft), sessionId, timestamp, sessionTime);

            _newPacketRead?.Invoke(this, sessionTimeLeft);
        }
Ejemplo n.º 19
0
        public static Packet Read(Stream ms)
        {
            //Read the 14 bytes of header.
            //[0-3] Data length
            //[4-12] Timestamp ticks
            //[13-14] Source

            byte[] buf = new byte[4];
            ms.Read(buf, 0, 4);
            if (BitConverter.IsLittleEndian == false)
            {
                Array.Reverse(buf);
            }
            int length = BitConverter.ToInt32(buf, 0);

            buf = new byte[8];
            ms.Read(buf, 0, 8);
            if (BitConverter.IsLittleEndian == false)
            {
                Array.Reverse(buf);
            }
            DateTime dt = new DateTime(BitConverter.ToInt64(buf, 0));

            buf = new byte[2];
            ms.Read(buf, 0, 2);
            if (BitConverter.IsLittleEndian == false)
            {
                Array.Reverse(buf);
            }
            PacketSource src = (PacketSource)BitConverter.ToInt16(buf, 0);

            //Read in actual data.
            buf = new byte[length];
            ms.Read(buf, 0, length);

            //Create packet.
            return(new Packet(src, buf, dt));
        }
Ejemplo n.º 20
0
        internal PacketResult Handle(PacketSource source, Session session, Packet packet)
        {
            switch (source)
            {
            case PacketSource.Certificator:
                if (_certificatorHandler.ContainsKey(packet.Opcode))
                {
                    return(_certificatorHandler[packet.Opcode].Invoke(session, packet));
                }
                break;

            case PacketSource.Module:
                if (_moduleHandler.ContainsKey(packet.Opcode))
                {
                    return(_moduleHandler[packet.Opcode].Invoke(session, packet));
                }
                break;
            }

            //if (StaticLogger.Instance.IsTraceEnabled)
            //    StaticLogger.Instance.Warn("[{7}][{0:X4}][{1} bytes]{2}{3}{4}{5}{6}", packet.Opcode, packet.Length, packet.Encrypted ? "[Encrypted]" : "", packet.Massive ? "[Massive]" : "", Environment.NewLine, packet.GetBytes().HexDump(), Environment.NewLine, source);
            return(PacketResult.None);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Initialize All Events and Initial Values of Object.
        /// </summary>
        protected void Initialize()
        {
            state = ConnectionState.Disconnected;
            packetsToSave = PacketSource.Unknow;
            Xtea = new NativeCryptoManager(CryptoType.Xtea, this);
            RSA = new NativeCryptoManager(CryptoType.RSA, this);
            IPLocal = new IPAddress(new byte[] { 127, 0, 0, 1 });

            OnBeforeConnect += Connection_OnBeforeConnect;
            OnConnect += Connection_OnConnect;
            OnAfterConnect += Connection_OnAfterConnect;
            OnBeforeDisconnect += Connection_OnBeforeDisconnect;
            OnDisconnect += Connection_OnDisconnect;
            OnAfterDisconnect += Connection_OnAfterDisconnect;
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Fire a changed packet event.
        /// </summary>
        internal void FireChangedPacket(byte[] data, PacketSource source)
        {
            lock (this) {
                if (PacketChanged != null) {

                    var packets = PacketBuilder.GetPackets(data, this, source);
                    foreach (var packet in packets) {
                        PacketChanged(this, new PacketEventArgs(packet, source));
                    }

                }
            }
        }
Ejemplo n.º 23
0
 public ulong sendAtomic(PacketSource source, ref Packet pkt)
 {
     Debug.Fail(String.Format("{0} was not expecting a sendAtomic request\n", name()));
     return(0);
 }
Ejemplo n.º 24
0
 public void OnPacketCarTelemetryData(ref PacketCarTelemetryData pTelemetry, PacketSource packetSource)
 {
     WritePacket(pTelemetry.Header.SessionUID, ref pTelemetry, packetSource);
 }
Ejemplo n.º 25
0
        private void PacketSource_ReceivedPacket(PacketSource<WaxPacket> sender, PacketEventArgs<WaxPacket> e)
        {
            // If a correctly parsed packet...
            if (e.Packet != null && e.Packet is WaxPacket)
            {
                WaxPacket packet = (WaxPacket)e.Packet;

                //Console.WriteLine("[" + packet.Timestamp + "]");
                //Console.WriteLine(packet.ToString());

                lock (SyncRoot)
                {
                    if (!waxDevices.ContainsKey(packet.DeviceId))
                    {
                        // Create new device
                        waxDevices.Add(packet.DeviceId, new WaxDevice(packet.DeviceId, packet.Timestamp));
                        OnNewDevice(new ManagerEventArgs(waxDevices[packet.DeviceId]));
                    }
                    WaxDevice waxDevice = waxDevices[packet.DeviceId];

                    waxDevice.AddSamples(packet.Samples);

                    // Forward packet to all destinations
                    foreach (PacketDest<WaxPacket> dest in packetDests)
                    {
                        dest.SendPacket(packet);
                    }

                    if (packet != null)
                    {
                        DebugString = packet.ToString();
                    }
                }
                OnReceivedPacket(new ManagerEventArgs(waxDevices[packet.DeviceId], packet));
            }
        }
Ejemplo n.º 26
0
 public void AddPacketSource(PacketSource<WaxPacket> source)
 {
     packetSources.Add(source);
     source.ReceivedPacket += PacketSource_ReceivedPacket;
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PacketEventArgs"/> class.
 /// </summary>
 /// <param name="packet">The packet.</param>
 /// <param name="source">The source.</param>
 public PacketEventArgs(Packet packet, PacketSource source)
 {
     Packet = packet;
     Source = source;
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Fires the changed packet.
 /// </summary>
 /// <param name="data">The data.</param>
 /// <param name="source">The source.</param>
 internal void FireChangedPacket(byte[] data, PacketSource source)
 {
     if (PacketChanged != null) {
         var packets = PacketBuilder.GetPackets(data, this, source);
         packets.ForEach(pk => PacketChanged(this, new PacketEventArgs(pk, source)));
     }
 }
Ejemplo n.º 29
0
 public void OnPacketSessionData(ref PacketSessionData pSessionData, PacketSource packetSource)
 {
     WritePacket(pSessionData.Header.SessionUID, ref pSessionData, packetSource);
 }
Ejemplo n.º 30
0
 public void OnPacketParticipantsData(ref PacketParticipantsData pParticipants, PacketSource packetSource)
 {
     WritePacket(pParticipants.Header.SessionUID, ref pParticipants, packetSource);
 }
Ejemplo n.º 31
0
 public void OnPacketMotionData(ref PacketMotionData pMotion, PacketSource packetSource)
 {
     WritePacket(pMotion.Header.SessionUID, ref pMotion, packetSource);
 }
Ejemplo n.º 32
0
 public void OnPacketCarSetupData(ref PacketCarSetupData pCarSetup, PacketSource packetSource)
 {
     WritePacket(pCarSetup.Header.SessionUID, ref pCarSetup, packetSource);
 }
Ejemplo n.º 33
0
 public PonykartPacket(Commands type, string contents, Connection c, bool isVolatile)
 {
     // Outgoing
     Contents = System.Text.ASCIIEncoding.ASCII.GetBytes(contents);
     Timestamp = System.DateTime.Now.Ticks;
     _Type = (Int32)type;
     Owner = c;
     Source = PacketSource.Local;
     Volatile = isVolatile;
 }
Ejemplo n.º 34
0
 public PonykartPacket(Commands type, byte[] contents, Connection c, bool isVolatile)
 {
     // Outgoing
     Contents = contents;
     Timestamp = System.DateTime.Now.Ticks;
     _Type = (Int32)type;
     Owner = c;
     Source = PacketSource.Local;
     Volatile = isVolatile;
 }
Ejemplo n.º 35
0
 public virtual bool sendTimingResq(PacketSource source, ref Packet pkt)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 36
0
 public bool sendTimingSnoopResp(PacketSource source, ref Packet pkt)
 {
     Debug.Fail(String.Format("{0} was not expecting a sendTimingSnoopResp request\n", name()));
     return(false);
 }
Ejemplo n.º 37
0
 public void sendFunctionalSnoopReq(PacketSource source, ref Packet pkt)
 {
     Debug.Fail(String.Format("{0} was not expecting a sendFunctionalSnoopReq request\n", name()));
 }
Ejemplo n.º 38
0
 public void RemovePacketSource(PacketSource<WaxPacket> source)
 {
     source.ReceivedPacket -= PacketSource_ReceivedPacket;
     packetSources.Remove(source);
 }
Ejemplo n.º 39
0
 public bool sendFunctionalResq(PacketSource source, ref Packet pkt)
 {
     Debug.Fail(String.Format("{0} was not expecting a sendFunctionalResq request\n", name()));
     return(false);
 }
Ejemplo n.º 40
0
 public void OnPacketLapData(ref PacketLapData pLap, PacketSource packetSource)
 {
     WritePacket(pLap.Header.SessionUID, ref pLap, packetSource);
 }
Ejemplo n.º 41
0
 public void OnPacketCarStatusData(ref PacketCarStatusData pCarStatus, PacketSource packetSource)
 {
     WritePacket(pCarStatus.Header.SessionUID, ref pCarStatus, packetSource);
 }