|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625 |
- using System;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using MQTTnet.Core.Channel;
- using MQTTnet.Core.Exceptions;
- using MQTTnet.Core.Packets;
- using MQTTnet.Core.Protocol;
-
- namespace MQTTnet.Core.Serializer
- {
- public sealed class MqttPacketSerializer : IMqttPacketSerializer
- {
- private static byte[] ProtocolVersionV311Name { get; } = Encoding.UTF8.GetBytes("MQTT");
- private static byte[] ProtocolVersionV310Name { get; } = Encoding.UTF8.GetBytes("MQIs");
-
- public MqttProtocolVersion ProtocolVersion { get; set; } = MqttProtocolVersion.V311;
-
- public Task SerializeAsync(MqttBasePacket packet, IMqttCommunicationChannel destination)
- {
- if (packet == null) throw new ArgumentNullException(nameof(packet));
- if (destination == null) throw new ArgumentNullException(nameof(destination));
-
- if (packet is MqttConnectPacket connectPacket)
- {
- return SerializeAsync(connectPacket, destination);
- }
-
- if (packet is MqttConnAckPacket connAckPacket)
- {
- return SerializeAsync(connAckPacket, destination);
- }
-
- if (packet is MqttDisconnectPacket disconnectPacket)
- {
- return SerializeAsync(disconnectPacket, destination);
- }
-
- if (packet is MqttPingReqPacket pingReqPacket)
- {
- return SerializeAsync(pingReqPacket, destination);
- }
-
- if (packet is MqttPingRespPacket pingRespPacket)
- {
- return SerializeAsync(pingRespPacket, destination);
- }
-
- if (packet is MqttPublishPacket publishPacket)
- {
- return SerializeAsync(publishPacket, destination);
- }
-
- if (packet is MqttPubAckPacket pubAckPacket)
- {
- return SerializeAsync(pubAckPacket, destination);
- }
-
- if (packet is MqttPubRecPacket pubRecPacket)
- {
- return SerializeAsync(pubRecPacket, destination);
- }
-
- if (packet is MqttPubRelPacket pubRelPacket)
- {
- return SerializeAsync(pubRelPacket, destination);
- }
-
- if (packet is MqttPubCompPacket pubCompPacket)
- {
- return SerializeAsync(pubCompPacket, destination);
- }
-
- if (packet is MqttSubscribePacket subscribePacket)
- {
- return SerializeAsync(subscribePacket, destination);
- }
-
- if (packet is MqttSubAckPacket subAckPacket)
- {
- return SerializeAsync(subAckPacket, destination);
- }
-
- if (packet is MqttUnsubscribePacket unsubscribePacket)
- {
- return SerializeAsync(unsubscribePacket, destination);
- }
-
- if (packet is MqttUnsubAckPacket unsubAckPacket)
- {
- return SerializeAsync(unsubAckPacket, destination);
- }
-
- throw new MqttProtocolViolationException("Packet type invalid.");
- }
-
- public async Task<MqttBasePacket> DeserializeAsync(IMqttCommunicationChannel source)
- {
- if (source == null) throw new ArgumentNullException(nameof(source));
-
- using (var mqttPacketReader = new MqttPacketReader(source))
- {
- await mqttPacketReader.ReadToEndAsync();
-
- switch (mqttPacketReader.ControlPacketType)
- {
- case MqttControlPacketType.Connect:
- {
- return await DeserializeConnectAsync(mqttPacketReader);
- }
-
- case MqttControlPacketType.ConnAck:
- {
- return await DeserializeConnAck(mqttPacketReader);
- }
-
- case MqttControlPacketType.Disconnect:
- {
- return new MqttDisconnectPacket();
- }
-
- case MqttControlPacketType.Publish:
- {
- return await DeserializePublishAsync(mqttPacketReader);
- }
-
- case MqttControlPacketType.PubAck:
- {
- return new MqttPubAckPacket
- {
- PacketIdentifier = await mqttPacketReader.ReadRemainingDataUShortAsync()
- };
- }
-
- case MqttControlPacketType.PubRec:
- {
- return new MqttPubRecPacket
- {
- PacketIdentifier = await mqttPacketReader.ReadRemainingDataUShortAsync()
- };
- }
-
- case MqttControlPacketType.PubRel:
- {
- return new MqttPubRelPacket
- {
- PacketIdentifier = await mqttPacketReader.ReadRemainingDataUShortAsync()
- };
- }
-
- case MqttControlPacketType.PubComp:
- {
- return new MqttPubCompPacket
- {
- PacketIdentifier = await mqttPacketReader.ReadRemainingDataUShortAsync()
- };
- }
-
- case MqttControlPacketType.PingReq:
- {
- return new MqttPingReqPacket();
- }
-
- case MqttControlPacketType.PingResp:
- {
- return new MqttPingRespPacket();
- }
-
- case MqttControlPacketType.Subscribe:
- {
- return await DeserializeSubscribeAsync(mqttPacketReader);
- }
-
- case MqttControlPacketType.SubAck:
- {
- return await DeserializeSubAck(mqttPacketReader);
- }
-
- case MqttControlPacketType.Unsubscibe:
- {
- return await DeserializeUnsubscribeAsync(mqttPacketReader);
- }
-
- case MqttControlPacketType.UnsubAck:
- {
- return new MqttUnsubAckPacket
- {
- PacketIdentifier = await mqttPacketReader.ReadRemainingDataUShortAsync()
- };
- }
-
- default:
- {
- throw new MqttProtocolViolationException($"Packet type ({(int)mqttPacketReader.ControlPacketType}) not supported.");
- }
- }
- }
- }
-
- private static async Task<MqttBasePacket> DeserializeUnsubscribeAsync(MqttPacketReader reader)
- {
- var packet = new MqttUnsubscribePacket
- {
- PacketIdentifier = await reader.ReadRemainingDataUShortAsync(),
- };
-
- while (!reader.EndOfRemainingData)
- {
- packet.TopicFilters.Add(await reader.ReadRemainingDataStringWithLengthPrefixAsync());
- }
-
- return packet;
- }
-
- private static async Task<MqttBasePacket> DeserializeSubscribeAsync(MqttPacketReader reader)
- {
- var packet = new MqttSubscribePacket
- {
- PacketIdentifier = await reader.ReadRemainingDataUShortAsync(),
- };
-
- while (!reader.EndOfRemainingData)
- {
- packet.TopicFilters.Add(new TopicFilter(
- await reader.ReadRemainingDataStringWithLengthPrefixAsync(),
- (MqttQualityOfServiceLevel)await reader.ReadRemainingDataByteAsync()));
- }
-
- return packet;
- }
-
- private static async Task<MqttBasePacket> DeserializePublishAsync(MqttPacketReader reader)
- {
- var fixedHeader = new ByteReader(reader.FixedHeader);
- var retain = fixedHeader.Read();
- var qualityOfServiceLevel = (MqttQualityOfServiceLevel)fixedHeader.Read(2);
- var dup = fixedHeader.Read();
-
- var topic = await reader.ReadRemainingDataStringWithLengthPrefixAsync();
-
- ushort packetIdentifier = 0;
- if (qualityOfServiceLevel > MqttQualityOfServiceLevel.AtMostOnce)
- {
- packetIdentifier = await reader.ReadRemainingDataUShortAsync();
- }
-
- var packet = new MqttPublishPacket
- {
- Retain = retain,
- QualityOfServiceLevel = qualityOfServiceLevel,
- Dup = dup,
- Topic = topic,
- Payload = await reader.ReadRemainingDataAsync(),
- PacketIdentifier = packetIdentifier
- };
-
- return packet;
- }
-
- private static async Task<MqttBasePacket> DeserializeConnectAsync(MqttPacketReader reader)
- {
- await reader.ReadRemainingDataAsync(2); // Skip 2 bytes
-
- MqttProtocolVersion protocolVersion;
- var protocolName = await reader.ReadRemainingDataAsync(4);
- if (protocolName.SequenceEqual(ProtocolVersionV310Name))
- {
- await reader.ReadRemainingDataAsync(2);
- protocolVersion = MqttProtocolVersion.V310;
- }
- else if (protocolName.SequenceEqual(ProtocolVersionV311Name))
- {
- protocolVersion = MqttProtocolVersion.V311;
- }
- else
- {
- throw new MqttProtocolViolationException("Protocol name is not supported.");
- }
-
- var protocolLevel = await reader.ReadRemainingDataByteAsync();
- var connectFlags = await reader.ReadRemainingDataByteAsync();
-
- var connectFlagsReader = new ByteReader(connectFlags);
- connectFlagsReader.Read(); // Reserved.
-
- var packet = new MqttConnectPacket
- {
- ProtocolVersion = protocolVersion,
- CleanSession = connectFlagsReader.Read()
- };
-
- var willFlag = connectFlagsReader.Read();
- var willQoS = connectFlagsReader.Read(2);
- var willRetain = connectFlagsReader.Read();
- var passwordFlag = connectFlagsReader.Read();
- var usernameFlag = connectFlagsReader.Read();
-
- packet.KeepAlivePeriod = await reader.ReadRemainingDataUShortAsync();
- packet.ClientId = await reader.ReadRemainingDataStringWithLengthPrefixAsync();
-
- if (willFlag)
- {
- packet.WillMessage = new MqttApplicationMessage(
- await reader.ReadRemainingDataStringWithLengthPrefixAsync(),
- await reader.ReadRemainingDataWithLengthPrefixAsync(),
- (MqttQualityOfServiceLevel)willQoS,
- willRetain);
- }
-
- if (usernameFlag)
- {
- packet.Username = await reader.ReadRemainingDataStringWithLengthPrefixAsync();
- }
-
- if (passwordFlag)
- {
- packet.Password = await reader.ReadRemainingDataStringWithLengthPrefixAsync();
- }
-
- ValidateConnectPacket(packet);
- return packet;
- }
-
- private static async Task<MqttBasePacket> DeserializeSubAck(MqttPacketReader reader)
- {
- var packet = new MqttSubAckPacket
- {
- PacketIdentifier = await reader.ReadRemainingDataUShortAsync()
- };
-
- while (!reader.EndOfRemainingData)
- {
- packet.SubscribeReturnCodes.Add((MqttSubscribeReturnCode)await reader.ReadRemainingDataByteAsync());
- }
-
- return packet;
- }
-
- private static async Task<MqttBasePacket> DeserializeConnAck(MqttPacketReader reader)
- {
- var variableHeader1 = await reader.ReadRemainingDataByteAsync();
- var variableHeader2 = await reader.ReadRemainingDataByteAsync();
-
- var packet = new MqttConnAckPacket
- {
- IsSessionPresent = new ByteReader(variableHeader1).Read(),
- ConnectReturnCode = (MqttConnectReturnCode)variableHeader2
- };
-
- return packet;
- }
-
- private static void ValidateConnectPacket(MqttConnectPacket packet)
- {
- if (string.IsNullOrEmpty(packet.ClientId) && !packet.CleanSession)
- {
- throw new MqttProtocolViolationException("CleanSession must be set if ClientId is empty [MQTT-3.1.3-7].");
- }
- }
-
- private static void ValidatePublishPacket(MqttPublishPacket packet)
- {
- if (packet.QualityOfServiceLevel == 0 && packet.Dup)
- {
- throw new MqttProtocolViolationException("Dup flag must be false for QoS 0 packets [MQTT-3.3.1-2].");
- }
- }
-
- private Task SerializeAsync(MqttConnectPacket packet, IMqttCommunicationChannel destination)
- {
- ValidateConnectPacket(packet);
-
- using (var output = new MqttPacketWriter())
- {
- // Write variable header
- output.Write(0x00, 0x04); // 3.1.2.1 Protocol Name
- if (ProtocolVersion == MqttProtocolVersion.V311)
- {
- output.Write(ProtocolVersionV311Name);
- output.Write(0x04); // 3.1.2.2 Protocol Level (4)
- }
- else
- {
- output.Write(ProtocolVersionV310Name);
- output.Write(0x64);
- output.Write(0x70);
- output.Write(0x03); // Protocol Level (3)
- }
-
- var connectFlags = new ByteWriter(); // 3.1.2.3 Connect Flags
- connectFlags.Write(false); // Reserved
- connectFlags.Write(packet.CleanSession);
- connectFlags.Write(packet.WillMessage != null);
-
- if (packet.WillMessage != null)
- {
- connectFlags.Write((int)packet.WillMessage.QualityOfServiceLevel, 2);
- connectFlags.Write(packet.WillMessage.Retain);
- }
- else
- {
- connectFlags.Write(0, 2);
- connectFlags.Write(false);
- }
-
- connectFlags.Write(packet.Password != null);
- connectFlags.Write(packet.Username != null);
-
- output.Write(connectFlags);
- output.Write(packet.KeepAlivePeriod);
- output.WriteWithLengthPrefix(packet.ClientId);
-
- if (packet.WillMessage != null)
- {
- output.WriteWithLengthPrefix(packet.WillMessage.Topic);
- output.WriteWithLengthPrefix(packet.WillMessage.Payload);
- }
-
- if (packet.Username != null)
- {
- output.WriteWithLengthPrefix(packet.Username);
- }
-
- if (packet.Password != null)
- {
- output.WriteWithLengthPrefix(packet.Password);
- }
-
- output.InjectFixedHeader(MqttControlPacketType.Connect);
- return output.WriteToAsync(destination);
- }
- }
-
- private Task SerializeAsync(MqttConnAckPacket packet, IMqttCommunicationChannel destination)
- {
- using (var output = new MqttPacketWriter())
- {
- var connectAcknowledgeFlags = new ByteWriter();
-
- if (ProtocolVersion == MqttProtocolVersion.V311)
- {
- connectAcknowledgeFlags.Write(packet.IsSessionPresent);
- }
-
- output.Write(connectAcknowledgeFlags);
- output.Write((byte)packet.ConnectReturnCode);
-
- output.InjectFixedHeader(MqttControlPacketType.ConnAck);
- return output.WriteToAsync(destination);
- }
- }
-
- private static async Task SerializeAsync(MqttPubRelPacket packet, IMqttCommunicationChannel destination)
- {
- using (var output = new MqttPacketWriter())
- {
- output.Write(packet.PacketIdentifier);
-
- output.InjectFixedHeader(MqttControlPacketType.PubRel, 0x02);
- await output.WriteToAsync(destination);
- }
- }
-
- private static Task SerializeAsync(MqttDisconnectPacket packet, IMqttCommunicationChannel destination)
- {
- return SerializeEmptyPacketAsync(MqttControlPacketType.Disconnect, destination);
- }
-
- private static Task SerializeAsync(MqttPingReqPacket packet, IMqttCommunicationChannel destination)
- {
- return SerializeEmptyPacketAsync(MqttControlPacketType.PingReq, destination);
- }
-
- private static Task SerializeAsync(MqttPingRespPacket packet, IMqttCommunicationChannel destination)
- {
- return SerializeEmptyPacketAsync(MqttControlPacketType.PingResp, destination);
- }
-
- private static Task SerializeAsync(MqttPublishPacket packet, IMqttCommunicationChannel destination)
- {
- ValidatePublishPacket(packet);
-
- using (var output = new MqttPacketWriter())
- {
- output.WriteWithLengthPrefix(packet.Topic);
-
- if (packet.QualityOfServiceLevel > MqttQualityOfServiceLevel.AtMostOnce)
- {
- output.Write(packet.PacketIdentifier);
- }
- else
- {
- if (packet.PacketIdentifier > 0)
- {
- throw new MqttProtocolViolationException("Packet identifier must be empty if QoS == 0 [MQTT-2.3.1-5].");
- }
- }
-
- if (packet.Payload?.Length > 0)
- {
- output.Write(packet.Payload);
- }
-
- var fixedHeader = new ByteWriter();
- fixedHeader.Write(packet.Retain);
- fixedHeader.Write((byte)packet.QualityOfServiceLevel, 2);
- fixedHeader.Write(packet.Dup);
-
- output.InjectFixedHeader(MqttControlPacketType.Publish, fixedHeader.Value);
- return output.WriteToAsync(destination);
- }
- }
-
- private static Task SerializeAsync(MqttPubAckPacket packet, IMqttCommunicationChannel destination)
- {
- using (var output = new MqttPacketWriter())
- {
- output.Write(packet.PacketIdentifier);
-
- output.InjectFixedHeader(MqttControlPacketType.PubAck);
- return output.WriteToAsync(destination);
- }
- }
-
- private static Task SerializeAsync(MqttPubRecPacket packet, IMqttCommunicationChannel destination)
- {
- using (var output = new MqttPacketWriter())
- {
- output.Write(packet.PacketIdentifier);
-
- output.InjectFixedHeader(MqttControlPacketType.PubRec);
- return output.WriteToAsync(destination);
- }
- }
-
- private static Task SerializeAsync(MqttPubCompPacket packet, IMqttCommunicationChannel destination)
- {
- using (var output = new MqttPacketWriter())
- {
- output.Write(packet.PacketIdentifier);
-
- output.InjectFixedHeader(MqttControlPacketType.PubComp);
- return output.WriteToAsync(destination);
- }
- }
-
- private static Task SerializeAsync(MqttSubscribePacket packet, IMqttCommunicationChannel destination)
- {
- using (var output = new MqttPacketWriter())
- {
- output.Write(packet.PacketIdentifier);
-
- if (packet.TopicFilters?.Count > 0)
- {
- foreach (var topicFilter in packet.TopicFilters)
- {
- output.WriteWithLengthPrefix(topicFilter.Topic);
- output.Write((byte)topicFilter.QualityOfServiceLevel);
- }
- }
-
- output.InjectFixedHeader(MqttControlPacketType.Subscribe, 0x02);
- return output.WriteToAsync(destination);
- }
- }
-
- private static Task SerializeAsync(MqttSubAckPacket packet, IMqttCommunicationChannel destination)
- {
- using (var output = new MqttPacketWriter())
- {
- output.Write(packet.PacketIdentifier);
-
- if (packet.SubscribeReturnCodes?.Any() == true)
- {
- foreach (var packetSubscribeReturnCode in packet.SubscribeReturnCodes)
- {
- output.Write((byte)packetSubscribeReturnCode);
- }
- }
-
- output.InjectFixedHeader(MqttControlPacketType.SubAck);
- return output.WriteToAsync(destination);
- }
- }
-
- private static Task SerializeAsync(MqttUnsubscribePacket packet, IMqttCommunicationChannel destination)
- {
- using (var output = new MqttPacketWriter())
- {
- output.Write(packet.PacketIdentifier);
-
- if (packet.TopicFilters?.Any() == true)
- {
- foreach (var topicFilter in packet.TopicFilters)
- {
- output.WriteWithLengthPrefix(topicFilter);
- }
- }
-
- output.InjectFixedHeader(MqttControlPacketType.Unsubscibe, 0x02);
- return output.WriteToAsync(destination);
- }
- }
-
- private static Task SerializeAsync(MqttUnsubAckPacket packet, IMqttCommunicationChannel destination)
- {
- using (var output = new MqttPacketWriter())
- {
- output.Write(packet.PacketIdentifier);
-
- output.InjectFixedHeader(MqttControlPacketType.UnsubAck);
- return output.WriteToAsync(destination);
- }
- }
-
- private static Task SerializeEmptyPacketAsync(MqttControlPacketType type, IMqttCommunicationChannel destination)
- {
- using (var output = new MqttPacketWriter())
- {
- output.InjectFixedHeader(type);
- return output.WriteToAsync(destination);
- }
- }
- }
- }
|