packet.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  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. "bytes"
  9. "encoding/hex"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "os"
  14. "reflect"
  15. "runtime/debug"
  16. "strings"
  17. "time"
  18. )
  19. // CaptureInfo provides standardized information about a packet captured off
  20. // the wire or read from a file.
  21. type CaptureInfo struct {
  22. // Timestamp is the time the packet was captured, if that is known.
  23. Timestamp time.Time
  24. // CaptureLength is the total number of bytes read off of the wire.
  25. CaptureLength int
  26. // Length is the size of the original packet. Should always be >=
  27. // CaptureLength.
  28. Length int
  29. // InterfaceIndex
  30. InterfaceIndex int
  31. }
  32. // PacketMetadata contains metadata for a packet.
  33. type PacketMetadata struct {
  34. CaptureInfo
  35. // Truncated is true if packet decoding logic detects that there are fewer
  36. // bytes in the packet than are detailed in various headers (for example, if
  37. // the number of bytes in the IPv4 contents/payload is less than IPv4.Length).
  38. // This is also set automatically for packets captured off the wire if
  39. // CaptureInfo.CaptureLength < CaptureInfo.Length.
  40. Truncated bool
  41. }
  42. // Packet is the primary object used by gopacket. Packets are created by a
  43. // Decoder's Decode call. A packet is made up of a set of Data, which
  44. // is broken into a number of Layers as it is decoded.
  45. type Packet interface {
  46. //// Functions for outputting the packet as a human-readable string:
  47. //// ------------------------------------------------------------------
  48. // String returns a human-readable string representation of the packet.
  49. // It uses LayerString on each layer to output the layer.
  50. String() string
  51. // Dump returns a verbose human-readable string representation of the packet,
  52. // including a hex dump of all layers. It uses LayerDump on each layer to
  53. // output the layer.
  54. Dump() string
  55. //// Functions for accessing arbitrary packet layers:
  56. //// ------------------------------------------------------------------
  57. // Layers returns all layers in this packet, computing them as necessary
  58. Layers() []Layer
  59. // Layer returns the first layer in this packet of the given type, or nil
  60. Layer(LayerType) Layer
  61. // LayerClass returns the first layer in this packet of the given class,
  62. // or nil.
  63. LayerClass(LayerClass) Layer
  64. //// Functions for accessing specific types of packet layers. These functions
  65. //// return the first layer of each type found within the packet.
  66. //// ------------------------------------------------------------------
  67. // LinkLayer returns the first link layer in the packet
  68. LinkLayer() LinkLayer
  69. // NetworkLayer returns the first network layer in the packet
  70. NetworkLayer() NetworkLayer
  71. // TransportLayer returns the first transport layer in the packet
  72. TransportLayer() TransportLayer
  73. // ApplicationLayer returns the first application layer in the packet
  74. ApplicationLayer() ApplicationLayer
  75. // ErrorLayer is particularly useful, since it returns nil if the packet
  76. // was fully decoded successfully, and non-nil if an error was encountered
  77. // in decoding and the packet was only partially decoded. Thus, its output
  78. // can be used to determine if the entire packet was able to be decoded.
  79. ErrorLayer() ErrorLayer
  80. //// Functions for accessing data specific to the packet:
  81. //// ------------------------------------------------------------------
  82. // Data returns the set of bytes that make up this entire packet.
  83. Data() []byte
  84. // Metadata returns packet metadata associated with this packet.
  85. Metadata() *PacketMetadata
  86. }
  87. // packet contains all the information we need to fulfill the Packet interface,
  88. // and its two "subclasses" (yes, no such thing in Go, bear with me),
  89. // eagerPacket and lazyPacket, provide eager and lazy decoding logic around the
  90. // various functions needed to access this information.
  91. type packet struct {
  92. // data contains the entire packet data for a packet
  93. data []byte
  94. // initialLayers is space for an initial set of layers already created inside
  95. // the packet.
  96. initialLayers [6]Layer
  97. // layers contains each layer we've already decoded
  98. layers []Layer
  99. // last is the last layer added to the packet
  100. last Layer
  101. // metadata is the PacketMetadata for this packet
  102. metadata PacketMetadata
  103. decodeOptions DecodeOptions
  104. // Pointers to the various important layers
  105. link LinkLayer
  106. network NetworkLayer
  107. transport TransportLayer
  108. application ApplicationLayer
  109. failure ErrorLayer
  110. }
  111. func (p *packet) SetTruncated() {
  112. p.metadata.Truncated = true
  113. }
  114. func (p *packet) SetLinkLayer(l LinkLayer) {
  115. if p.link == nil {
  116. p.link = l
  117. }
  118. }
  119. func (p *packet) SetNetworkLayer(l NetworkLayer) {
  120. if p.network == nil {
  121. p.network = l
  122. }
  123. }
  124. func (p *packet) SetTransportLayer(l TransportLayer) {
  125. if p.transport == nil {
  126. p.transport = l
  127. }
  128. }
  129. func (p *packet) SetApplicationLayer(l ApplicationLayer) {
  130. if p.application == nil {
  131. p.application = l
  132. }
  133. }
  134. func (p *packet) SetErrorLayer(l ErrorLayer) {
  135. if p.failure == nil {
  136. p.failure = l
  137. }
  138. }
  139. func (p *packet) AddLayer(l Layer) {
  140. p.layers = append(p.layers, l)
  141. p.last = l
  142. }
  143. func (p *packet) DumpPacketData() {
  144. fmt.Fprint(os.Stderr, p.packetDump())
  145. os.Stderr.Sync()
  146. }
  147. func (p *packet) Metadata() *PacketMetadata {
  148. return &p.metadata
  149. }
  150. func (p *packet) Data() []byte {
  151. return p.data
  152. }
  153. func (p *packet) DecodeOptions() *DecodeOptions {
  154. return &p.decodeOptions
  155. }
  156. func (p *packet) addFinalDecodeError(err error, stack []byte) {
  157. fail := &DecodeFailure{err: err, stack: stack}
  158. if p.last == nil {
  159. fail.data = p.data
  160. } else {
  161. fail.data = p.last.LayerPayload()
  162. }
  163. p.AddLayer(fail)
  164. p.SetErrorLayer(fail)
  165. }
  166. func (p *packet) recoverDecodeError() {
  167. if !p.decodeOptions.SkipDecodeRecovery {
  168. if r := recover(); r != nil {
  169. p.addFinalDecodeError(fmt.Errorf("%v", r), debug.Stack())
  170. }
  171. }
  172. }
  173. // LayerString outputs an individual layer as a string. The layer is output
  174. // in a single line, with no trailing newline. This function is specifically
  175. // designed to do the right thing for most layers... it follows the following
  176. // rules:
  177. // * If the Layer has a String function, just output that.
  178. // * Otherwise, output all exported fields in the layer, recursing into
  179. // exported slices and structs.
  180. // NOTE: This is NOT THE SAME AS fmt's "%#v". %#v will output both exported
  181. // and unexported fields... many times packet layers contain unexported stuff
  182. // that would just mess up the output of the layer, see for example the
  183. // Payload layer and it's internal 'data' field, which contains a large byte
  184. // array that would really mess up formatting.
  185. func LayerString(l Layer) string {
  186. return fmt.Sprintf("%v\t%s", l.LayerType(), layerString(reflect.ValueOf(l), false, false))
  187. }
  188. // Dumper dumps verbose information on a value. If a layer type implements
  189. // Dumper, then its LayerDump() string will include the results in its output.
  190. type Dumper interface {
  191. Dump() string
  192. }
  193. // LayerDump outputs a very verbose string representation of a layer. Its
  194. // output is a concatenation of LayerString(l) and hex.Dump(l.LayerContents()).
  195. // It contains newlines and ends with a newline.
  196. func LayerDump(l Layer) string {
  197. var b bytes.Buffer
  198. b.WriteString(LayerString(l))
  199. b.WriteByte('\n')
  200. if d, ok := l.(Dumper); ok {
  201. dump := d.Dump()
  202. if dump != "" {
  203. b.WriteString(dump)
  204. if dump[len(dump)-1] != '\n' {
  205. b.WriteByte('\n')
  206. }
  207. }
  208. }
  209. b.WriteString(hex.Dump(l.LayerContents()))
  210. return b.String()
  211. }
  212. // layerString outputs, recursively, a layer in a "smart" way. See docs for
  213. // LayerString for more details.
  214. //
  215. // Params:
  216. // i - value to write out
  217. // anonymous: if we're currently recursing an anonymous member of a struct
  218. // writeSpace: if we've already written a value in a struct, and need to
  219. // write a space before writing more. This happens when we write various
  220. // anonymous values, and need to keep writing more.
  221. func layerString(v reflect.Value, anonymous bool, writeSpace bool) string {
  222. // Let String() functions take precedence.
  223. if v.CanInterface() {
  224. if s, ok := v.Interface().(fmt.Stringer); ok {
  225. return s.String()
  226. }
  227. }
  228. // Reflect, and spit out all the exported fields as key=value.
  229. switch v.Type().Kind() {
  230. case reflect.Interface, reflect.Ptr:
  231. if v.IsNil() {
  232. return "nil"
  233. }
  234. r := v.Elem()
  235. return layerString(r, anonymous, writeSpace)
  236. case reflect.Struct:
  237. var b bytes.Buffer
  238. typ := v.Type()
  239. if !anonymous {
  240. b.WriteByte('{')
  241. }
  242. for i := 0; i < v.NumField(); i++ {
  243. // Check if this is upper-case.
  244. ftype := typ.Field(i)
  245. f := v.Field(i)
  246. if ftype.Anonymous {
  247. anonStr := layerString(f, true, writeSpace)
  248. writeSpace = writeSpace || anonStr != ""
  249. b.WriteString(anonStr)
  250. } else if ftype.PkgPath == "" { // exported
  251. if writeSpace {
  252. b.WriteByte(' ')
  253. }
  254. writeSpace = true
  255. fmt.Fprintf(&b, "%s=%s", typ.Field(i).Name, layerString(f, false, writeSpace))
  256. }
  257. }
  258. if !anonymous {
  259. b.WriteByte('}')
  260. }
  261. return b.String()
  262. case reflect.Slice:
  263. var b bytes.Buffer
  264. b.WriteByte('[')
  265. if v.Len() > 4 {
  266. fmt.Fprintf(&b, "..%d..", v.Len())
  267. } else {
  268. for j := 0; j < v.Len(); j++ {
  269. if j != 0 {
  270. b.WriteString(", ")
  271. }
  272. b.WriteString(layerString(v.Index(j), false, false))
  273. }
  274. }
  275. b.WriteByte(']')
  276. return b.String()
  277. }
  278. return fmt.Sprintf("%v", v.Interface())
  279. }
  280. const (
  281. longBytesLength = 128
  282. )
  283. // LongBytesGoString returns a string representation of the byte slice shortened
  284. // using the format '<type>{<truncated slice> ... (<n> bytes)}' if it
  285. // exceeds a predetermined length. Can be used to avoid filling the display with
  286. // very long byte strings.
  287. func LongBytesGoString(buf []byte) string {
  288. if len(buf) < longBytesLength {
  289. return fmt.Sprintf("%#v", buf)
  290. }
  291. s := fmt.Sprintf("%#v", buf[:longBytesLength-1])
  292. s = strings.TrimSuffix(s, "}")
  293. return fmt.Sprintf("%s ... (%d bytes)}", s, len(buf))
  294. }
  295. func baseLayerString(value reflect.Value) string {
  296. t := value.Type()
  297. content := value.Field(0)
  298. c := make([]byte, content.Len())
  299. for i := range c {
  300. c[i] = byte(content.Index(i).Uint())
  301. }
  302. payload := value.Field(1)
  303. p := make([]byte, payload.Len())
  304. for i := range p {
  305. p[i] = byte(payload.Index(i).Uint())
  306. }
  307. return fmt.Sprintf("%s{Contents:%s, Payload:%s}", t.String(),
  308. LongBytesGoString(c),
  309. LongBytesGoString(p))
  310. }
  311. func layerGoString(i interface{}, b *bytes.Buffer) {
  312. if s, ok := i.(fmt.GoStringer); ok {
  313. b.WriteString(s.GoString())
  314. return
  315. }
  316. var v reflect.Value
  317. var ok bool
  318. if v, ok = i.(reflect.Value); !ok {
  319. v = reflect.ValueOf(i)
  320. }
  321. switch v.Kind() {
  322. case reflect.Ptr, reflect.Interface:
  323. if v.Kind() == reflect.Ptr {
  324. b.WriteByte('&')
  325. }
  326. layerGoString(v.Elem().Interface(), b)
  327. case reflect.Struct:
  328. t := v.Type()
  329. b.WriteString(t.String())
  330. b.WriteByte('{')
  331. for i := 0; i < v.NumField(); i++ {
  332. if i > 0 {
  333. b.WriteString(", ")
  334. }
  335. if t.Field(i).Name == "BaseLayer" {
  336. fmt.Fprintf(b, "BaseLayer:%s", baseLayerString(v.Field(i)))
  337. } else if v.Field(i).Kind() == reflect.Struct {
  338. fmt.Fprintf(b, "%s:", t.Field(i).Name)
  339. layerGoString(v.Field(i), b)
  340. } else if v.Field(i).Kind() == reflect.Ptr {
  341. b.WriteByte('&')
  342. layerGoString(v.Field(i), b)
  343. } else {
  344. fmt.Fprintf(b, "%s:%#v", t.Field(i).Name, v.Field(i))
  345. }
  346. }
  347. b.WriteByte('}')
  348. default:
  349. fmt.Fprintf(b, "%#v", i)
  350. }
  351. }
  352. // LayerGoString returns a representation of the layer in Go syntax,
  353. // taking care to shorten "very long" BaseLayer byte slices
  354. func LayerGoString(l Layer) string {
  355. b := new(bytes.Buffer)
  356. layerGoString(l, b)
  357. return b.String()
  358. }
  359. func (p *packet) packetString() string {
  360. var b bytes.Buffer
  361. fmt.Fprintf(&b, "PACKET: %d bytes", len(p.Data()))
  362. if p.metadata.Truncated {
  363. b.WriteString(", truncated")
  364. }
  365. if p.metadata.Length > 0 {
  366. fmt.Fprintf(&b, ", wire length %d cap length %d", p.metadata.Length, p.metadata.CaptureLength)
  367. }
  368. if !p.metadata.Timestamp.IsZero() {
  369. fmt.Fprintf(&b, " @ %v", p.metadata.Timestamp)
  370. }
  371. b.WriteByte('\n')
  372. for i, l := range p.layers {
  373. fmt.Fprintf(&b, "- Layer %d (%02d bytes) = %s\n", i+1, len(l.LayerContents()), LayerString(l))
  374. }
  375. return b.String()
  376. }
  377. func (p *packet) packetDump() string {
  378. var b bytes.Buffer
  379. fmt.Fprintf(&b, "-- FULL PACKET DATA (%d bytes) ------------------------------------\n%s", len(p.data), hex.Dump(p.data))
  380. for i, l := range p.layers {
  381. fmt.Fprintf(&b, "--- Layer %d ---\n%s", i+1, LayerDump(l))
  382. }
  383. return b.String()
  384. }
  385. // eagerPacket is a packet implementation that does eager decoding. Upon
  386. // initial construction, it decodes all the layers it can from packet data.
  387. // eagerPacket implements Packet and PacketBuilder.
  388. type eagerPacket struct {
  389. packet
  390. }
  391. var errNilDecoder = errors.New("NextDecoder passed nil decoder, probably an unsupported decode type")
  392. func (p *eagerPacket) NextDecoder(next Decoder) error {
  393. if next == nil {
  394. return errNilDecoder
  395. }
  396. if p.last == nil {
  397. return errors.New("NextDecoder called, but no layers added yet")
  398. }
  399. d := p.last.LayerPayload()
  400. if len(d) == 0 {
  401. return nil
  402. }
  403. // Since we're eager, immediately call the next decoder.
  404. return next.Decode(d, p)
  405. }
  406. func (p *eagerPacket) initialDecode(dec Decoder) {
  407. defer p.recoverDecodeError()
  408. err := dec.Decode(p.data, p)
  409. if err != nil {
  410. p.addFinalDecodeError(err, nil)
  411. }
  412. }
  413. func (p *eagerPacket) LinkLayer() LinkLayer {
  414. return p.link
  415. }
  416. func (p *eagerPacket) NetworkLayer() NetworkLayer {
  417. return p.network
  418. }
  419. func (p *eagerPacket) TransportLayer() TransportLayer {
  420. return p.transport
  421. }
  422. func (p *eagerPacket) ApplicationLayer() ApplicationLayer {
  423. return p.application
  424. }
  425. func (p *eagerPacket) ErrorLayer() ErrorLayer {
  426. return p.failure
  427. }
  428. func (p *eagerPacket) Layers() []Layer {
  429. return p.layers
  430. }
  431. func (p *eagerPacket) Layer(t LayerType) Layer {
  432. for _, l := range p.layers {
  433. if l.LayerType() == t {
  434. return l
  435. }
  436. }
  437. return nil
  438. }
  439. func (p *eagerPacket) LayerClass(lc LayerClass) Layer {
  440. for _, l := range p.layers {
  441. if lc.Contains(l.LayerType()) {
  442. return l
  443. }
  444. }
  445. return nil
  446. }
  447. func (p *eagerPacket) String() string { return p.packetString() }
  448. func (p *eagerPacket) Dump() string { return p.packetDump() }
  449. // lazyPacket does lazy decoding on its packet data. On construction it does
  450. // no initial decoding. For each function call, it decodes only as many layers
  451. // as are necessary to compute the return value for that function.
  452. // lazyPacket implements Packet and PacketBuilder.
  453. type lazyPacket struct {
  454. packet
  455. next Decoder
  456. }
  457. func (p *lazyPacket) NextDecoder(next Decoder) error {
  458. if next == nil {
  459. return errNilDecoder
  460. }
  461. p.next = next
  462. return nil
  463. }
  464. func (p *lazyPacket) decodeNextLayer() {
  465. if p.next == nil {
  466. return
  467. }
  468. d := p.data
  469. if p.last != nil {
  470. d = p.last.LayerPayload()
  471. }
  472. next := p.next
  473. p.next = nil
  474. // We've just set p.next to nil, so if we see we have no data, this should be
  475. // the final call we get to decodeNextLayer if we return here.
  476. if len(d) == 0 {
  477. return
  478. }
  479. defer p.recoverDecodeError()
  480. err := next.Decode(d, p)
  481. if err != nil {
  482. p.addFinalDecodeError(err, nil)
  483. }
  484. }
  485. func (p *lazyPacket) LinkLayer() LinkLayer {
  486. for p.link == nil && p.next != nil {
  487. p.decodeNextLayer()
  488. }
  489. return p.link
  490. }
  491. func (p *lazyPacket) NetworkLayer() NetworkLayer {
  492. for p.network == nil && p.next != nil {
  493. p.decodeNextLayer()
  494. }
  495. return p.network
  496. }
  497. func (p *lazyPacket) TransportLayer() TransportLayer {
  498. for p.transport == nil && p.next != nil {
  499. p.decodeNextLayer()
  500. }
  501. return p.transport
  502. }
  503. func (p *lazyPacket) ApplicationLayer() ApplicationLayer {
  504. for p.application == nil && p.next != nil {
  505. p.decodeNextLayer()
  506. }
  507. return p.application
  508. }
  509. func (p *lazyPacket) ErrorLayer() ErrorLayer {
  510. for p.failure == nil && p.next != nil {
  511. p.decodeNextLayer()
  512. }
  513. return p.failure
  514. }
  515. func (p *lazyPacket) Layers() []Layer {
  516. for p.next != nil {
  517. p.decodeNextLayer()
  518. }
  519. return p.layers
  520. }
  521. func (p *lazyPacket) Layer(t LayerType) Layer {
  522. for _, l := range p.layers {
  523. if l.LayerType() == t {
  524. return l
  525. }
  526. }
  527. numLayers := len(p.layers)
  528. for p.next != nil {
  529. p.decodeNextLayer()
  530. for _, l := range p.layers[numLayers:] {
  531. if l.LayerType() == t {
  532. return l
  533. }
  534. }
  535. numLayers = len(p.layers)
  536. }
  537. return nil
  538. }
  539. func (p *lazyPacket) LayerClass(lc LayerClass) Layer {
  540. for _, l := range p.layers {
  541. if lc.Contains(l.LayerType()) {
  542. return l
  543. }
  544. }
  545. numLayers := len(p.layers)
  546. for p.next != nil {
  547. p.decodeNextLayer()
  548. for _, l := range p.layers[numLayers:] {
  549. if lc.Contains(l.LayerType()) {
  550. return l
  551. }
  552. }
  553. numLayers = len(p.layers)
  554. }
  555. return nil
  556. }
  557. func (p *lazyPacket) String() string { p.Layers(); return p.packetString() }
  558. func (p *lazyPacket) Dump() string { p.Layers(); return p.packetDump() }
  559. // DecodeOptions tells gopacket how to decode a packet.
  560. type DecodeOptions struct {
  561. // Lazy decoding decodes the minimum number of layers needed to return data
  562. // for a packet at each function call. Be careful using this with concurrent
  563. // packet processors, as each call to packet.* could mutate the packet, and
  564. // two concurrent function calls could interact poorly.
  565. Lazy bool
  566. // NoCopy decoding doesn't copy its input buffer into storage that's owned by
  567. // the packet. If you can guarantee that the bytes underlying the slice
  568. // passed into NewPacket aren't going to be modified, this can be faster. If
  569. // there's any chance that those bytes WILL be changed, this will invalidate
  570. // your packets.
  571. NoCopy bool
  572. // SkipDecodeRecovery skips over panic recovery during packet decoding.
  573. // Normally, when packets decode, if a panic occurs, that panic is captured
  574. // by a recover(), and a DecodeFailure layer is added to the packet detailing
  575. // the issue. If this flag is set, panics are instead allowed to continue up
  576. // the stack.
  577. SkipDecodeRecovery bool
  578. // DecodeStreamsAsDatagrams enables routing of application-level layers in the TCP
  579. // decoder. If true, we should try to decode layers after TCP in single packets.
  580. // This is disabled by default because the reassembly package drives the decoding
  581. // of TCP payload data after reassembly.
  582. DecodeStreamsAsDatagrams bool
  583. }
  584. // Default decoding provides the safest (but slowest) method for decoding
  585. // packets. It eagerly processes all layers (so it's concurrency-safe) and it
  586. // copies its input buffer upon creation of the packet (so the packet remains
  587. // valid if the underlying slice is modified. Both of these take time,
  588. // though, so beware. If you can guarantee that the packet will only be used
  589. // by one goroutine at a time, set Lazy decoding. If you can guarantee that
  590. // the underlying slice won't change, set NoCopy decoding.
  591. var Default = DecodeOptions{}
  592. // Lazy is a DecodeOptions with just Lazy set.
  593. var Lazy = DecodeOptions{Lazy: true}
  594. // NoCopy is a DecodeOptions with just NoCopy set.
  595. var NoCopy = DecodeOptions{NoCopy: true}
  596. // DecodeStreamsAsDatagrams is a DecodeOptions with just DecodeStreamsAsDatagrams set.
  597. var DecodeStreamsAsDatagrams = DecodeOptions{DecodeStreamsAsDatagrams: true}
  598. // NewPacket creates a new Packet object from a set of bytes. The
  599. // firstLayerDecoder tells it how to interpret the first layer from the bytes,
  600. // future layers will be generated from that first layer automatically.
  601. func NewPacket(data []byte, firstLayerDecoder Decoder, options DecodeOptions) Packet {
  602. if !options.NoCopy {
  603. dataCopy := make([]byte, len(data))
  604. copy(dataCopy, data)
  605. data = dataCopy
  606. }
  607. if options.Lazy {
  608. p := &lazyPacket{
  609. packet: packet{data: data, decodeOptions: options},
  610. next: firstLayerDecoder,
  611. }
  612. p.layers = p.initialLayers[:0]
  613. // Crazy craziness:
  614. // If the following return statemet is REMOVED, and Lazy is FALSE, then
  615. // eager packet processing becomes 17% FASTER. No, there is no logical
  616. // explanation for this. However, it's such a hacky micro-optimization that
  617. // we really can't rely on it. It appears to have to do with the size the
  618. // compiler guesses for this function's stack space, since one symptom is
  619. // that with the return statement in place, we more than double calls to
  620. // runtime.morestack/runtime.lessstack. We'll hope the compiler gets better
  621. // over time and we get this optimization for free. Until then, we'll have
  622. // to live with slower packet processing.
  623. return p
  624. }
  625. p := &eagerPacket{
  626. packet: packet{data: data, decodeOptions: options},
  627. }
  628. p.layers = p.initialLayers[:0]
  629. p.initialDecode(firstLayerDecoder)
  630. return p
  631. }
  632. // PacketDataSource is an interface for some source of packet data. Users may
  633. // create their own implementations, or use the existing implementations in
  634. // gopacket/pcap (libpcap, allows reading from live interfaces or from
  635. // pcap files) or gopacket/pfring (PF_RING, allows reading from live
  636. // interfaces).
  637. type PacketDataSource interface {
  638. // ReadPacketData returns the next packet available from this data source.
  639. // It returns:
  640. // data: The bytes of an individual packet.
  641. // ci: Metadata about the capture
  642. // err: An error encountered while reading packet data. If err != nil,
  643. // then data/ci will be ignored.
  644. ReadPacketData() (data []byte, ci CaptureInfo, err error)
  645. }
  646. // ConcatFinitePacketDataSources returns a PacketDataSource that wraps a set
  647. // of internal PacketDataSources, each of which will stop with io.EOF after
  648. // reading a finite number of packets. The returned PacketDataSource will
  649. // return all packets from the first finite source, followed by all packets from
  650. // the second, etc. Once all finite sources have returned io.EOF, the returned
  651. // source will as well.
  652. func ConcatFinitePacketDataSources(pds ...PacketDataSource) PacketDataSource {
  653. c := concat(pds)
  654. return &c
  655. }
  656. type concat []PacketDataSource
  657. func (c *concat) ReadPacketData() (data []byte, ci CaptureInfo, err error) {
  658. for len(*c) > 0 {
  659. data, ci, err = (*c)[0].ReadPacketData()
  660. if err == io.EOF {
  661. *c = (*c)[1:]
  662. continue
  663. }
  664. return
  665. }
  666. return nil, CaptureInfo{}, io.EOF
  667. }
  668. // ZeroCopyPacketDataSource is an interface to pull packet data from sources
  669. // that allow data to be returned without copying to a user-controlled buffer.
  670. // It's very similar to PacketDataSource, except that the caller must be more
  671. // careful in how the returned buffer is handled.
  672. type ZeroCopyPacketDataSource interface {
  673. // ZeroCopyReadPacketData returns the next packet available from this data source.
  674. // It returns:
  675. // data: The bytes of an individual packet. Unlike with
  676. // PacketDataSource's ReadPacketData, the slice returned here points
  677. // to a buffer owned by the data source. In particular, the bytes in
  678. // this buffer may be changed by future calls to
  679. // ZeroCopyReadPacketData. Do not use the returned buffer after
  680. // subsequent ZeroCopyReadPacketData calls.
  681. // ci: Metadata about the capture
  682. // err: An error encountered while reading packet data. If err != nil,
  683. // then data/ci will be ignored.
  684. ZeroCopyReadPacketData() (data []byte, ci CaptureInfo, err error)
  685. }
  686. // PacketSource reads in packets from a PacketDataSource, decodes them, and
  687. // returns them.
  688. //
  689. // There are currently two different methods for reading packets in through
  690. // a PacketSource:
  691. //
  692. // Reading With Packets Function
  693. //
  694. // This method is the most convenient and easiest to code, but lacks
  695. // flexibility. Packets returns a 'chan Packet', then asynchronously writes
  696. // packets into that channel. Packets uses a blocking channel, and closes
  697. // it if an io.EOF is returned by the underlying PacketDataSource. All other
  698. // PacketDataSource errors are ignored and discarded.
  699. // for packet := range packetSource.Packets() {
  700. // ...
  701. // }
  702. //
  703. // Reading With NextPacket Function
  704. //
  705. // This method is the most flexible, and exposes errors that may be
  706. // encountered by the underlying PacketDataSource. It's also the fastest
  707. // in a tight loop, since it doesn't have the overhead of a channel
  708. // read/write. However, it requires the user to handle errors, most
  709. // importantly the io.EOF error in cases where packets are being read from
  710. // a file.
  711. // for {
  712. // packet, err := packetSource.NextPacket()
  713. // if err == io.EOF {
  714. // break
  715. // } else if err != nil {
  716. // log.Println("Error:", err)
  717. // continue
  718. // }
  719. // handlePacket(packet) // Do something with each packet.
  720. // }
  721. type PacketSource struct {
  722. source PacketDataSource
  723. decoder Decoder
  724. // DecodeOptions is the set of options to use for decoding each piece
  725. // of packet data. This can/should be changed by the user to reflect the
  726. // way packets should be decoded.
  727. DecodeOptions
  728. c chan Packet
  729. }
  730. // NewPacketSource creates a packet data source.
  731. func NewPacketSource(source PacketDataSource, decoder Decoder) *PacketSource {
  732. return &PacketSource{
  733. source: source,
  734. decoder: decoder,
  735. }
  736. }
  737. // NextPacket returns the next decoded packet from the PacketSource. On error,
  738. // it returns a nil packet and a non-nil error.
  739. func (p *PacketSource) NextPacket() (Packet, error) {
  740. data, ci, err := p.source.ReadPacketData()
  741. if err != nil {
  742. return nil, err
  743. }
  744. packet := NewPacket(data, p.decoder, p.DecodeOptions)
  745. m := packet.Metadata()
  746. m.CaptureInfo = ci
  747. m.Truncated = m.Truncated || ci.CaptureLength < ci.Length
  748. return packet, nil
  749. }
  750. // packetsToChannel reads in all packets from the packet source and sends them
  751. // to the given channel. When it receives an error, it ignores it. When it
  752. // receives an io.EOF, it closes the channel.
  753. func (p *PacketSource) packetsToChannel() {
  754. defer close(p.c)
  755. for {
  756. packet, err := p.NextPacket()
  757. if err == io.EOF {
  758. return
  759. } else if err == nil {
  760. p.c <- packet
  761. }
  762. }
  763. }
  764. // Packets returns a channel of packets, allowing easy iterating over
  765. // packets. Packets will be asynchronously read in from the underlying
  766. // PacketDataSource and written to the returned channel. If the underlying
  767. // PacketDataSource returns an io.EOF error, the channel will be closed.
  768. // If any other error is encountered, it is ignored.
  769. //
  770. // for packet := range packetSource.Packets() {
  771. // handlePacket(packet) // Do something with each packet.
  772. // }
  773. //
  774. // If called more than once, returns the same channel.
  775. func (p *PacketSource) Packets() chan Packet {
  776. if p.c == nil {
  777. p.c = make(chan Packet, 1000)
  778. go p.packetsToChannel()
  779. }
  780. return p.c
  781. }