parser.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. // A container for single LayerType->DecodingLayer mapping.
  11. type decodingLayerElem struct {
  12. typ LayerType
  13. dec DecodingLayer
  14. }
  15. // DecodingLayer is an interface for packet layers that can decode themselves.
  16. //
  17. // The important part of DecodingLayer is that they decode themselves in-place.
  18. // Calling DecodeFromBytes on a DecodingLayer totally resets the entire layer to
  19. // the new state defined by the data passed in. A returned error leaves the
  20. // DecodingLayer in an unknown intermediate state, thus its fields should not be
  21. // trusted.
  22. //
  23. // Because the DecodingLayer is resetting its own fields, a call to
  24. // DecodeFromBytes should normally not require any memory allocation.
  25. type DecodingLayer interface {
  26. // DecodeFromBytes resets the internal state of this layer to the state
  27. // defined by the passed-in bytes. Slices in the DecodingLayer may
  28. // reference the passed-in data, so care should be taken to copy it
  29. // first should later modification of data be required before the
  30. // DecodingLayer is discarded.
  31. DecodeFromBytes(data []byte, df DecodeFeedback) error
  32. // CanDecode returns the set of LayerTypes this DecodingLayer can
  33. // decode. For Layers that are also DecodingLayers, this will most
  34. // often be that Layer's LayerType().
  35. CanDecode() LayerClass
  36. // NextLayerType returns the LayerType which should be used to decode
  37. // the LayerPayload.
  38. NextLayerType() LayerType
  39. // LayerPayload is the set of bytes remaining to decode after a call to
  40. // DecodeFromBytes.
  41. LayerPayload() []byte
  42. }
  43. // DecodingLayerFunc decodes given packet and stores decoded LayerType
  44. // values into specified slice. Returns either first encountered
  45. // unsupported LayerType value or decoding error. In case of success,
  46. // returns (LayerTypeZero, nil).
  47. type DecodingLayerFunc func([]byte, *[]LayerType) (LayerType, error)
  48. // DecodingLayerContainer stores all DecodingLayer-s and serves as a
  49. // searching tool for DecodingLayerParser.
  50. type DecodingLayerContainer interface {
  51. // Put adds new DecodingLayer to container. The new instance of
  52. // the same DecodingLayerContainer is returned so it may be
  53. // implemented as a value receiver.
  54. Put(DecodingLayer) DecodingLayerContainer
  55. // Decoder returns DecodingLayer to decode given LayerType and
  56. // true if it was found. If no decoder found, return false.
  57. Decoder(LayerType) (DecodingLayer, bool)
  58. // LayersDecoder returns DecodingLayerFunc which decodes given
  59. // packet, starting with specified LayerType and DecodeFeedback.
  60. LayersDecoder(first LayerType, df DecodeFeedback) DecodingLayerFunc
  61. }
  62. // DecodingLayerSparse is a sparse array-based implementation of
  63. // DecodingLayerContainer. Each DecodingLayer is addressed in an
  64. // allocated slice by LayerType value itself. Though this is the
  65. // fastest container it may be memory-consuming if used with big
  66. // LayerType values.
  67. type DecodingLayerSparse []DecodingLayer
  68. // Put implements DecodingLayerContainer interface.
  69. func (dl DecodingLayerSparse) Put(d DecodingLayer) DecodingLayerContainer {
  70. maxLayerType := LayerType(len(dl) - 1)
  71. for _, typ := range d.CanDecode().LayerTypes() {
  72. if typ > maxLayerType {
  73. maxLayerType = typ
  74. }
  75. }
  76. if extra := maxLayerType - LayerType(len(dl)) + 1; extra > 0 {
  77. dl = append(dl, make([]DecodingLayer, extra)...)
  78. }
  79. for _, typ := range d.CanDecode().LayerTypes() {
  80. dl[typ] = d
  81. }
  82. return dl
  83. }
  84. // LayersDecoder implements DecodingLayerContainer interface.
  85. func (dl DecodingLayerSparse) LayersDecoder(first LayerType, df DecodeFeedback) DecodingLayerFunc {
  86. return LayersDecoder(dl, first, df)
  87. }
  88. // Decoder implements DecodingLayerContainer interface.
  89. func (dl DecodingLayerSparse) Decoder(typ LayerType) (DecodingLayer, bool) {
  90. if int64(typ) < int64(len(dl)) {
  91. decoder := dl[typ]
  92. return decoder, decoder != nil
  93. }
  94. return nil, false
  95. }
  96. // DecodingLayerArray is an array-based implementation of
  97. // DecodingLayerContainer. Each DecodingLayer is searched linearly in
  98. // an allocated slice in one-by-one fashion.
  99. type DecodingLayerArray []decodingLayerElem
  100. // Put implements DecodingLayerContainer interface.
  101. func (dl DecodingLayerArray) Put(d DecodingLayer) DecodingLayerContainer {
  102. TYPES:
  103. for _, typ := range d.CanDecode().LayerTypes() {
  104. for i := range dl {
  105. if dl[i].typ == typ {
  106. dl[i].dec = d
  107. continue TYPES
  108. }
  109. }
  110. dl = append(dl, decodingLayerElem{typ, d})
  111. }
  112. return dl
  113. }
  114. // Decoder implements DecodingLayerContainer interface.
  115. func (dl DecodingLayerArray) Decoder(typ LayerType) (DecodingLayer, bool) {
  116. for i := range dl {
  117. if dl[i].typ == typ {
  118. return dl[i].dec, true
  119. }
  120. }
  121. return nil, false
  122. }
  123. // LayersDecoder implements DecodingLayerContainer interface.
  124. func (dl DecodingLayerArray) LayersDecoder(first LayerType, df DecodeFeedback) DecodingLayerFunc {
  125. return LayersDecoder(dl, first, df)
  126. }
  127. // DecodingLayerMap is an map-based implementation of
  128. // DecodingLayerContainer. Each DecodingLayer is searched in a map
  129. // hashed by LayerType value.
  130. type DecodingLayerMap map[LayerType]DecodingLayer
  131. // Put implements DecodingLayerContainer interface.
  132. func (dl DecodingLayerMap) Put(d DecodingLayer) DecodingLayerContainer {
  133. for _, typ := range d.CanDecode().LayerTypes() {
  134. if dl == nil {
  135. dl = make(map[LayerType]DecodingLayer)
  136. }
  137. dl[typ] = d
  138. }
  139. return dl
  140. }
  141. // Decoder implements DecodingLayerContainer interface.
  142. func (dl DecodingLayerMap) Decoder(typ LayerType) (DecodingLayer, bool) {
  143. d, ok := dl[typ]
  144. return d, ok
  145. }
  146. // LayersDecoder implements DecodingLayerContainer interface.
  147. func (dl DecodingLayerMap) LayersDecoder(first LayerType, df DecodeFeedback) DecodingLayerFunc {
  148. return LayersDecoder(dl, first, df)
  149. }
  150. // Static code check.
  151. var (
  152. _ = []DecodingLayerContainer{
  153. DecodingLayerSparse(nil),
  154. DecodingLayerMap(nil),
  155. DecodingLayerArray(nil),
  156. }
  157. )
  158. // DecodingLayerParser parses a given set of layer types. See DecodeLayers for
  159. // more information on how DecodingLayerParser should be used.
  160. type DecodingLayerParser struct {
  161. // DecodingLayerParserOptions is the set of options available to the
  162. // user to define the parser's behavior.
  163. DecodingLayerParserOptions
  164. dlc DecodingLayerContainer
  165. first LayerType
  166. df DecodeFeedback
  167. decodeFunc DecodingLayerFunc
  168. // Truncated is set when a decode layer detects that the packet has been
  169. // truncated.
  170. Truncated bool
  171. }
  172. // AddDecodingLayer adds a decoding layer to the parser. This adds support for
  173. // the decoding layer's CanDecode layers to the parser... should they be
  174. // encountered, they'll be parsed.
  175. func (l *DecodingLayerParser) AddDecodingLayer(d DecodingLayer) {
  176. l.SetDecodingLayerContainer(l.dlc.Put(d))
  177. }
  178. // SetTruncated is used by DecodingLayers to set the Truncated boolean in the
  179. // DecodingLayerParser. Users should simply read Truncated after calling
  180. // DecodeLayers.
  181. func (l *DecodingLayerParser) SetTruncated() {
  182. l.Truncated = true
  183. }
  184. // NewDecodingLayerParser creates a new DecodingLayerParser and adds in all
  185. // of the given DecodingLayers with AddDecodingLayer.
  186. //
  187. // Each call to DecodeLayers will attempt to decode the given bytes first by
  188. // treating them as a 'first'-type layer, then by using NextLayerType on
  189. // subsequently decoded layers to find the next relevant decoder. Should a
  190. // deoder not be available for the layer type returned by NextLayerType,
  191. // decoding will stop.
  192. //
  193. // NewDecodingLayerParser uses DecodingLayerMap container by
  194. // default.
  195. func NewDecodingLayerParser(first LayerType, decoders ...DecodingLayer) *DecodingLayerParser {
  196. dlp := &DecodingLayerParser{first: first}
  197. dlp.df = dlp // Cast this once to the interface
  198. // default container
  199. dlc := DecodingLayerContainer(DecodingLayerMap(make(map[LayerType]DecodingLayer)))
  200. for _, d := range decoders {
  201. dlc = dlc.Put(d)
  202. }
  203. dlp.SetDecodingLayerContainer(dlc)
  204. return dlp
  205. }
  206. // SetDecodingLayerContainer specifies container with decoders. This
  207. // call replaces all decoders already registered in given instance of
  208. // DecodingLayerParser.
  209. func (l *DecodingLayerParser) SetDecodingLayerContainer(dlc DecodingLayerContainer) {
  210. l.dlc = dlc
  211. l.decodeFunc = l.dlc.LayersDecoder(l.first, l.df)
  212. }
  213. // DecodeLayers decodes as many layers as possible from the given data. It
  214. // initially treats the data as layer type 'typ', then uses NextLayerType on
  215. // each subsequent decoded layer until it gets to a layer type it doesn't know
  216. // how to parse.
  217. //
  218. // For each layer successfully decoded, DecodeLayers appends the layer type to
  219. // the decoded slice. DecodeLayers truncates the 'decoded' slice initially, so
  220. // there's no need to empty it yourself.
  221. //
  222. // This decoding method is about an order of magnitude faster than packet
  223. // decoding, because it only decodes known layers that have already been
  224. // allocated. This means it doesn't need to allocate each layer it returns...
  225. // instead it overwrites the layers that already exist.
  226. //
  227. // Example usage:
  228. // func main() {
  229. // var eth layers.Ethernet
  230. // var ip4 layers.IPv4
  231. // var ip6 layers.IPv6
  232. // var tcp layers.TCP
  233. // var udp layers.UDP
  234. // var payload gopacket.Payload
  235. // parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, &eth, &ip4, &ip6, &tcp, &udp, &payload)
  236. // var source gopacket.PacketDataSource = getMyDataSource()
  237. // decodedLayers := make([]gopacket.LayerType, 0, 10)
  238. // for {
  239. // data, _, err := source.ReadPacketData()
  240. // if err != nil {
  241. // fmt.Println("Error reading packet data: ", err)
  242. // continue
  243. // }
  244. // fmt.Println("Decoding packet")
  245. // err = parser.DecodeLayers(data, &decodedLayers)
  246. // for _, typ := range decodedLayers {
  247. // fmt.Println(" Successfully decoded layer type", typ)
  248. // switch typ {
  249. // case layers.LayerTypeEthernet:
  250. // fmt.Println(" Eth ", eth.SrcMAC, eth.DstMAC)
  251. // case layers.LayerTypeIPv4:
  252. // fmt.Println(" IP4 ", ip4.SrcIP, ip4.DstIP)
  253. // case layers.LayerTypeIPv6:
  254. // fmt.Println(" IP6 ", ip6.SrcIP, ip6.DstIP)
  255. // case layers.LayerTypeTCP:
  256. // fmt.Println(" TCP ", tcp.SrcPort, tcp.DstPort)
  257. // case layers.LayerTypeUDP:
  258. // fmt.Println(" UDP ", udp.SrcPort, udp.DstPort)
  259. // }
  260. // }
  261. // if decodedLayers.Truncated {
  262. // fmt.Println(" Packet has been truncated")
  263. // }
  264. // if err != nil {
  265. // fmt.Println(" Error encountered:", err)
  266. // }
  267. // }
  268. // }
  269. //
  270. // If DecodeLayers is unable to decode the next layer type, it will return the
  271. // error UnsupportedLayerType.
  272. func (l *DecodingLayerParser) DecodeLayers(data []byte, decoded *[]LayerType) (err error) {
  273. l.Truncated = false
  274. if !l.IgnorePanic {
  275. defer panicToError(&err)
  276. }
  277. typ, err := l.decodeFunc(data, decoded)
  278. if typ != LayerTypeZero {
  279. // no decoder
  280. if l.IgnoreUnsupported {
  281. return nil
  282. }
  283. return UnsupportedLayerType(typ)
  284. }
  285. return err
  286. }
  287. // UnsupportedLayerType is returned by DecodingLayerParser if DecodeLayers
  288. // encounters a layer type that the DecodingLayerParser has no decoder for.
  289. type UnsupportedLayerType LayerType
  290. // Error implements the error interface, returning a string to say that the
  291. // given layer type is unsupported.
  292. func (e UnsupportedLayerType) Error() string {
  293. return fmt.Sprintf("No decoder for layer type %v", LayerType(e))
  294. }
  295. func panicToError(e *error) {
  296. if r := recover(); r != nil {
  297. *e = fmt.Errorf("panic: %v", r)
  298. }
  299. }
  300. // DecodingLayerParserOptions provides options to affect the behavior of a given
  301. // DecodingLayerParser.
  302. type DecodingLayerParserOptions struct {
  303. // IgnorePanic determines whether a DecodingLayerParser should stop
  304. // panics on its own (by returning them as an error from DecodeLayers)
  305. // or should allow them to raise up the stack. Handling errors does add
  306. // latency to the process of decoding layers, but is much safer for
  307. // callers. IgnorePanic defaults to false, thus if the caller does
  308. // nothing decode panics will be returned as errors.
  309. IgnorePanic bool
  310. // IgnoreUnsupported will stop parsing and return a nil error when it
  311. // encounters a layer it doesn't have a parser for, instead of returning an
  312. // UnsupportedLayerType error. If this is true, it's up to the caller to make
  313. // sure that all expected layers have been parsed (by checking the decoded
  314. // slice).
  315. IgnoreUnsupported bool
  316. }