message.go 16 KB

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