packet.go 26 KB

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