message.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. package stun
  2. import (
  3. "crypto/rand"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "io"
  8. )
  9. const (
  10. // magicCookie is fixed value that aids in distinguishing STUN packets
  11. // from packets of other protocols when STUN is multiplexed with those
  12. // other protocols on the same Port.
  13. //
  14. // The magic cookie field MUST contain the fixed value 0x2112A442 in
  15. // network byte order.
  16. //
  17. // Defined in "STUN Message Structure", section 6.
  18. magicCookie = 0x2112A442
  19. attributeHeaderSize = 4
  20. messageHeaderSize = 20
  21. // TransactionIDSize is length of transaction id array (in bytes).
  22. TransactionIDSize = 12 // 96 bit
  23. )
  24. // NewTransactionID returns new random transaction ID using crypto/rand
  25. // as source.
  26. func NewTransactionID() (b [TransactionIDSize]byte) {
  27. readFullOrPanic(rand.Reader, b[:])
  28. return b
  29. }
  30. // IsMessage returns true if b looks like STUN message.
  31. // Useful for multiplexing. IsMessage does not guarantee
  32. // that decoding will be successful.
  33. func IsMessage(b []byte) bool {
  34. return len(b) >= messageHeaderSize && bin.Uint32(b[4:8]) == magicCookie
  35. }
  36. // New returns *Message with pre-allocated Raw.
  37. func New() *Message {
  38. const defaultRawCapacity = 120
  39. return &Message{
  40. Raw: make([]byte, messageHeaderSize, defaultRawCapacity),
  41. }
  42. }
  43. // ErrDecodeToNil occurs on Decode(data, nil) call.
  44. var ErrDecodeToNil = errors.New("attempt to decode to nil message")
  45. // Decode decodes Message from data to m, returning error if any.
  46. func Decode(data []byte, m *Message) error {
  47. if m == nil {
  48. return ErrDecodeToNil
  49. }
  50. m.Raw = append(m.Raw[:0], data...)
  51. return m.Decode()
  52. }
  53. // Message represents a single STUN packet. It uses aggressive internal
  54. // buffering to enable zero-allocation encoding and decoding,
  55. // so there are some usage constraints:
  56. //
  57. // Message, its fields, results of m.Get or any attribute a.GetFrom
  58. // are valid only until Message.Raw is not modified.
  59. type Message struct {
  60. Type MessageType
  61. Length uint32 // len(Raw) not including header
  62. TransactionID [TransactionIDSize]byte
  63. Attributes Attributes
  64. Raw []byte
  65. }
  66. // MarshalBinary implements the encoding.BinaryMarshaler interface.
  67. func (m Message) MarshalBinary() (data []byte, err error) {
  68. // We can't return m.Raw, allocation is expected by implicit interface
  69. // contract induced by other implementations.
  70. b := make([]byte, len(m.Raw))
  71. copy(b, m.Raw)
  72. return b, nil
  73. }
  74. // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
  75. func (m *Message) UnmarshalBinary(data []byte) error {
  76. // We can't retain data, copy is expected by interface contract.
  77. m.Raw = append(m.Raw[:0], data...)
  78. return m.Decode()
  79. }
  80. // GobEncode implements the gob.GobEncoder interface.
  81. func (m Message) GobEncode() ([]byte, error) {
  82. return m.MarshalBinary()
  83. }
  84. // GobDecode implements the gob.GobDecoder interface.
  85. func (m *Message) GobDecode(data []byte) error {
  86. return m.UnmarshalBinary(data)
  87. }
  88. // AddTo sets b.TransactionID to m.TransactionID.
  89. //
  90. // Implements Setter to aid in crafting responses.
  91. func (m *Message) AddTo(b *Message) error {
  92. b.TransactionID = m.TransactionID
  93. b.WriteTransactionID()
  94. return nil
  95. }
  96. // NewTransactionID sets m.TransactionID to random value from crypto/rand
  97. // and returns error if any.
  98. func (m *Message) NewTransactionID() error {
  99. _, err := io.ReadFull(rand.Reader, m.TransactionID[:])
  100. if err == nil {
  101. m.WriteTransactionID()
  102. }
  103. return err
  104. }
  105. func (m *Message) String() string {
  106. tID := base64.StdEncoding.EncodeToString(m.TransactionID[:])
  107. aInfo := ""
  108. for k, a := range m.Attributes {
  109. aInfo += fmt.Sprintf("attr%d=%s ", k, a.Type)
  110. }
  111. return fmt.Sprintf("%s l=%d attrs=%d id=%s, %s", m.Type, m.Length, len(m.Attributes), tID, aInfo)
  112. }
  113. // Reset resets Message, attributes and underlying buffer length.
  114. func (m *Message) Reset() {
  115. m.Raw = m.Raw[:0]
  116. m.Length = 0
  117. m.Attributes = m.Attributes[:0]
  118. }
  119. // grow ensures that internal buffer has n length.
  120. func (m *Message) grow(n int) {
  121. if len(m.Raw) >= n {
  122. return
  123. }
  124. if cap(m.Raw) >= n {
  125. m.Raw = m.Raw[:n]
  126. return
  127. }
  128. m.Raw = append(m.Raw, make([]byte, n-len(m.Raw))...)
  129. }
  130. // Add appends new attribute to message. Not goroutine-safe.
  131. //
  132. // Value of attribute is copied to internal buffer so
  133. // it is safe to reuse v.
  134. func (m *Message) Add(t AttrType, v []byte) {
  135. // Allocating buffer for TLV (type-length-value).
  136. // T = t, L = len(v), V = v.
  137. // m.Raw will look like:
  138. // [0:20] <- message header
  139. // [20:20+m.Length] <- existing message attributes
  140. // [20+m.Length:20+m.Length+len(v) + 4] <- allocated buffer for new TLV
  141. // [first:last] <- same as previous
  142. // [0 1|2 3|4 4 + len(v)] <- mapping for allocated buffer
  143. // T L V
  144. allocSize := attributeHeaderSize + len(v) // ~ len(TLV) = len(TL) + len(V)
  145. first := messageHeaderSize + int(m.Length) // first byte number
  146. last := first + allocSize // last byte number
  147. m.grow(last) // growing cap(Raw) to fit TLV
  148. m.Raw = m.Raw[:last] // now len(Raw) = last
  149. m.Length += uint32(allocSize) // rendering length change
  150. // Sub-slicing internal buffer to simplify encoding.
  151. buf := m.Raw[first:last] // slice for TLV
  152. value := buf[attributeHeaderSize:] // slice for V
  153. attr := RawAttribute{
  154. Type: t, // T
  155. Length: uint16(len(v)), // L
  156. Value: value, // V
  157. }
  158. // Encoding attribute TLV to allocated buffer.
  159. bin.PutUint16(buf[0:2], attr.Type.Value()) // T
  160. bin.PutUint16(buf[2:4], attr.Length) // L
  161. copy(value, v) // V
  162. // Checking that attribute value needs padding.
  163. if attr.Length%padding != 0 {
  164. // Performing padding.
  165. bytesToAdd := nearestPaddedValueLength(len(v)) - len(v)
  166. last += bytesToAdd
  167. m.grow(last)
  168. // setting all padding bytes to zero
  169. // to prevent data leak from previous
  170. // data in next bytesToAdd bytes
  171. buf = m.Raw[last-bytesToAdd : last]
  172. for i := range buf {
  173. buf[i] = 0
  174. }
  175. m.Raw = m.Raw[:last] // increasing buffer length
  176. m.Length += uint32(bytesToAdd) // rendering length change
  177. }
  178. m.Attributes = append(m.Attributes, attr)
  179. m.WriteLength()
  180. }
  181. func attrSliceEqual(a, b Attributes) bool {
  182. for _, attr := range a {
  183. found := false
  184. for _, attrB := range b {
  185. if attrB.Type != attr.Type {
  186. continue
  187. }
  188. if attrB.Equal(attr) {
  189. found = true
  190. break
  191. }
  192. }
  193. if !found {
  194. return false
  195. }
  196. }
  197. return true
  198. }
  199. func attrEqual(a, b Attributes) bool {
  200. if a == nil && b == nil {
  201. return true
  202. }
  203. if a == nil || b == nil {
  204. return false
  205. }
  206. if len(a) != len(b) {
  207. return false
  208. }
  209. if !attrSliceEqual(a, b) {
  210. return false
  211. }
  212. if !attrSliceEqual(b, a) {
  213. return false
  214. }
  215. return true
  216. }
  217. // Equal returns true if Message b equals to m.
  218. // Ignores m.Raw.
  219. func (m *Message) Equal(b *Message) bool {
  220. if m == nil && b == nil {
  221. return true
  222. }
  223. if m == nil || b == nil {
  224. return false
  225. }
  226. if m.Type != b.Type {
  227. return false
  228. }
  229. if m.TransactionID != b.TransactionID {
  230. return false
  231. }
  232. if m.Length != b.Length {
  233. return false
  234. }
  235. if !attrEqual(m.Attributes, b.Attributes) {
  236. return false
  237. }
  238. return true
  239. }
  240. // WriteLength writes m.Length to m.Raw.
  241. func (m *Message) WriteLength() {
  242. m.grow(4)
  243. bin.PutUint16(m.Raw[2:4], uint16(m.Length))
  244. }
  245. // WriteHeader writes header to underlying buffer. Not goroutine-safe.
  246. func (m *Message) WriteHeader() {
  247. m.grow(messageHeaderSize)
  248. _ = m.Raw[:messageHeaderSize] // early bounds check to guarantee safety of writes below
  249. m.WriteType()
  250. m.WriteLength()
  251. bin.PutUint32(m.Raw[4:8], magicCookie) // magic cookie
  252. copy(m.Raw[8:messageHeaderSize], m.TransactionID[:]) // transaction ID
  253. }
  254. // WriteTransactionID writes m.TransactionID to m.Raw.
  255. func (m *Message) WriteTransactionID() {
  256. copy(m.Raw[8:messageHeaderSize], m.TransactionID[:]) // transaction ID
  257. }
  258. // WriteAttributes encodes all m.Attributes to m.
  259. func (m *Message) WriteAttributes() {
  260. attributes := m.Attributes
  261. m.Attributes = attributes[:0]
  262. for _, a := range attributes {
  263. m.Add(a.Type, a.Value)
  264. }
  265. m.Attributes = attributes
  266. }
  267. // WriteType writes m.Type to m.Raw.
  268. func (m *Message) WriteType() {
  269. m.grow(2)
  270. bin.PutUint16(m.Raw[0:2], m.Type.Value()) // message type
  271. }
  272. // SetType sets m.Type and writes it to m.Raw.
  273. func (m *Message) SetType(t MessageType) {
  274. m.Type = t
  275. m.WriteType()
  276. }
  277. // Encode re-encodes message into m.Raw.
  278. func (m *Message) Encode() {
  279. m.Raw = m.Raw[:0]
  280. m.WriteHeader()
  281. m.Length = 0
  282. m.WriteAttributes()
  283. }
  284. // WriteTo implements WriterTo via calling Write(m.Raw) on w and returning
  285. // call result.
  286. func (m *Message) WriteTo(w io.Writer) (int64, error) {
  287. n, err := w.Write(m.Raw)
  288. return int64(n), err
  289. }
  290. // ReadFrom implements ReaderFrom. Reads message from r into m.Raw,
  291. // Decodes it and return error if any. If m.Raw is too small, will return
  292. // ErrUnexpectedEOF, ErrUnexpectedHeaderEOF or *DecodeErr.
  293. //
  294. // Can return *DecodeErr while decoding too.
  295. func (m *Message) ReadFrom(r io.Reader) (int64, error) {
  296. tBuf := m.Raw[:cap(m.Raw)]
  297. var (
  298. n int
  299. err error
  300. )
  301. if n, err = r.Read(tBuf); err != nil {
  302. return int64(n), err
  303. }
  304. m.Raw = tBuf[:n]
  305. return int64(n), m.Decode()
  306. }
  307. // ErrUnexpectedHeaderEOF means that there were not enough bytes in
  308. // m.Raw to read header.
  309. var ErrUnexpectedHeaderEOF = errors.New("unexpected EOF: not enough bytes to read header")
  310. // Decode decodes m.Raw into m.
  311. func (m *Message) Decode() error {
  312. // decoding message header
  313. buf := m.Raw
  314. if len(buf) < messageHeaderSize {
  315. return ErrUnexpectedHeaderEOF
  316. }
  317. var (
  318. t = bin.Uint16(buf[0:2]) // first 2 bytes
  319. size = int(bin.Uint16(buf[2:4])) // second 2 bytes
  320. cookie = bin.Uint32(buf[4:8]) // last 4 bytes
  321. fullSize = messageHeaderSize + size // len(m.Raw)
  322. )
  323. if cookie != magicCookie {
  324. msg := fmt.Sprintf("%x is invalid magic cookie (should be %x)", cookie, magicCookie)
  325. return newDecodeErr("message", "cookie", msg)
  326. }
  327. if len(buf) < fullSize {
  328. msg := fmt.Sprintf("buffer length %d is less than %d (expected message size)", len(buf), fullSize)
  329. return newAttrDecodeErr("message", msg)
  330. }
  331. // saving header data
  332. m.Type.ReadValue(t)
  333. m.Length = uint32(size)
  334. copy(m.TransactionID[:], buf[8:messageHeaderSize])
  335. m.Attributes = m.Attributes[:0]
  336. var (
  337. offset = 0
  338. b = buf[messageHeaderSize:fullSize]
  339. )
  340. for offset < size {
  341. // checking that we have enough bytes to read header
  342. if len(b) < attributeHeaderSize {
  343. msg := fmt.Sprintf("buffer length %d is less than %d (expected header size)", len(b), attributeHeaderSize)
  344. return newAttrDecodeErr("header", msg)
  345. }
  346. var (
  347. a = RawAttribute{
  348. Type: compatAttrType(bin.Uint16(b[0:2])), // first 2 bytes
  349. Length: bin.Uint16(b[2:4]), // second 2 bytes
  350. }
  351. aL = int(a.Length) // attribute length
  352. aBuffL = nearestPaddedValueLength(aL) // expected buffer length (with padding)
  353. )
  354. b = b[attributeHeaderSize:] // slicing again to simplify value read
  355. offset += attributeHeaderSize
  356. if len(b) < aBuffL { // checking size
  357. msg := fmt.Sprintf("buffer length %d is less than %d (expected value size for %s)", len(b), aBuffL, a.Type)
  358. return newAttrDecodeErr("value", msg)
  359. }
  360. a.Value = b[:aL]
  361. offset += aBuffL
  362. b = b[aBuffL:]
  363. m.Attributes = append(m.Attributes, a)
  364. }
  365. return nil
  366. }
  367. // Write decodes message and return error if any.
  368. //
  369. // Any error is unrecoverable, but message could be partially decoded.
  370. func (m *Message) Write(tBuf []byte) (int, error) {
  371. m.Raw = append(m.Raw[:0], tBuf...)
  372. return len(tBuf), m.Decode()
  373. }
  374. // CloneTo clones m to b securing any further m mutations.
  375. func (m *Message) CloneTo(b *Message) error {
  376. b.Raw = append(b.Raw[:0], m.Raw...)
  377. return b.Decode()
  378. }
  379. // MessageClass is 8-bit representation of 2-bit class of STUN Message Class.
  380. type MessageClass byte
  381. // Possible values for message class in STUN Message Type.
  382. const (
  383. ClassRequest MessageClass = 0x00 // 0b00
  384. ClassIndication MessageClass = 0x01 // 0b01
  385. ClassSuccessResponse MessageClass = 0x02 // 0b10
  386. ClassErrorResponse MessageClass = 0x03 // 0b11
  387. )
  388. // Common STUN message types.
  389. var (
  390. // Binding request message type.
  391. BindingRequest = NewType(MethodBinding, ClassRequest) // nolint:gochecknoglobals
  392. // Binding success response message type
  393. BindingSuccess = NewType(MethodBinding, ClassSuccessResponse) // nolint:gochecknoglobals
  394. // Binding error response message type.
  395. BindingError = NewType(MethodBinding, ClassErrorResponse) // nolint:gochecknoglobals
  396. )
  397. func (c MessageClass) String() string {
  398. switch c {
  399. case ClassRequest:
  400. return "request"
  401. case ClassIndication:
  402. return "indication"
  403. case ClassSuccessResponse:
  404. return "success response"
  405. case ClassErrorResponse:
  406. return "error response"
  407. default:
  408. panic("unknown message class") // nolint
  409. }
  410. }
  411. // Method is uint16 representation of 12-bit STUN method.
  412. type Method uint16
  413. // Possible methods for STUN Message.
  414. const (
  415. MethodBinding Method = 0x001
  416. MethodAllocate Method = 0x003
  417. MethodRefresh Method = 0x004
  418. MethodSend Method = 0x006
  419. MethodData Method = 0x007
  420. MethodCreatePermission Method = 0x008
  421. MethodChannelBind Method = 0x009
  422. )
  423. // Methods from RFC 6062.
  424. const (
  425. MethodConnect Method = 0x000a
  426. MethodConnectionBind Method = 0x000b
  427. MethodConnectionAttempt Method = 0x000c
  428. )
  429. func methodName() map[Method]string {
  430. return map[Method]string{
  431. MethodBinding: "Binding",
  432. MethodAllocate: "Allocate",
  433. MethodRefresh: "Refresh",
  434. MethodSend: "Send",
  435. MethodData: "Data",
  436. MethodCreatePermission: "CreatePermission",
  437. MethodChannelBind: "ChannelBind",
  438. // RFC 6062.
  439. MethodConnect: "Connect",
  440. MethodConnectionBind: "ConnectionBind",
  441. MethodConnectionAttempt: "ConnectionAttempt",
  442. }
  443. }
  444. func (m Method) String() string {
  445. s, ok := methodName()[m]
  446. if !ok {
  447. // Falling back to hex representation.
  448. s = fmt.Sprintf("0x%x", uint16(m))
  449. }
  450. return s
  451. }
  452. // MessageType is STUN Message Type Field.
  453. type MessageType struct {
  454. Method Method // e.g. binding
  455. Class MessageClass // e.g. request
  456. }
  457. // AddTo sets m type to t.
  458. func (t MessageType) AddTo(m *Message) error {
  459. m.SetType(t)
  460. return nil
  461. }
  462. // NewType returns new message type with provided method and class.
  463. func NewType(method Method, class MessageClass) MessageType {
  464. return MessageType{
  465. Method: method,
  466. Class: class,
  467. }
  468. }
  469. const (
  470. methodABits = 0xf // 0b0000000000001111
  471. methodBBits = 0x70 // 0b0000000001110000
  472. methodDBits = 0xf80 // 0b0000111110000000
  473. methodBShift = 1
  474. methodDShift = 2
  475. firstBit = 0x1
  476. secondBit = 0x2
  477. c0Bit = firstBit
  478. c1Bit = secondBit
  479. classC0Shift = 4
  480. classC1Shift = 7
  481. )
  482. // Value returns bit representation of messageType.
  483. func (t MessageType) Value() uint16 {
  484. // 0 1
  485. // 2 3 4 5 6 7 8 9 0 1 2 3 4 5
  486. // +--+--+-+-+-+-+-+-+-+-+-+-+-+-+
  487. // |M |M |M|M|M|C|M|M|M|C|M|M|M|M|
  488. // |11|10|9|8|7|1|6|5|4|0|3|2|1|0|
  489. // +--+--+-+-+-+-+-+-+-+-+-+-+-+-+
  490. // Figure 3: Format of STUN Message Type Field
  491. // Warning: Abandon all hope ye who enter here.
  492. // Splitting M into A(M0-M3), B(M4-M6), D(M7-M11).
  493. m := uint16(t.Method)
  494. a := m & methodABits // A = M * 0b0000000000001111 (right 4 bits)
  495. b := m & methodBBits // B = M * 0b0000000001110000 (3 bits after A)
  496. d := m & methodDBits // D = M * 0b0000111110000000 (5 bits after B)
  497. // Shifting to add "holes" for C0 (at 4 bit) and C1 (8 bit).
  498. m = a + (b << methodBShift) + (d << methodDShift)
  499. // C0 is zero bit of C, C1 is first bit.
  500. // C0 = C * 0b01, C1 = (C * 0b10) >> 1
  501. // Ct = C0 << 4 + C1 << 8.
  502. // Optimizations: "((C * 0b10) >> 1) << 8" as "(C * 0b10) << 7"
  503. // We need C0 shifted by 4, and C1 by 8 to fit "11" and "7" positions
  504. // (see figure 3).
  505. c := uint16(t.Class)
  506. c0 := (c & c0Bit) << classC0Shift
  507. c1 := (c & c1Bit) << classC1Shift
  508. class := c0 + c1
  509. return m + class
  510. }
  511. // ReadValue decodes uint16 into MessageType.
  512. func (t *MessageType) ReadValue(v uint16) {
  513. // Decoding class.
  514. // We are taking first bit from v >> 4 and second from v >> 7.
  515. c0 := (v >> classC0Shift) & c0Bit
  516. c1 := (v >> classC1Shift) & c1Bit
  517. class := c0 + c1
  518. t.Class = MessageClass(class)
  519. // Decoding method.
  520. a := v & methodABits // A(M0-M3)
  521. b := (v >> methodBShift) & methodBBits // B(M4-M6)
  522. d := (v >> methodDShift) & methodDBits // D(M7-M11)
  523. m := a + b + d
  524. t.Method = Method(m)
  525. }
  526. func (t MessageType) String() string {
  527. return fmt.Sprintf("%s %s", t.Method, t.Class)
  528. }
  529. // Contains return true if message contain t attribute.
  530. func (m *Message) Contains(t AttrType) bool {
  531. for _, a := range m.Attributes {
  532. if a.Type == t {
  533. return true
  534. }
  535. }
  536. return false
  537. }
  538. type transactionIDValueSetter [TransactionIDSize]byte
  539. // NewTransactionIDSetter returns new Setter that sets message transaction id
  540. // to provided value.
  541. func NewTransactionIDSetter(value [TransactionIDSize]byte) Setter {
  542. return transactionIDValueSetter(value)
  543. }
  544. func (t transactionIDValueSetter) AddTo(m *Message) error {
  545. m.TransactionID = t
  546. m.WriteTransactionID()
  547. return nil
  548. }