writer.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. // Copyright 2012 Google, Inc. All rights reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style license
  4. // that can be found in the LICENSE file in the root of the source
  5. // tree.
  6. package gopacket
  7. import (
  8. "fmt"
  9. )
  10. // SerializableLayer allows its implementations to be written out as a set of bytes,
  11. // so those bytes may be sent on the wire or otherwise used by the caller.
  12. // SerializableLayer is implemented by certain Layer types, and can be encoded to
  13. // bytes using the LayerWriter object.
  14. type SerializableLayer interface {
  15. // SerializeTo writes this layer to a slice, growing that slice if necessary
  16. // to make it fit the layer's data.
  17. // Args:
  18. // b: SerializeBuffer to write this layer on to. When called, b.Bytes()
  19. // is the payload this layer should wrap, if any. Note that this
  20. // layer can either prepend itself (common), append itself
  21. // (uncommon), or both (sometimes padding or footers are required at
  22. // the end of packet data). It's also possible (though probably very
  23. // rarely needed) to overwrite any bytes in the current payload.
  24. // After this call, b.Bytes() should return the byte encoding of
  25. // this layer wrapping the original b.Bytes() payload.
  26. // opts: options to use while writing out data.
  27. // Returns:
  28. // error if a problem was encountered during encoding. If an error is
  29. // returned, the bytes in data should be considered invalidated, and
  30. // not used.
  31. //
  32. // SerializeTo calls SHOULD entirely ignore LayerContents and
  33. // LayerPayload. It just serializes based on struct fields, neither
  34. // modifying nor using contents/payload.
  35. SerializeTo(b SerializeBuffer, opts SerializeOptions) error
  36. }
  37. // SerializeOptions provides options for behaviors that SerializableLayers may want to
  38. // implement.
  39. type SerializeOptions struct {
  40. // FixLengths determines whether, during serialization, layers should fix
  41. // the values for any length field that depends on the payload.
  42. FixLengths bool
  43. // ComputeChecksums determines whether, during serialization, layers
  44. // should recompute checksums based on their payloads.
  45. ComputeChecksums bool
  46. }
  47. // SerializeBuffer is a helper used by gopacket for writing out packet layers.
  48. // SerializeBuffer starts off as an empty []byte. Subsequent calls to PrependBytes
  49. // return byte slices before the current Bytes(), AppendBytes returns byte
  50. // slices after.
  51. //
  52. // Byte slices returned by PrependBytes/AppendBytes are NOT zero'd out, so if
  53. // you want to make sure they're all zeros, set them as such.
  54. //
  55. // SerializeBuffer is specifically designed to handle packet writing, where unlike
  56. // with normal writes it's easier to start writing at the inner-most layer and
  57. // work out, meaning that we often need to prepend bytes. This runs counter to
  58. // typical writes to byte slices using append(), where we only write at the end
  59. // of the buffer.
  60. //
  61. // It can be reused via Clear. Note, however, that a Clear call will invalidate the
  62. // byte slices returned by any previous Bytes() call (the same buffer is
  63. // reused).
  64. //
  65. // 1) Reusing a write buffer is generally much faster than creating a new one,
  66. // and with the default implementation it avoids additional memory allocations.
  67. // 2) If a byte slice from a previous Bytes() call will continue to be used,
  68. // it's better to create a new SerializeBuffer.
  69. //
  70. // The Clear method is specifically designed to minimize memory allocations for
  71. // similar later workloads on the SerializeBuffer. IE: if you make a set of
  72. // Prepend/Append calls, then clear, then make the same calls with the same
  73. // sizes, the second round (and all future similar rounds) shouldn't allocate
  74. // any new memory.
  75. type SerializeBuffer interface {
  76. // Bytes returns the contiguous set of bytes collected so far by Prepend/Append
  77. // calls. The slice returned by Bytes will be modified by future Clear calls,
  78. // so if you're planning on clearing this SerializeBuffer, you may want to copy
  79. // Bytes somewhere safe first.
  80. Bytes() []byte
  81. // PrependBytes returns a set of bytes which prepends the current bytes in this
  82. // buffer. These bytes start in an indeterminate state, so they should be
  83. // overwritten by the caller. The caller must only call PrependBytes if they
  84. // know they're going to immediately overwrite all bytes returned.
  85. PrependBytes(num int) ([]byte, error)
  86. // AppendBytes returns a set of bytes which appends the current bytes in this
  87. // buffer. These bytes start in an indeterminate state, so they should be
  88. // overwritten by the caller. The caller must only call AppendBytes if they
  89. // know they're going to immediately overwrite all bytes returned.
  90. AppendBytes(num int) ([]byte, error)
  91. // Clear resets the SerializeBuffer to a new, empty buffer. After a call to clear,
  92. // the byte slice returned by any previous call to Bytes() for this buffer
  93. // should be considered invalidated.
  94. Clear() error
  95. }
  96. type serializeBuffer struct {
  97. data []byte
  98. start int
  99. prepended, appended int
  100. }
  101. // NewSerializeBuffer creates a new instance of the default implementation of
  102. // the SerializeBuffer interface.
  103. func NewSerializeBuffer() SerializeBuffer {
  104. return &serializeBuffer{}
  105. }
  106. // NewSerializeBufferExpectedSize creates a new buffer for serialization, optimized for an
  107. // expected number of bytes prepended/appended. This tends to decrease the
  108. // number of memory allocations made by the buffer during writes.
  109. func NewSerializeBufferExpectedSize(expectedPrependLength, expectedAppendLength int) SerializeBuffer {
  110. return &serializeBuffer{
  111. data: make([]byte, expectedPrependLength, expectedPrependLength+expectedAppendLength),
  112. start: expectedPrependLength,
  113. prepended: expectedPrependLength,
  114. appended: expectedAppendLength,
  115. }
  116. }
  117. func (w *serializeBuffer) Bytes() []byte {
  118. return w.data[w.start:]
  119. }
  120. func (w *serializeBuffer) PrependBytes(num int) ([]byte, error) {
  121. if num < 0 {
  122. panic("num < 0")
  123. }
  124. if w.start < num {
  125. toPrepend := w.prepended
  126. if toPrepend < num {
  127. toPrepend = num
  128. }
  129. w.prepended += toPrepend
  130. length := cap(w.data) + toPrepend
  131. newData := make([]byte, length)
  132. newStart := w.start + toPrepend
  133. copy(newData[newStart:], w.data[w.start:])
  134. w.start = newStart
  135. w.data = newData[:toPrepend+len(w.data)]
  136. }
  137. w.start -= num
  138. return w.data[w.start : w.start+num], nil
  139. }
  140. func (w *serializeBuffer) AppendBytes(num int) ([]byte, error) {
  141. if num < 0 {
  142. panic("num < 0")
  143. }
  144. initialLength := len(w.data)
  145. if cap(w.data)-initialLength < num {
  146. toAppend := w.appended
  147. if toAppend < num {
  148. toAppend = num
  149. }
  150. w.appended += toAppend
  151. newData := make([]byte, cap(w.data)+toAppend)
  152. copy(newData[w.start:], w.data[w.start:])
  153. w.data = newData[:initialLength]
  154. }
  155. // Grow the buffer. We know it'll be under capacity given above.
  156. w.data = w.data[:initialLength+num]
  157. return w.data[initialLength:], nil
  158. }
  159. func (w *serializeBuffer) Clear() error {
  160. w.start = w.prepended
  161. w.data = w.data[:w.start]
  162. return nil
  163. }
  164. // SerializeLayers clears the given write buffer, then writes all layers into it so
  165. // they correctly wrap each other. Note that by clearing the buffer, it
  166. // invalidates all slices previously returned by w.Bytes()
  167. //
  168. // Example:
  169. // buf := gopacket.NewSerializeBuffer()
  170. // opts := gopacket.SerializeOptions{}
  171. // gopacket.SerializeLayers(buf, opts, a, b, c)
  172. // firstPayload := buf.Bytes() // contains byte representation of a(b(c))
  173. // gopacket.SerializeLayers(buf, opts, d, e, f)
  174. // secondPayload := buf.Bytes() // contains byte representation of d(e(f)). firstPayload is now invalidated, since the SerializeLayers call Clears buf.
  175. func SerializeLayers(w SerializeBuffer, opts SerializeOptions, layers ...SerializableLayer) error {
  176. w.Clear()
  177. for i := len(layers) - 1; i >= 0; i-- {
  178. layer := layers[i]
  179. err := layer.SerializeTo(w, opts)
  180. if err != nil {
  181. return err
  182. }
  183. }
  184. return nil
  185. }
  186. // SerializePacket is a convenience function that calls SerializeLayers
  187. // on packet's Layers().
  188. // It returns an error if one of the packet layers is not a SerializebleLayer.
  189. func SerializePacket(buf SerializeBuffer, opts SerializeOptions, packet Packet) error {
  190. sls := []SerializableLayer{}
  191. for _, layer := range packet.Layers() {
  192. sl, ok := layer.(SerializableLayer)
  193. if !ok {
  194. return fmt.Errorf("layer %s is not serializable", layer.LayerType().String())
  195. }
  196. sls = append(sls, sl)
  197. }
  198. return SerializeLayers(buf, opts, sls...)
  199. }