ServerName.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.IO;
  5. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls
  6. {
  7. /// <summary>RFC 6066 3. Server Name Indication</summary>
  8. /// <remarks>
  9. /// Current implementation uses this guidance: "For backward compatibility, all future data structures associated
  10. /// with new NameTypes MUST begin with a 16-bit length field. TLS MAY treat provided server names as opaque data
  11. /// and pass the names and types to the application.". RFC 6066 specifies ASCII encoding for host_name (possibly
  12. /// using A-labels for IDNs), but note that the previous version (RFC 4366) specified UTF-8 encoding (see RFC 6066
  13. /// Appendix A). For maximum compatibility, it is recommended that client code tolerate receiving UTF-8 from the
  14. /// peer, but only generate ASCII itself.
  15. /// </remarks>
  16. public sealed class ServerName
  17. {
  18. private readonly short nameType;
  19. private readonly byte[] nameData;
  20. public ServerName(short nameType, byte[] nameData)
  21. {
  22. if (!TlsUtilities.IsValidUint8(nameType))
  23. throw new ArgumentException("must be from 0 to 255", "nameType");
  24. if (null == nameData)
  25. throw new ArgumentNullException("nameData");
  26. if (nameData.Length < 1 || !TlsUtilities.IsValidUint16(nameData.Length))
  27. throw new ArgumentException("must have length from 1 to 65535", "nameData");
  28. this.nameType = nameType;
  29. this.nameData = nameData;
  30. }
  31. public byte[] NameData
  32. {
  33. get { return nameData; }
  34. }
  35. public short NameType
  36. {
  37. get { return nameType; }
  38. }
  39. /// <summary>Encode this <see cref="ServerName"/> to a <see cref="Stream"/>.</summary>
  40. /// <param name="output">the <see cref="Stream"/> to encode to.</param>
  41. /// <exception cref="IOException"/>
  42. public void Encode(Stream output)
  43. {
  44. TlsUtilities.WriteUint8(nameType, output);
  45. TlsUtilities.WriteOpaque16(nameData, output);
  46. }
  47. /// <summary>Parse a <see cref="ServerName"/> from a <see cref="Stream"/>.</summary>
  48. /// <param name="input">the <see cref="Stream"/> to parse from.</param>
  49. /// <returns>a <see cref="ServerName"/> object.</returns>
  50. /// <exception cref="IOException"/>
  51. public static ServerName Parse(Stream input)
  52. {
  53. short name_type = TlsUtilities.ReadUint8(input);
  54. byte[] nameData = TlsUtilities.ReadOpaque16(input, 1);
  55. return new ServerName(name_type, nameData);
  56. }
  57. }
  58. }
  59. #pragma warning restore
  60. #endif