PositiveNameQueryResponse.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* Copyright (C) 2014-2020 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Text;
  11. using Utilities;
  12. namespace SMBLibrary.NetBios
  13. {
  14. /// <summary>
  15. /// [RFC 1002] 4.2.13. POSITIVE NAME QUERY RESPONSE
  16. /// </summary>
  17. public class PositiveNameQueryResponse
  18. {
  19. public const int EntryLength = 6;
  20. public NameServicePacketHeader Header;
  21. public ResourceRecord Resource;
  22. // Resource Data:
  23. public KeyValuePairList<byte[], NameFlags> Addresses = new KeyValuePairList<byte[], NameFlags>();
  24. public PositiveNameQueryResponse()
  25. {
  26. Header = new NameServicePacketHeader();
  27. Header.Flags = OperationFlags.AuthoritativeAnswer | OperationFlags.RecursionDesired;
  28. Header.OpCode = NameServiceOperation.QueryResponse;
  29. Header.ANCount = 1;
  30. Resource = new ResourceRecord(NameRecordType.NB);
  31. }
  32. public PositiveNameQueryResponse(byte[] buffer, int offset)
  33. {
  34. Header = new NameServicePacketHeader(buffer, ref offset);
  35. Resource = new ResourceRecord(buffer, ref offset);
  36. int position = 0;
  37. while (position < Resource.Data.Length)
  38. {
  39. NameFlags nameFlags = (NameFlags)BigEndianReader.ReadUInt16(Resource.Data, ref position);
  40. byte[] address = ByteReader.ReadBytes(Resource.Data, ref position, 4);
  41. Addresses.Add(address, nameFlags);
  42. }
  43. }
  44. public byte[] GetBytes()
  45. {
  46. Resource.Data = GetData();
  47. MemoryStream stream = new MemoryStream();
  48. Header.WriteBytes(stream);
  49. Resource.WriteBytes(stream);
  50. return stream.ToArray();
  51. }
  52. private byte[] GetData()
  53. {
  54. byte[] data = new byte[EntryLength * Addresses.Count];
  55. int offset = 0;
  56. foreach (KeyValuePair<byte[], NameFlags> entry in Addresses)
  57. {
  58. BigEndianWriter.WriteUInt16(data, ref offset, (ushort)entry.Value);
  59. ByteWriter.WriteBytes(data, ref offset, entry.Key, 4);
  60. }
  61. return data;
  62. }
  63. }
  64. }