header.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. package header
  2. import (
  3. "encoding/binary"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. )
  8. //Version 1 header:
  9. // 0 31
  10. // |------------------------------------------------------------------------------------|
  11. // | Version (uint4) | Type (uint4) | Subtype (uint8) | Reserved (uint8) | Lane (uint8) | 32
  12. // |------------------------------------------------------------------------------------|
  13. // | Remote index (uint32) | 64
  14. // |------------------------------------------------------------------------------------|
  15. // | Message counter | 96
  16. // | (uint64) | 128
  17. // |------------------------------------------------------------------------------------|
  18. // | payload... |
  19. //
  20. // Lane is the multiport lane index, carved out of the low 8 bits of what was a
  21. // single Reserved (uint16) before multiport. Lane 0 is the base tunnel, which is
  22. // what every sender that does not know about lanes emits and what every non-lane
  23. // packet — handshakes, lighthouse, relays, close — carries, so the field is
  24. // compatible in both directions with a peer that has never heard of it. The
  25. // remaining 8 bits stay reserved and are always sent as zero. The H struct still
  26. // holds the pair as one Reserved field; use H.Lane and EncodeLane to reach the
  27. // low byte.
  28. //
  29. // Lane is part of the AEAD's associated data, so a lane index cannot be altered
  30. // in flight: a packet decrypts on the lane it claims or not at all.
  31. type m = map[string]any
  32. const (
  33. Version uint8 = 1
  34. Len = 16
  35. )
  36. type MessageType uint8
  37. type MessageSubType uint8
  38. const (
  39. Handshake MessageType = 0
  40. Message MessageType = 1
  41. RecvError MessageType = 2
  42. LightHouse MessageType = 3
  43. Test MessageType = 4
  44. CloseTunnel MessageType = 5
  45. Control MessageType = 6
  46. )
  47. var typeMap = map[MessageType]string{
  48. Handshake: "handshake",
  49. Message: "message",
  50. RecvError: "recvError",
  51. LightHouse: "lightHouse",
  52. Test: "test",
  53. CloseTunnel: "closeTunnel",
  54. Control: "control",
  55. }
  56. const (
  57. MessageNone MessageSubType = 0
  58. MessageRelay MessageSubType = 1
  59. )
  60. const (
  61. TestRequest MessageSubType = 0
  62. TestReply MessageSubType = 1
  63. // LaneProbe is sent on a multiport lane to prove the lane's 5-tuple is
  64. // usable; LaneProbeAck answers it on the base tunnel.
  65. LaneProbe MessageSubType = 2
  66. LaneProbeAck MessageSubType = 3
  67. )
  68. // MaxLane is the largest lane index the header can carry.
  69. const MaxLane = 0xff
  70. // laneMask covers the bits of Reserved that hold the lane index.
  71. const laneMask uint16 = 0x00ff
  72. const (
  73. HandshakeIXPSK0 MessageSubType = 0
  74. HandshakeXXPSK0 MessageSubType = 1
  75. )
  76. var ErrHeaderTooShort = errors.New("header is too short")
  77. var subTypeTestMap = map[MessageSubType]string{
  78. TestRequest: "testRequest",
  79. TestReply: "testReply",
  80. LaneProbe: "laneProbe",
  81. LaneProbeAck: "laneProbeAck",
  82. }
  83. var subTypeNoneMap = map[MessageSubType]string{0: "none"}
  84. var subTypeMap = map[MessageType]*map[MessageSubType]string{
  85. Message: {
  86. MessageNone: "none",
  87. MessageRelay: "relay",
  88. },
  89. RecvError: &subTypeNoneMap,
  90. LightHouse: &subTypeNoneMap,
  91. Test: &subTypeTestMap,
  92. CloseTunnel: &subTypeNoneMap,
  93. Handshake: {
  94. HandshakeIXPSK0: "ix_psk0",
  95. },
  96. Control: &subTypeNoneMap,
  97. }
  98. type H struct {
  99. Version uint8
  100. Type MessageType
  101. Subtype MessageSubType
  102. Reserved uint16
  103. RemoteIndex uint32
  104. MessageCounter uint64
  105. }
  106. // Encode uses the provided byte array to encode the provided header values into.
  107. // Byte array must be capped higher than HeaderLen or this will panic
  108. func Encode(b []byte, v uint8, t MessageType, st MessageSubType, ri uint32, c uint64) []byte {
  109. return EncodeLane(b, v, t, st, ri, c, 0)
  110. }
  111. // EncodeLane is Encode with an explicit multiport lane index, which is carried
  112. // in the low 8 bits of Reserved.
  113. func EncodeLane(b []byte, v uint8, t MessageType, st MessageSubType, ri uint32, c uint64, lane uint8) []byte {
  114. b = b[:Len]
  115. b[0] = v<<4 | byte(t&0x0f)
  116. b[1] = byte(st)
  117. binary.BigEndian.PutUint16(b[2:4], uint16(lane))
  118. binary.BigEndian.PutUint32(b[4:8], ri)
  119. binary.BigEndian.PutUint64(b[8:16], c)
  120. return b
  121. }
  122. // String creates a readable string representation of a header
  123. func (h *H) String() string {
  124. if h == nil {
  125. return "<nil>"
  126. }
  127. return fmt.Sprintf("ver=%d type=%s subtype=%s reserved=%#x remoteindex=%v messagecounter=%v",
  128. h.Version, h.TypeName(), h.SubTypeName(), h.Reserved, h.RemoteIndex, h.MessageCounter)
  129. }
  130. // MarshalJSON creates a json string representation of a header
  131. func (h *H) MarshalJSON() ([]byte, error) {
  132. return json.Marshal(m{
  133. "version": h.Version,
  134. "type": h.TypeName(),
  135. "subType": h.SubTypeName(),
  136. "reserved": h.Reserved,
  137. "remoteIndex": h.RemoteIndex,
  138. "messageCounter": h.MessageCounter,
  139. })
  140. }
  141. // Encode turns header into bytes
  142. func (h *H) Encode(b []byte) ([]byte, error) {
  143. if h == nil {
  144. return nil, errors.New("nil header")
  145. }
  146. return EncodeLane(b, h.Version, h.Type, h.Subtype, h.RemoteIndex, h.MessageCounter, h.Lane()), nil
  147. }
  148. // Lane returns the multiport lane index carried in Reserved. Lane 0 is the base
  149. // tunnel, which is what any sender that does not know about lanes will report.
  150. func (h *H) Lane() uint8 {
  151. return uint8(h.Reserved & laneMask)
  152. }
  153. // Parse is a helper function to parses given bytes into new Header struct
  154. func (h *H) Parse(b []byte) error {
  155. if len(b) < Len {
  156. return ErrHeaderTooShort
  157. }
  158. // get upper 4 bytes
  159. h.Version = uint8((b[0] >> 4) & 0x0f)
  160. // get lower 4 bytes
  161. h.Type = MessageType(b[0] & 0x0f)
  162. h.Subtype = MessageSubType(b[1])
  163. h.Reserved = binary.BigEndian.Uint16(b[2:4])
  164. h.RemoteIndex = binary.BigEndian.Uint32(b[4:8])
  165. h.MessageCounter = binary.BigEndian.Uint64(b[8:16])
  166. return nil
  167. }
  168. // TypeName will transform the headers message type into a human string
  169. func (h *H) TypeName() string {
  170. return TypeName(h.Type)
  171. }
  172. // TypeName will transform a nebula message type into a human string
  173. func TypeName(t MessageType) string {
  174. if n, ok := typeMap[t]; ok {
  175. return n
  176. }
  177. return "unknown"
  178. }
  179. // SubTypeName will transform the headers message sub type into a human string
  180. func (h *H) SubTypeName() string {
  181. return SubTypeName(h.Type, h.Subtype)
  182. }
  183. func (h *H) IsValidSubType() bool {
  184. return IsValidSubType(h.Type, h.Subtype)
  185. }
  186. // SubTypeName will transform a nebula message sub type into a human string
  187. func SubTypeName(t MessageType, s MessageSubType) string {
  188. if n, ok := subTypeMap[t]; ok {
  189. if x, ok := (*n)[s]; ok {
  190. return x
  191. }
  192. }
  193. return "unknown"
  194. }
  195. func IsValidSubType(t MessageType, s MessageSubType) bool {
  196. switch t {
  197. case Message:
  198. return s == MessageNone || s == MessageRelay
  199. case Handshake:
  200. return s == HandshakeIXPSK0
  201. case Test:
  202. return s == TestReply || s == TestRequest || s == LaneProbe || s == LaneProbeAck
  203. case Control, CloseTunnel, RecvError, LightHouse:
  204. return s == 0
  205. default:
  206. return false
  207. }
  208. }
  209. // NewHeader turns bytes into a header
  210. func NewHeader(b []byte) (*H, error) {
  211. h := new(H)
  212. if err := h.Parse(b); err != nil {
  213. return nil, err
  214. }
  215. return h, nil
  216. }