protected void DecodeMultiplePacketsByteArray(uint clientIndex, byte[] data, bool isWebSocketClient) { lock (oldDecodedFrame) { int numberOfBytesProcessed = 0; int numberOfBytesToProcess = 0; int numberOfBytesReceived = data.Length; byte[] packetByteArray; List <byte> packets = new List <byte>(); MqttMsgBase tmpPacket = new MqttMsgSubscribe(); try { while (numberOfBytesProcessed != numberOfBytesReceived) { int remainingLength = MqttMsgBase.decodeRemainingLength(data); int remainingLenghtIndex = tmpPacket.encodeRemainingLength(remainingLength, data, 1); numberOfBytesToProcess = remainingLength + remainingLenghtIndex; packetByteArray = new byte[numberOfBytesToProcess]; Array.Copy(data, 0, packetByteArray, 0, numberOfBytesToProcess); MqttMsgBase packet = PacketDecoder.DecodeControlPacket(packetByteArray); OnPacketReceived(clientIndex, packet, isWebSocketClient); { byte[] tmp = new byte[data.Length - numberOfBytesToProcess]; Array.Copy(data, numberOfBytesToProcess, tmp, 0, tmp.Length); data = tmp; } numberOfBytesProcessed += numberOfBytesToProcess; } } catch (Exception e) { oldDecodedFrame[clientIndex].AddRange(data); } } }
public void Add(byte[] octets) { // log.Debug("Adding to receive stream:{0:X}", octets); queue.Enqueue(octets, 0, octets.Length); HastyPacket packet = null; do { var octetCount = queue.Peek(targetBuffer, 0, targetBuffer.Length); if (octetCount == 0) { // log.Debug("octetCount zero"); return; } int newOffset; packet = PacketDecoder.Decode(targetBuffer, 0, octetCount, out newOffset, log); if (packet != null) { // log.Debug("Got packet!"); queue.Skip(newOffset); packetReceiver.ReceivePacket(packet); } else { // log.Debug("No packet so far"); } } while (packet != null); }
public BufferedPacketDecoder(int bufsize, PacketDecoder decoder) { _data = new byte[bufsize]; _decoder = decoder; _parsepos = 0; _readpos = 0; }
public void DecodeMultiplePacketsByteArray(byte[] data) { List <MqttMsgBase> packetsInTheByteArray = new List <MqttMsgBase>(); int numberOfBytesProcessed = 0; int numberOfBytesToProcess = 0; int numberOfBytesReceived = data.Length; byte[] packetByteArray; MqttMsgBase tmpPacket = new MqttMsgSubscribe(); while (numberOfBytesProcessed != numberOfBytesReceived) { int remainingLength = MqttMsgBase.decodeRemainingLength(data); int remainingLenghtIndex = tmpPacket.encodeRemainingLength(remainingLength, data, 1); numberOfBytesToProcess = remainingLength + remainingLenghtIndex; packetByteArray = new byte[numberOfBytesToProcess]; Array.Copy(data, 0, packetByteArray, 0, numberOfBytesToProcess); { byte[] tmp = new byte[data.Length - numberOfBytesToProcess]; Array.Copy(data, numberOfBytesToProcess, tmp, 0, tmp.Length); data = tmp; } numberOfBytesProcessed += numberOfBytesToProcess; MqttMsgBase packet = PacketDecoder.DecodeControlPacket(packetByteArray); //RouteControlPacketDelegate r = new RouteControlPacketDelegate(RouteControlPacketToMethodHandler); //r.Invoke(packet); CrestronInvoke.BeginInvoke(RouteControlPacketToMethodHandler, packet); } }
static void Main(string[] args) { Start: Console.Clear(); Console.WriteLine("Input data or leave empty for done: "); string allInput = ""; string input = ""; Console.Write(">"); while (!string.IsNullOrEmpty(input = Console.ReadLine())) { allInput += input; Console.Write(">"); } if (string.IsNullOrEmpty(allInput)) { Console.WriteLine("Can't have empty input!"); Console.ReadLine(); goto Start; } byte[] data = StringToByteArray(allInput); Packet packet = PacketDecoder.FromBytes(data); PacketDecoder.LogPacket(packet); Console.WriteLine(""); //byte[] data2 = PacketDecoder.ToBytes(packet); //Packet packet2 = PacketDecoder.FromBytes(data2); //Console.WriteLine(BitConverter.ToString(data2).Replace("-", string.Empty)); //PacketDecoder.LogPacket(packet2); Console.ReadLine(); goto Start; }
// LogPacket: dump a packet to the console private void LogPacket(Packet packet, IPEndPoint endPoint, Direction direction) { //string packetText = DecodePacket.PacketToString(packet); string packetText = PacketDecoder.PacketToString(packet); if (logGrep == null || (logGrep != null && Regex.IsMatch(packetText, logGrep))) { string line = String.Format("{0}\n{1} {2,21} {3,5} {4}{5}{6}" , packet.Type , direction == Direction.Incoming ? "<--" : "-->" , endPoint , packet.Header.Sequence , InterpretOptions(packet.Header) , Environment.NewLine , packetText ); Console.WriteLine(line); if (output != null) { output.WriteLine(line); } } }
private void ConnectToServerCallback(SecureTCPClient myTCPClient) { try { if (myTCPClient.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED) { MqttMsgConnect connect = MsgBuilder.BuildConnect(this.ClientId, MqttSettings.Instance.Username, MqttSettings.Instance.Password, this.WillRetain, this.WillQosLevel, this.WillFlag, this.WillTopic, this.WillMessage, this.CleanSession, this.KeepAlivePeriod, ProtocolVersion); Send(connect); //TODO: timer for connack tcpClient.ReceiveData(); MqttMsgBase packet = PacketDecoder.DecodeControlPacket(tcpClient.IncomingDataBuffer); if (packet.Type == MqttMsgBase.MQTT_MSG_CONNACK_TYPE) { RouteControlPacketToMethodHandler(packet); } else { throw new MqttConnectionException("MQTTCLIENT - ConnectToServerCallback - " + PayloadMapper.ClientType + " , Expected CONNACK , received " + packet, new ArgumentException()); } } } catch (MqttClientException e) { CrestronLogger.WriteToLog("MQTTCLIENT - ConnectToServerCallback - Error occured : " + e.ErrorCode, 7); CrestronLogger.WriteToLog("MQTTCLIENT - ConnectToServerCallback - Error occured : " + e.StackTrace, 7); } catch (Exception e) { CrestronLogger.WriteToLog("MQTTCLIENT - ConnectToServerCallback - Error occured : " + e.Message, 7); CrestronLogger.WriteToLog("MQTTCLIENT - ConnectToServerCallback - Error occured : " + e.StackTrace, 7); //Disconnect from server , signal error at module lvl; } }
public override string ToPrettyString(Direction direction) { if (direction == this.Direction) { IMessage message = null; OSD osd = OSDParser.Deserialize(this.ResponseBytes); OSDMap data = (OSDMap)osd; if (data.ContainsKey("body")) { message = MessageUtils.DecodeEvent(this.Name, (OSDMap)data["body"]); } else { message = MessageUtils.DecodeEvent(this.Name, data); } if (message != null) { return(PacketDecoder.MessageToString(message, 0)); } else { return("No Decoder for " + this.Name + Environment.NewLine + osd.ToString()); } } else { return(String.Empty); } }
override protected void ConnectionCallback(SecureTCPServer server, uint clientIndex) { try { Server.WaitForConnectionAsync(IPAddress.Parse("0.0.0.0"), this.ConnectionCallback); if (Server.ClientConnected(clientIndex)) { oldDecodedFrame.Add(clientIndex, new List <byte>()); int lenghtOfData = Server.ReceiveData(clientIndex); byte[] data = Server.GetIncomingDataBufferForSpecificClient(clientIndex); MqttMsgBase packet = PacketDecoder.DecodeControlPacket(data); if (packet.Type == MqttMsgBase.MQTT_MSG_CONNECT_TYPE) { OnPacketReceived(clientIndex, packet, false); } else { throw new ArgumentException("Attempted connection with a non CONNECT packet"); } } } catch (Exception e) { DisconnectClient(clientIndex, false); } }
private async void StartPollingLoop() { try { while (Running && !AppIsInBackground) { try { var reader = _inboundReader; await reader.LoadAsync(PacketDecoder.PACKET_HEADER_LENGTH); var packet = await PacketDecoder.DecodePacket(reader); await OnPacketReceived(packet); } catch (Exception e) { if (Running && !AppIsInBackground) { e.PrintInDebug(); OnDisconnect?.Invoke(this, true); Restart(); } return; } } } catch { } }
/// <summary> /// Logs the packet received for this client. /// </summary> /// <remarks> /// This handler assumes that packets are processed one at a time. /// </remarks> /// <param name="sender">Sender.</param> /// <param name="args">Arguments.</param> private void HandlePacket(object sender, PacketReceivedEventArgs args) { // Console.WriteLine( // "Received packet {0} from {1} for {2}", args.Packet.Type, args.Simulator.Name, m_client.Self.Name); lock (this) { if (!m_isLogging) { return; } m_logStreamWriter.WriteLine("Received: {0}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fff")); try { m_logStreamWriter.WriteLine(PacketDecoder.PacketToString(args.Packet)); } catch (Exception e) { m_logStreamWriter.WriteLine("Failed to write decode of {0}, exception {1}", args.Packet.Type, e); } if (--m_packetsToLogRemaining <= 0) { m_client.Network.UnregisterCallback(PacketType.Default, HandlePacket); m_logStreamWriter.Close(); Console.WriteLine("Finished logging packets for {0}", m_client.Self.Name); m_isLogging = false; } } }
private void OctetQueueChanged(OctetQueue queue) { // log.Debug("OctetQueue changed {0}", queue); lastReceivedPacketTime = Timestamp.Now(); var tempBuf = new byte[32 * 1024]; while (true) { var octetCount = queue.Peek(tempBuf, 0, tempBuf.Length); if (octetCount <= 0) { return; } int octetsUsed = 0; var packet = PacketDecoder.Decode(tempBuf, 0, octetCount, out octetsUsed, log); if (packet == null) { return; } queue.Skip(octetsUsed); try { OnPacketRead(packet); } catch (Exception e) { log.Exception(e); throw e; } } }
public void Should_Get_Correct_Value(string hex, long expected) { var packet = PacketDecoder.DecodeString(hex); // Shouldn't really be doing it like this but oh well.. var result = packet.GetValue(); Assert.Equal(expected, result); }
public void TestCompletePacket() { var data = new byte[] { 0x06, 0x01, 0x48, 0x65, 0x6C, 0x6C, 0x6F }; int remainingOctets; var packet = PacketDecoder.Decode(data, 0, data.Length, out remainingOctets); Assert.That(0x01, Is.EqualTo(packet.Command)); }
public void Should_Parse_Correct_Version_Sum(string hex, int expected) { var packet = PacketDecoder.DecodeString(hex); var result = packet.GetVersionSum(); Assert.Equal(expected, result); }
public void TestIncompletePacket() { var data = new byte[] { 0x06, 0x01, 0x48, 0x65, 0x6C, 0x6C }; int nextOffset; var packet = PacketDecoder.Decode(data, 0, data.Length, out nextOffset); Assert.That(nextOffset, Is.EqualTo(0)); Assert.That(packet, Is.Null); }
public override string ToRawString(Direction direction) { if (direction == this.Direction) { return(PacketDecoder.PacketToString(this.Packet)); } else { return(String.Empty); } }
public void Initialize(string username, string password, ushort port, string ipAddressOfTheServer, ushort bufferSize, string clientId, ushort willFlag, ushort willReatin, uint willQoS, string willTopic, string willMessage, ushort keepAlivePeriod, ClientType clientType, uint publishQoSLevel, uint retain, uint cleanSession, string certificateFileName, string privateKeyFileName) { { MqttSettings.Instance.Username = username; MqttSettings.Instance.Password = password; MqttSettings.Instance.BufferSize = Convert.ToInt32(bufferSize); MqttSettings.Instance.Port = Convert.ToInt32(port); MqttSettings.Instance.IPAddressOfTheServer = IPAddress.Parse(ipAddressOfTheServer); } CrestronLogger.WriteToLog("Settings initialized", 1); { KeepAlivePeriod = keepAlivePeriod; ClientId = clientId; WillFlag = willFlag == 0 ? false : true; WillRetain = willReatin == 0 ? false : true; WillQosLevel = (byte)willQoS; WillTopic = willTopic; WillMessage = willMessage; Topics = new Dictionary <string, byte>(); PublishQoSLevel = publishQoSLevel; Retain = retain == 0 ? false : true; CleanSession = cleanSession == 0 ? false : true; } CrestronLogger.WriteToLog("CLIENT STUFF initialized", 1); { try { tcpClient = new SecureTCPClient(ipAddressOfTheServer.ToString(), port, bufferSize); if (certificateFileName != "//" && privateKeyFileName != "//") { var certificate = ReadFromResource(@"NVRAM\\" + certificateFileName); X509Certificate2 x509Cert = new X509Certificate2(certificate); tcpClient.SetClientCertificate(x509Cert); tcpClient.SetClientPrivateKey(ReadFromResource(@"NVRAM\\" + privateKeyFileName)); } tcpClient.SocketStatusChange += this.OnSocketStatusChange; PayloadMapper = new PayloadMapper(); PayloadMapper.ClientType = clientType; PacketDecoder = new PacketDecoder(); sessionManager = new MqttSessionManager(clientId); publisherManager = new MqttPublisherManager(sessionManager); publisherManager.PacketToSend += this.OnPacketToSend; } catch (Exception e) { OnErrorOccured("ERROR DURING INITIALIZATION: " + e.Message); } } CrestronLogger.WriteToLog("MQTTCLIENT - Initialize - completed : " + clientId, 1); }
public void TestMultiplePackets() { var data = new byte[] { 0x02, 0x01, 0x48, 0x01, 0x42 }; int nextOctetOffset; var packet = PacketDecoder.Decode(data, 0, data.Length, out nextOctetOffset); Assert.That(nextOctetOffset, Is.EqualTo(3)); Assert.That(packet.Command, Is.EqualTo(0x01)); Assert.That(packet.Length, Is.EqualTo(0x02)); int nextOctetOffset2; var packet2 = PacketDecoder.Decode(data, nextOctetOffset, data.Length - nextOctetOffset, out nextOctetOffset2); Assert.That(nextOctetOffset2, Is.EqualTo(5)); Assert.That(packet2.Command, Is.EqualTo(0x42)); Assert.That(packet2.Length, Is.EqualTo(0x01)); }
public static void Main(string[] args) { ReadWriteBuffer buffer = new ReadWriteBuffer(); buffer.WriteBytes(REQUEST); string targetID; byte[] rawData; bool b = PacketDecoder.TryReadPacket(buffer, out targetID, out rawData); Console.WriteLine(b); Console.WriteLine(targetID); Console.WriteLine(rawData); b = PacketDecoder.TryReadPacket(buffer, out targetID, out rawData); Console.WriteLine(b); Console.WriteLine(targetID); Console.WriteLine(rawData); }
/// <summary> /// Constructs the packet decpders for the dictionary. /// </summary> /// <returns></returns> private static Dictionary <int[], PacketDecoder> BuildDecoders() { Dictionary <int[], PacketDecoder> builder = new Dictionary <int[], PacketDecoder>(); try { Type[] classes = Assembly.GetExecutingAssembly().GetTypes().Where(a => a.Namespace == $"{Constants.NAMESPACE_PRESENTATION}.Network.Protocol.Packet.Decoder.Impl").ToArray(); foreach (Type decoder in classes) { PacketDecoder @class = Activator.CreateInstance(decoder) as PacketDecoder; builder.Add(@class.GetPacketIds(), @class); } } catch (Exception e) { Console.WriteLine(e.StackTrace); } return(builder); }
private void DecodeButton_Click(object sender, RoutedEventArgs e) { var text = Regex.Replace(new TextRange(TextInput.Document.ContentStart, TextInput.Document.ContentEnd).Text, @"\t|\n|\r|\s", ""); ExpandTreeViewButton.Visibility = Visibility.Visible; TextInput.Document.Blocks.Clear(); TextInput.Document.Blocks.Add(new Paragraph(new Run(text.ToUpper()))); if (string.IsNullOrWhiteSpace(text)) { MessageBox.Show("Insert data."); return; } try { string transferType; if (tcpRadioButton.IsChecked != null && (bool)tcpRadioButton.IsChecked) { transferType = "TCP"; } else { transferType = "UDP"; } CompositeData data = new PacketDecoder().Decode(transferType, text); HandleGpsListView(data); HandleAvlTableDataGrid(data); treeView.ItemsSource = data.Data; } catch (Exception ex) { MessageBox.Show("Corrupted data inserted."); } }
void ProxyManager_OnPacketLog(Packet packet, GridProxy.Direction direction, System.Net.IPEndPoint endpoint) { Application.Invoke((xsender, xe) => { PacketCounter++; if (direction == GridProxy.Direction.Incoming) { PacketsInCounter++; PacketsInBytes += packet.Length; } else { PacketsOutCounter++; PacketsOutBytes += packet.Length; } SessionPacket sessionPacket = new SessionPacket(packet, direction, endpoint, PacketDecoder.InterpretOptions(packet.Header) + " Seq: " + packet.Header.Sequence.ToString() + " Freq:" + packet.Header.Frequency.ToString()); sessionPacket.Columns = new string[] { PacketCounter.ToString(), sessionPacket.TimeStamp.ToString("HH:mm:ss.fff"), sessionPacket.Protocol, sessionPacket.Name, sessionPacket.Length.ToString(), sessionPacket.Host, sessionPacket.ContentType }; messages.AddSession(sessionPacket); }); }
private async void StartPollingLoop() { while (Running) { var reader = _inboundReader; try { await reader.LoadAsync(PacketDecoder.PACKET_HEADER_LENGTH); var packet = await PacketDecoder.DecodePacket(reader); await OnPacketReceived(packet); } catch (Exception e) { if (Running) { DebugLogger.LogExceptionX(e); OnDisconnect?.Invoke(this, true); Restart(); } return; } } }
public void Initialize( string clientID, string brokerAddress, ushort brokerPort, ushort enableSSL, string username, string password, ushort willFlag, ushort willRetain, uint willQoS, string willTopic, string willMessage, uint cleanSession, ushort bufferSize ) { MqttSettings.Instance.Username = username; MqttSettings.Instance.Password = password; MqttSettings.Instance.BufferSize = Convert.ToInt32(bufferSize); MqttSettings.Instance.Port = Convert.ToInt32(brokerPort); MqttSettings.Instance.Broker = brokerAddress; EnableSSL = (enableSSL > 0); CrestronLogger.WriteToLog("Instance Settings initialized", 1); KeepAlivePeriod = 0; // currently set to 0, as the keepalive mechanism has not been implemented ClientID = clientID; WillFlag = willFlag == 0 ? false : true; WillRetain = willRetain == 0 ? false : true; WillQosLevel = (byte)willQoS; WillTopic = willTopic; WillMessage = willMessage; Subscriptions = new Dictionary <string, byte>(); CleanSession = cleanSession == 0 ? false : true; CrestronLogger.WriteToLog("Client settings initialized", 1); try { if (EnableSSL) { SSLClient = new SecureTCPClient(brokerAddress.ToString(), brokerPort, bufferSize); if (CertificateFile != "" && KeyFile != "") { var certificate = ReadFromResource(@"NVRAM\\" + CertificateFile); X509Certificate2 x509Cert = new X509Certificate2(certificate); SSLClient.SetClientCertificate(x509Cert); SSLClient.SetClientPrivateKey(ReadFromResource(@"NVRAM\\" + KeyFile)); } SSLClient.SocketStatusChange += this.OnSSLSocketStatusChange; } else { NoSSLClient = new TCPClient(brokerAddress.ToString(), brokerPort, bufferSize); NoSSLClient.SocketStatusChange += this.OnNoSSLSocketStatusChange; } PacketDecoder = new PacketDecoder(); sessionManager = new MqttSessionManager(clientID); publisherManager = new MqttPublisherManager(sessionManager); publisherManager.PacketToSend += this.OnPacketToSend; } catch (Exception e) { OnErrorOccured("ERROR DURING INITIALIZATION: " + e.Message); } CrestronLogger.WriteToLog("MQTTCLIENT - Initialize - completed : " + clientID, 1); }
public TSharkPacketDecoderProcess(string pipename, PacketDecoder decoder) : base(pipename) { m_decoder = decoder; }