You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

83 lines
2.5 KiB

  1. using System;
  2. using System.Buffers;
  3. using MQTTnet.Adapter;
  4. using MQTTnet.Exceptions;
  5. using MQTTnet.Packets;
  6. using MQTTnet.Serializer;
  7. namespace MQTTnet.AspNetCore
  8. {
  9. public static class ReaderExtensions
  10. {
  11. public static bool TryDeserialize(this IMqttPacketSerializer serializer, in ReadOnlySequence<byte> input, out MqttBasePacket packet, out SequencePosition consumed, out SequencePosition observed)
  12. {
  13. packet = null;
  14. consumed = input.Start;
  15. observed = input.End;
  16. var copy = input;
  17. if (copy.Length < 2)
  18. {
  19. return false;
  20. }
  21. var fixedheader = copy.First.Span[0];
  22. if (!TryReadBodyLength(ref copy, out var bodyLength))
  23. {
  24. return false;
  25. }
  26. var bodySlice = copy.Slice(0, bodyLength);
  27. packet = serializer.Deserialize(new ReceivedMqttPacket(fixedheader, new MqttPacketBodyReader(bodySlice.GetArray(), 0)));
  28. consumed = bodySlice.End;
  29. observed = bodySlice.End;
  30. return true;
  31. }
  32. private static byte[] GetArray(this in ReadOnlySequence<byte> input)
  33. {
  34. if (input.IsSingleSegment)
  35. {
  36. return input.First.Span.ToArray();
  37. }
  38. // Should be rare
  39. return input.ToArray();
  40. }
  41. private static bool TryReadBodyLength(ref ReadOnlySequence<byte> input, out int result)
  42. {
  43. // Alorithm taken from https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/errata01/os/mqtt-v3.1.1-errata01-os-complete.html.
  44. var multiplier = 1;
  45. var value = 0;
  46. byte encodedByte;
  47. var index = 1;
  48. result = 0;
  49. var temp = input.Slice(0, Math.Min(5, input.Length)).GetArray();
  50. do
  51. {
  52. if (index == temp.Length)
  53. {
  54. return false;
  55. }
  56. encodedByte = temp[index];
  57. index++;
  58. value += (byte)(encodedByte & 127) * multiplier;
  59. if (multiplier > 128 * 128 * 128)
  60. {
  61. throw new MqttProtocolViolationException($"Remaining length is invalid (Data={string.Join(",", temp.AsSpan(1, index).ToArray())}).");
  62. }
  63. multiplier *= 128;
  64. } while ((encodedByte & 128) != 0);
  65. input = input.Slice(index);
  66. result = value;
  67. return true;
  68. }
  69. }
  70. }