From 79ed37abfefb87f76277442589bd2b74155560d8 Mon Sep 17 00:00:00 2001 From: TochusC <205329624@qq.com> Date: Wed, 23 Oct 2024 16:57:08 +0800 Subject: [PATCH] Update: Add Chinese translation to multiple doc.go file and copyright year to 2024 in multiple source files --- LICENSE | 6 +- README.md | 21 +- afpacket/afpacket.go | 10 +- afpacket/afpacket_test.go | 2 + afpacket/header.go | 2 + afpacket/options.go | 2 + afpacket/sockopt_linux.go | 2 + base.go | 1 + bsdbpf/bsd_bpf_sniffer.go | 1 + bytediff/bytediff.go | 10 +- bytediff/bytediff_test.go | 1 + decode.go | 22 +- defrag/lcmdefrag/lcmdefrag.go | 6 +- defrag/lcmdefrag/lcmdefrag_test.go | 1 + doc.go | 805 +++++++++++++-------------- dumpcommand/tcpdump.go | 1 + examples/afpacket/afpacket.go | 1 + examples/arpscan/arpscan.go | 7 +- examples/bidirectional/main.go | 1 + examples/bytediff/main.go | 1 + examples/httpassembly/main.go | 1 + examples/pcapdump/main.go | 1 + examples/pcaplay/main.go | 1 + examples/pfdump/main.go | 1 + examples/reassemblydump/main.go | 1 + examples/statsassembly/main.go | 1 + examples/synscan/main.go | 1 + examples/util/util.go | 9 +- flows.go | 1 + layerclass.go | 1 + layers/arp.go | 1 + layers/base.go | 1 + layers/cdp.go | 1 + layers/ctp.go | 1 + layers/dhcpv4.go | 3 +- layers/dhcpv6.go | 1 + layers/dns.go | 3 +- layers/doc.go | 1 + layers/dot1q.go | 1 + layers/dot1q_test.go | 1 + layers/eap.go | 1 + layers/eapol.go | 1 + layers/endpoints.go | 1 + layers/enums.go | 1 + layers/enums_generated.go | 1 + layers/erspan2.go | 1 + layers/erspan2_test.go | 1 + layers/etherip.go | 1 + layers/ethernet.go | 1 + layers/fddi.go | 1 + layers/gen.go | 4 +- layers/gen2.go | 4 +- layers/geneve.go | 1 + layers/geneve_test.go | 1 + layers/gre.go | 1 + layers/gre_test.go | 41 +- layers/iana_ports.go | 1 + layers/icmp4.go | 1 + layers/icmp6.go | 1 + layers/icmp6msg.go | 1 + layers/igmp.go | 11 +- layers/ip4.go | 1 + layers/ip4_test.go | 1 + layers/ip6.go | 1 + layers/ipsec.go | 1 + layers/layertypes.go | 1 + layers/lcm.go | 6 +- layers/lcm_test.go | 1 + layers/linux_sll.go | 1 + layers/llc.go | 8 +- layers/lldp.go | 3 +- layers/loopback.go | 1 + layers/mpls.go | 9 +- layers/mpls_test.go | 1 + layers/ndp.go | 1 + layers/ntp.go | 94 ++-- layers/ntp_test.go | 4 +- layers/pflog.go | 1 + layers/ports.go | 1 + layers/ppp.go | 1 + layers/pppoe.go | 1 + layers/radiotap_test.go | 19 +- layers/rudp.go | 1 + layers/sctp.go | 1 + layers/stp_test.go | 1 + layers/tcp.go | 1 + layers/tcpip.go | 1 + layers/udp.go | 1 + layers/udplite.go | 1 + layers/vrrp.go | 1 + layers/vrrp_test.go | 15 +- layers/vxlan.go | 1 + layers/vxlan_test.go | 4 +- layertype.go | 1 + macs/benchmark_test.go | 1 + macs/doc.go | 8 +- macs/gen.go | 4 +- macs/valid_mac_prefixes.go | 1 + packet.go | 57 +- packet_test.go | 1 + parser.go | 84 +-- pcap/doc.go | 178 +++--- pcap/gopacket_benchmark/benchmark.go | 1 + pcap/pcap.go | 1 + pcap/pcap_test.go | 1 + pcap/pcap_tester.go | 2 + pcap/pcap_unix.go | 2 + pcap/pcap_windows.go | 1 + pcap/pcapgo_test.go | 1 + pcapgo/capture.go | 2 + pcapgo/capture_test.go | 2 + pcapgo/write.go | 49 +- pcapgo/write_test.go | 1 + pfring/doc.go | 1 + pfring/pfring.go | 8 +- reassembly/cap2test.go | 2 + reassembly/memory.go | 1 + reassembly/tcpassembly.go | 28 +- reassembly/tcpassembly_test.go | 1 + reassembly/tcpcheck.go | 1 + reassembly/tcpcheck_test.go | 1 + routing/common.go | 1 + routing/other.go | 2 + routing/routing.go | 2 + routing/routing_test.go | 2 + tcpassembly/assembly.go | 27 +- tcpassembly/assembly_test.go | 1 + tcpassembly/tcpreader/reader.go | 73 +-- tcpassembly/tcpreader/reader_test.go | 1 + writer.go | 18 +- writer_test.go | 1 + 131 files changed, 962 insertions(+), 804 deletions(-) diff --git a/LICENSE b/LICENSE index 2100d524d..88c27ef81 100644 --- a/LICENSE +++ b/LICENSE @@ -1,3 +1,5 @@ + +Copyright (c) 2024 TochusC. All rights reserved. Copyright (c) 2012 Google, Inc. All rights reserved. Copyright (c) 2009-2011 Andreas Krennmair. All rights reserved. @@ -11,8 +13,8 @@ notice, this list of conditions and the following disclaimer. copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of Andreas Krennmair, Google, nor the names of its -contributors may be used to endorse or promote products derived from + * Neither the name of Andreas Krennmair, Google, TochusC nor the names +of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS diff --git a/README.md b/README.md index 5968678ea..3238a6367 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,21 @@ -# GoPacket +# TochusC/GoPacket +该库为`google/gopacket`的分支版本,除为 Go 提供了数据包解码功能外,特别地对layers/dns.go文件进行了修改,以进行DNS相关实验。 -This library provides packet decoding capabilities for Go. -See [godoc](https://godoc.org/github.com/tochusc/gopacket) for more details. +## 引入的新特性🌟 +- 支持构建并发送未知类型的Resource Recourd(RR), +- 添加对DNSSEC相关RR的基本支持 + +## 未来工作🛠️ +- 进一步扩展对DNSSEC的支持 +- 添加更多RR类型 + +有关更多详细信息,请参阅 [godoc](https://godoc.org/github.com/tochusc/gopacket)。 [![Build Status](https://travis-ci.org/google/gopacket.svg?branch=master)](https://travis-ci.org/google/gopacket) [![GoDoc](https://godoc.org/github.com/tochusc/gopacket?status.svg)](https://godoc.org/github.com/tochusc/gopacket) -Minimum Go version required is 1.5 except for pcapgo/EthernetHandle, afpacket, and bsdbpf which need at least 1.9 due to x/sys/unix dependencies. +最低 Go 版本要求是 1.9 + +最初从 Andreas Krennmair (http://github.com/akrennmair/gopcap) 编写的 gopcap 项目中分叉出来。 -Originally forked from the gopcap project written by Andreas -Krennmair (http://github.com/akrennmair/gopcap). +`layers\dns.go`中的相关代码参考了 `gopacket\gopacket`(http://github.com/gopacket/gopacket) 项目,感谢他们的贡献! diff --git a/afpacket/afpacket.go b/afpacket/afpacket.go index 4c667bc39..8a2aa6e6b 100644 --- a/afpacket/afpacket.go +++ b/afpacket/afpacket.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -293,10 +294,11 @@ func (h *TPacket) releaseCurrentPacket() error { // to old bytes when using ZeroCopyReadPacketData... if you need to keep data past // the next time you call ZeroCopyReadPacketData, use ReadPacketData, which copies // the bytes into a new buffer for you. -// tp, _ := NewTPacket(...) -// data1, _, _ := tp.ZeroCopyReadPacketData() -// // do everything you want with data1 here, copying bytes out of it if you'd like to keep them around. -// data2, _, _ := tp.ZeroCopyReadPacketData() // invalidates bytes in data1 +// +// tp, _ := NewTPacket(...) +// data1, _, _ := tp.ZeroCopyReadPacketData() +// // do everything you want with data1 here, copying bytes out of it if you'd like to keep them around. +// data2, _, _ := tp.ZeroCopyReadPacketData() // invalidates bytes in data1 func (h *TPacket) ZeroCopyReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error) { h.mu.Lock() retry: diff --git a/afpacket/afpacket_test.go b/afpacket/afpacket_test.go index 57f6480d5..b14ac2f65 100644 --- a/afpacket/afpacket_test.go +++ b/afpacket/afpacket_test.go @@ -1,9 +1,11 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. +//go:build linux // +build linux package afpacket diff --git a/afpacket/header.go b/afpacket/header.go index 61634e7ab..91df5cea6 100644 --- a/afpacket/header.go +++ b/afpacket/header.go @@ -1,9 +1,11 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. +//go:build linux // +build linux package afpacket diff --git a/afpacket/options.go b/afpacket/options.go index 3e305c4d6..c19bee3f1 100644 --- a/afpacket/options.go +++ b/afpacket/options.go @@ -1,9 +1,11 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. +//go:build linux // +build linux package afpacket diff --git a/afpacket/sockopt_linux.go b/afpacket/sockopt_linux.go index c53e1cceb..6b5e0a699 100644 --- a/afpacket/sockopt_linux.go +++ b/afpacket/sockopt_linux.go @@ -1,9 +1,11 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. +//go:build linux // +build linux package afpacket diff --git a/base.go b/base.go index 91e150c21..5316e2e56 100644 --- a/base.go +++ b/base.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/bsdbpf/bsd_bpf_sniffer.go b/bsdbpf/bsd_bpf_sniffer.go index 9f2e30e5b..cd178760b 100644 --- a/bsdbpf/bsd_bpf_sniffer.go +++ b/bsdbpf/bsd_bpf_sniffer.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/bytediff/bytediff.go b/bytediff/bytediff.go index 9d8ee5d77..b0dad5b55 100644 --- a/bytediff/bytediff.go +++ b/bytediff/bytediff.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -95,10 +96,11 @@ func longestCommonSubstring(strA, strB []byte) (indexA, indexB, length int) { // Difference represents a single part of the data being diffed, containing // information about both the original and new values. // From and To are the sets of bytes in the original and the new byte slice. -// !Replace implies From == To (no change) -// len(To) == 0 implies From is being deleted -// len(From) == 0 implies To is being inserted -// else implies From is being replaced by To +// +// !Replace implies From == To (no change) +// len(To) == 0 implies From is being deleted +// len(From) == 0 implies To is being inserted +// else implies From is being replaced by To type Difference struct { Replace bool From, To []byte diff --git a/bytediff/bytediff_test.go b/bytediff/bytediff_test.go index 022ad4bc5..06125fafb 100644 --- a/bytediff/bytediff_test.go +++ b/bytediff/bytediff_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/decode.go b/decode.go index 2633f848e..c5629fbb6 100644 --- a/decode.go +++ b/decode.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -28,16 +29,17 @@ var NilDecodeFeedback DecodeFeedback = nilDecodeFeedback{} // PacketBuilder is used by layer decoders to store the layers they've decoded, // and to defer future decoding via NextDecoder. // Typically, the pattern for use is: -// func (m *myDecoder) Decode(data []byte, p PacketBuilder) error { -// if myLayer, err := myDecodingLogic(data); err != nil { -// return err -// } else { -// p.AddLayer(myLayer) -// } -// // maybe do this, if myLayer is a LinkLayer -// p.SetLinkLayer(myLayer) -// return p.NextDecoder(nextDecoder) -// } +// +// func (m *myDecoder) Decode(data []byte, p PacketBuilder) error { +// if myLayer, err := myDecodingLogic(data); err != nil { +// return err +// } else { +// p.AddLayer(myLayer) +// } +// // maybe do this, if myLayer is a LinkLayer +// p.SetLinkLayer(myLayer) +// return p.NextDecoder(nextDecoder) +// } type PacketBuilder interface { DecodeFeedback // AddLayer should be called by a decoder immediately upon successful diff --git a/defrag/lcmdefrag/lcmdefrag.go b/defrag/lcmdefrag/lcmdefrag.go index 1facf3b66..79c182d59 100644 --- a/defrag/lcmdefrag/lcmdefrag.go +++ b/defrag/lcmdefrag/lcmdefrag.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2018 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -32,8 +33,9 @@ type lcmPacket struct { // LCMDefragmenter supports defragmentation of LCM messages. // // References -// https://lcm-proj.github.io/ -// https://github.com/lcm-proj/lcm +// +// https://lcm-proj.github.io/ +// https://github.com/lcm-proj/lcm type LCMDefragmenter struct { packets map[uint32]*lcmPacket } diff --git a/defrag/lcmdefrag/lcmdefrag_test.go b/defrag/lcmdefrag/lcmdefrag_test.go index d51b80b79..9b6a2f1d8 100644 --- a/defrag/lcmdefrag/lcmdefrag_test.go +++ b/defrag/lcmdefrag/lcmdefrag_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2018 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/doc.go b/doc.go index 6d8a77a6e..969342ae4 100644 --- a/doc.go +++ b/doc.go @@ -1,432 +1,407 @@ -// Copyright 2012 Google, Inc. All rights reserved. +// Copyright 2024 TochusC, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. /* -Package gopacket provides packet decoding for the Go language. - -gopacket contains many sub-packages with additional functionality you may find -useful, including: - - * layers: You'll probably use this every time. This contains of the logic - built into gopacket for decoding packet protocols. Note that all example - code below assumes that you have imported both gopacket and - gopacket/layers. - * pcap: C bindings to use libpcap to read packets off the wire. - * pfring: C bindings to use PF_RING to read packets off the wire. - * afpacket: C bindings for Linux's AF_PACKET to read packets off the wire. - * tcpassembly: TCP stream reassembly - -Also, if you're looking to dive right into code, see the examples subdirectory -for numerous simple binaries built using gopacket libraries. - -Minimum go version required is 1.5 except for pcapgo/EthernetHandle, afpacket, -and bsdbpf which need at least 1.7 due to x/sys/unix dependencies. - -Basic Usage - -gopacket takes in packet data as a []byte and decodes it into a packet with -a non-zero number of "layers". Each layer corresponds to a protocol -within the bytes. Once a packet has been decoded, the layers of the packet -can be requested from the packet. - - // Decode a packet - packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Default) - // Get the TCP layer from this packet - if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil { - fmt.Println("This is a TCP packet!") - // Get actual TCP data from this layer - tcp, _ := tcpLayer.(*layers.TCP) - fmt.Printf("From src port %d to dst port %d\n", tcp.SrcPort, tcp.DstPort) - } - // Iterate over all layers, printing out each layer type - for _, layer := range packet.Layers() { - fmt.Println("PACKET LAYER:", layer.LayerType()) - } - -Packets can be decoded from a number of starting points. Many of our base -types implement Decoder, which allow us to decode packets for which -we don't have full data. - - // Decode an ethernet packet - ethP := gopacket.NewPacket(p1, layers.LayerTypeEthernet, gopacket.Default) - // Decode an IPv6 header and everything it contains - ipP := gopacket.NewPacket(p2, layers.LayerTypeIPv6, gopacket.Default) - // Decode a TCP header and its payload - tcpP := gopacket.NewPacket(p3, layers.LayerTypeTCP, gopacket.Default) - - -Reading Packets From A Source - -Most of the time, you won't just have a []byte of packet data lying around. -Instead, you'll want to read packets in from somewhere (file, interface, etc) -and process them. To do that, you'll want to build a PacketSource. - -First, you'll need to construct an object that implements the PacketDataSource -interface. There are implementations of this interface bundled with gopacket -in the gopacket/pcap and gopacket/pfring subpackages... see their documentation -for more information on their usage. Once you have a PacketDataSource, you can -pass it into NewPacketSource, along with a Decoder of your choice, to create -a PacketSource. - -Once you have a PacketSource, you can read packets from it in multiple ways. -See the docs for PacketSource for more details. The easiest method is the -Packets function, which returns a channel, then asynchronously writes new -packets into that channel, closing the channel if the packetSource hits an -end-of-file. - - packetSource := ... // construct using pcap or pfring - for packet := range packetSource.Packets() { - handlePacket(packet) // do something with each packet - } - -You can change the decoding options of the packetSource by setting fields in -packetSource.DecodeOptions... see the following sections for more details. - - -Lazy Decoding - -gopacket optionally decodes packet data lazily, meaning it -only decodes a packet layer when it needs to handle a function call. - - // Create a packet, but don't actually decode anything yet - packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Lazy) - // Now, decode the packet up to the first IPv4 layer found but no further. - // If no IPv4 layer was found, the whole packet will be decoded looking for - // it. - ip4 := packet.Layer(layers.LayerTypeIPv4) - // Decode all layers and return them. The layers up to the first IPv4 layer - // are already decoded, and will not require decoding a second time. - layers := packet.Layers() - -Lazily-decoded packets are not concurrency-safe. Since layers have not all been -decoded, each call to Layer() or Layers() has the potential to mutate the packet -in order to decode the next layer. If a packet is used -in multiple goroutines concurrently, don't use gopacket.Lazy. Then gopacket -will decode the packet fully, and all future function calls won't mutate the -object. - - -NoCopy Decoding - -By default, gopacket will copy the slice passed to NewPacket and store the -copy within the packet, so future mutations to the bytes underlying the slice -don't affect the packet and its layers. If you can guarantee that the -underlying slice bytes won't be changed, you can use NoCopy to tell -gopacket.NewPacket, and it'll use the passed-in slice itself. - - // This channel returns new byte slices, each of which points to a new - // memory location that's guaranteed immutable for the duration of the - // packet. - for data := range myByteSliceChannel { - p := gopacket.NewPacket(data, layers.LayerTypeEthernet, gopacket.NoCopy) - doSomethingWithPacket(p) - } - -The fastest method of decoding is to use both Lazy and NoCopy, but note from -the many caveats above that for some implementations either or both may be -dangerous. - - -Pointers To Known Layers - -During decoding, certain layers are stored in the packet as well-known -layer types. For example, IPv4 and IPv6 are both considered NetworkLayer -layers, while TCP and UDP are both TransportLayer layers. We support 4 -layers, corresponding to the 4 layers of the TCP/IP layering scheme (roughly -anagalous to layers 2, 3, 4, and 7 of the OSI model). To access these, -you can use the packet.LinkLayer, packet.NetworkLayer, -packet.TransportLayer, and packet.ApplicationLayer functions. Each of -these functions returns a corresponding interface -(gopacket.{Link,Network,Transport,Application}Layer). The first three -provide methods for getting src/dst addresses for that particular layer, -while the final layer provides a Payload function to get payload data. -This is helpful, for example, to get payloads for all packets regardless -of their underlying data type: - - // Get packets from some source - for packet := range someSource { - if app := packet.ApplicationLayer(); app != nil { - if strings.Contains(string(app.Payload()), "magic string") { - fmt.Println("Found magic string in a packet!") - } - } - } - -A particularly useful layer is ErrorLayer, which is set whenever there's -an error parsing part of the packet. - - packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Default) - if err := packet.ErrorLayer(); err != nil { - fmt.Println("Error decoding some part of the packet:", err) - } - -Note that we don't return an error from NewPacket because we may have decoded -a number of layers successfully before running into our erroneous layer. You -may still be able to get your Ethernet and IPv4 layers correctly, even if -your TCP layer is malformed. - - -Flow And Endpoint - -gopacket has two useful objects, Flow and Endpoint, for communicating in a protocol -independent manner the fact that a packet is coming from A and going to B. -The general layer types LinkLayer, NetworkLayer, and TransportLayer all provide -methods for extracting their flow information, without worrying about the type -of the underlying Layer. - -A Flow is a simple object made up of a set of two Endpoints, one source and one -destination. It details the sender and receiver of the Layer of the Packet. - -An Endpoint is a hashable representation of a source or destination. For -example, for LayerTypeIPv4, an Endpoint contains the IP address bytes for a v4 -IP packet. A Flow can be broken into Endpoints, and Endpoints can be combined -into Flows: - - packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Lazy) - netFlow := packet.NetworkLayer().NetworkFlow() - src, dst := netFlow.Endpoints() - reverseFlow := gopacket.NewFlow(dst, src) - -Both Endpoint and Flow objects can be used as map keys, and the equality -operator can compare them, so you can easily group together all packets -based on endpoint criteria: - - flows := map[gopacket.Endpoint]chan gopacket.Packet - packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Lazy) - // Send all TCP packets to channels based on their destination port. - if tcp := packet.Layer(layers.LayerTypeTCP); tcp != nil { - flows[tcp.TransportFlow().Dst()] <- packet - } - // Look for all packets with the same source and destination network address - if net := packet.NetworkLayer(); net != nil { - src, dst := net.NetworkFlow().Endpoints() - if src == dst { - fmt.Println("Fishy packet has same network source and dst: %s", src) - } - } - // Find all packets coming from UDP port 1000 to UDP port 500 - interestingFlow := gopacket.FlowFromEndpoints(layers.NewUDPPortEndpoint(1000), layers.NewUDPPortEndpoint(500)) - if t := packet.NetworkLayer(); t != nil && t.TransportFlow() == interestingFlow { - fmt.Println("Found that UDP flow I was looking for!") - } - -For load-balancing purposes, both Flow and Endpoint have FastHash() functions, -which provide quick, non-cryptographic hashes of their contents. Of particular -importance is the fact that Flow FastHash() is symmetric: A->B will have the same -hash as B->A. An example usage could be: - - channels := [8]chan gopacket.Packet - for i := 0; i < 8; i++ { - channels[i] = make(chan gopacket.Packet) - go packetHandler(channels[i]) - } - for packet := range getPackets() { - if net := packet.NetworkLayer(); net != nil { - channels[int(net.NetworkFlow().FastHash()) & 0x7] <- packet - } - } - -This allows us to split up a packet stream while still making sure that each -stream sees all packets for a flow (and its bidirectional opposite). - - -Implementing Your Own Decoder - -If your network has some strange encapsulation, you can implement your own -decoder. In this example, we handle Ethernet packets which are encapsulated -in a 4-byte header. - - // Create a layer type, should be unique and high, so it doesn't conflict, - // giving it a name and a decoder to use. - var MyLayerType = gopacket.RegisterLayerType(12345, gopacket.LayerTypeMetadata{Name: "MyLayerType", Decoder: gopacket.DecodeFunc(decodeMyLayer)}) - - // Implement my layer - type MyLayer struct { - StrangeHeader []byte - payload []byte - } - func (m MyLayer) LayerType() gopacket.LayerType { return MyLayerType } - func (m MyLayer) LayerContents() []byte { return m.StrangeHeader } - func (m MyLayer) LayerPayload() []byte { return m.payload } - - // Now implement a decoder... this one strips off the first 4 bytes of the - // packet. - func decodeMyLayer(data []byte, p gopacket.PacketBuilder) error { - // Create my layer - p.AddLayer(&MyLayer{data[:4], data[4:]}) - // Determine how to handle the rest of the packet - return p.NextDecoder(layers.LayerTypeEthernet) - } - - // Finally, decode your packets: - p := gopacket.NewPacket(data, MyLayerType, gopacket.Lazy) +gopacket 提供了用于 Go 语言的数据包解码功能。 + +gopacket 包含许多子包,这些子包提供了额外的功能,包括: + + - layers:您可能每次都将会使用layers。它包含了 gopacket 内置的用于解码数据包协议的逻辑。请注意,以下的所有示例代码都将假设您已经导入了 gopacket 和 gopacket/layers。 + - pcap:C 绑定,用于使用 libpcap 从网络中读取数据包。 + - pfring:C 绑定,用于使用 PF_RING 从网络中读取数据包。 + - afpacket:C 绑定,用于使用 Linux 的 AF_PACKET 从网络中读取数据包。 + - tcpassembly:TCP 流重组 + +此外,如果您想直接进入代码,请参阅 examples 子目录,其中包含了许多使用 gopacket 库构建的简单二进制文件。 + +最低 Go 版本要求是 1.5,但 pcapgo/EthernetHandle、afpacket 和 bsdbpf 由于依赖 x/sys/unix ,所以至少需要 1.7 及以上的版本。 + +基本用法 + +gopacket 接收一个 []byte 类型的数据包数据,并将其解码为包含一个或多个“层”的数据包。 +每一层对应于字节中的一个协议。一旦数据包被解码,数据包的层就可以直接从数据包中请求。 + + // 解码一个数据包 + packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Default) + // 从这个数据包中获取 TCP 层 + if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil { + fmt.Println("这是一个 TCP 数据包!") + // 从该层获取实际的 TCP 数据 + tcp, _ := tcpLayer.(*layers.TCP) + fmt.Printf("从源端口 %d 到目标端口 %d\n", tcp.SrcPort, tcp.DstPort) + } + // 遍历所有层,打印出每一层的类型 + for _, layer := range packet.Layers() { + fmt.Println("数据包层:", layer.LayerType()) + } + +数据包可以从多个起点解码。我们的许多基本类型实现了 Decoder 接口, +这使我们能够解码我们没有完整数据的数据包。 + + // 解码一个以太网数据包 + ethP := gopacket.NewPacket(p1, layers.LayerTypeEthernet, gopacket.Default) + // 解码一个 IPv6 头及其包含的所有内容 + ipP := gopacket.NewPacket(p2, layers.LayerTypeIPv6, gopacket.Default) + // 解码一个 TCP 头及其负载 + tcpP := gopacket.NewPacket(p3, layers.LayerTypeTCP, gopacket.Default) + +从源读取数据包 + +大多数时候,您不会仅仅只拥有一个 []byte 类型的数据包数据。 +相反,您可能会希望从某个地方(文件、接口等)读取数据包并处理它们。 +为此,您需要构建一个 PacketSource 对象。 + +为此,您需要首先构造一个实现 PacketDataSource 接口的对象。 +gopacket 在 gopacket/pcap 和 gopacket/pfring 子包中包含了这个接口的实现…… +请参阅它们的文档以获取更多使用信息。 +一旦您有了一个 PacketDataSource,您可以将其传递给 NewPacketSource, +并选择一个 Decoder 来创建一个 PacketSource。 + +一旦您有了一个 PacketSource 后,您可以通过多种方式从中读取数据包。 +请参阅 PacketSource 的文档以获取更多详细信息。 +最简单的方法是 Packets 函数,它返回一个通道,然后异步地将新数据包写入该通道, +如果 packetSource 遇到文件结束,则关闭该通道。 + + packetSource := ... // 使用 pcap 或 pfring 构造 + for packet := range packetSource.Packets() { + handlePacket(packet) // 对每个数据包执行某些操作 + } + +您可以通过设置 packetSource.DecodeOptions 中的字段来更改 packetSource 的解码选项…… +请参阅以下部分以获取更多详细信息。 + + +# 延迟解码 + +gopacket 可以选择性地延迟解码数据包数据,这代表gopacket +将只会在需要处理函数调用时才解码数据包层。 + + // 创建一个数据包,但实际上还没有解码任何内容 + packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Lazy) + // 现在,解码数据包直到发现第一个 IPv4 层,但不再进一步解码。 + // 如果没有发现 IPv4 层,gopacket将解码整个数据包以寻找IPv4层。 + ip4 := packet.Layer(layers.LayerTypeIPv4) + // 解码所有层并返回它们。在第一个 IPv4 层前已经被解码过的内容将不会被再次解码。 + layers := packet.Layers() + +延迟解码的数据包不是并发安全的。 +由于没有一次性解码所有层,所以每次调用 Layer() 或 Layers() 都因为要解码下一层而改变数据包。 +如果一个数据包在多个 goroutine 中被并发使用,请不要使用 gopacket.Lazy 参数。 +这样 gopacket 将完全解码数据包,使得后续函数调用不会改变数据包对象。 + + +无拷贝解码 + +默认情况下,gopacket 将复制传递给 NewPacket 的切片参数,并将拷贝存储在生成的数据包中, +因此对原始切片的后续更改不会影响新生成的数据包及其所包含的层。 +如果您可以保证底层切片不会被更改,您可以将 NoCopy 参数传递给 gopacket.NewPacket, +这将让 NewPacket 使用传入的切片本身,而不是使用拷贝来承载数据。 + + // 这个通道返回新的字节切片,每个切片都指向一个新的内存位置, + // 该位置在数据包的持续时间内是不可变的。 + for data := range myByteSliceChannel { + p := gopacket.NewPacket(data, layers.LayerTypeEthernet, gopacket.NoCopy) + doSomethingWithPacket(p) + } + +最快的解码方法是同时使用 Lazy 和 NoCopy,但请注意上述的许多警告,对于某些实现,使用Lazy或NoCopy可能产生危险。 + + +指向已知层的指针 + +在解码过程中,某些层被存储为数据包中的已知层类型。例如,IPv4 和 IPv6 都被视为网络层(NetworkLayer)层, +而 TCP 和 UDP 都被视为传输层(TransportLayer)层。gopacket采用 4 层划分,分别对应于 TCP/IP 分层方案的 4 层 +(大致类似于 OSI 模型的第 2、3、4 和 7 层)。要访问这些层,可以使用 packet.LinkLayer、packet.NetworkLayer、 +packet.TransportLayer 和 packet.ApplicationLayer 函数。每个函数返回一个相应的接口(gopacket.{Link,Network,Transport,Application}Layer)。 +前三层(LinkLayer, NetworkLayer, TransportLayer)的接口提供了获取该特定层的源/目标地址的方法,而最后一层(ApplicationLayer)的接口则提供 Payload 函数以获取其有效负荷。 +这可以帮助您忽视底层数据类型,从而直接获取所有数据包的有效负荷: + +// 从某个源获取数据包 + + for packet := range someSource { + if app := packet.ApplicationLayer(); app != nil { + if strings.Contains(string(app.Payload()), "magic string") { + fmt.Println("在数据包中找到了奇妙字符串(magic string)!") + } + } + } + +一个特别有用的层是 ErrorLayer,当数据包某部分出现解码错误时会设置该层。 + + packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Default) + if err := packet.ErrorLayer(); err != nil { + fmt.Println("解码数据包某部分时发生错误:", err) + } + +请注意 gopacket 并没有从 NewPacket 中返回错误, +这是因为在遇到错误的层之前,gopacket 可能已经成功解码了许多层。 +这使得即使数据包的 TCP 层可能格式不正确,但您仍然可以正确获取数据包的 以太网 和 IPv4 层数据。 + + +流和端点 + +gopacket 有着两个重要的概念:流和结束点。 +在忽视协议的情况下,信息传输实质是从A到B的数据包流。 +常用的层接口 LinkLayer、NetworkLayer 和 TransportLayer +都提供了能够忽视底层,而直接提取该层数据流信息的方法。 + + +一个 流(Flow) 是一个由两个端点(Endpoint)组成的简单对象,一个源端点和一个目标端点。 +它详细描述了数据包在该层的发送者和接收者。 + + +一个端点(Endpoint)是源或目标的可哈希表示。 +例如,对于 LayerTypeIPv4,一个端点包含了 v4 IP 数据包的 IP 地址字节。 +一个流可以被分解为端点,并且端点可以被组合成流。 + + packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Lazy) + netFlow := packet.NetworkLayer().NetworkFlow() + src, dst := netFlow.Endpoints() + reverseFlow := gopacket.NewFlow(dst, src) + +端点和流都可以被用作 map 键, +并且等号操作符可以比较它们, +因此您可以通过对端点的判断条件轻松地将所有数据包分组在一起: + + flows := map[gopacket.Endpoint]chan gopacket.Packet + packet := gopacket.NewPacket(myPacketData, layers.LayerTypeEthernet, gopacket.Lazy) + // 根据TCP数据包的目标端口,将所有数据吧发送到不同的通道。 + if tcp := packet.Layer(layers.LayerTypeTCP); tcp != nil { + flows[tcp.TransportFlow().Dst()] <- packet + } + // 寻找有着相同源和目标网络地址的数据包 + if net := packet.NetworkLayer(); net != nil { + src, dst := net.NetworkFlow().Endpoints() + if src == dst { + fmt.Println("有着相同源和目标地址的可疑数据包: %s", src) + } + } + // 寻找所有从UDP端口1000到UDP端口500的数据包 + interestingFlow := gopacket.FlowFromEndpoints(layers.NewUDPPortEndpoint(1000), layers.NewUDPPortEndpoint(500)) + if t := packet.NetworkLayer(); t != nil && t.TransportFlow() == interestingFlow { + fmt.Println("发现了我所寻找的UDP数据流!") + } + +为了平衡负载,Flow 和 Endpoint 都有 FastHash() 函数,它们提供了快速的、非加密的哈希值。 +特别重要的是 Flow FastHash() 是对称运算:A->B 的哈希值与 B->A 的哈希值相同。 +一个可能的使用示例: + + channels := [8]chan gopacket.Packet + for i := 0; i < 8; i++ { + channels[i] = make(chan gopacket.Packet) + go packetHandler(channels[i]) + } + for packet := range getPackets() { + if net := packet.NetworkLayer(); net != nil { + channels[int(net.NetworkFlow().FastHash()) & 0x7] <- packet + } + } + +这允许我们在确保每个传输流将所有数据包看作同一个数据流 +(从数据流的另一端也没问题)的情况下,对数据包进行分割。 + + +实现你自己的解码器 + + +如果你的网络有一些奇怪的封装,你可以实现自己的解码器。 +在这个例子中,我们处理以太网数据包,但这些数据包被封装在一个 4 字节的头部中。 + + // 创建一个层类型,并给它一个唯一的编号,以避免冲突。 + // 给该层定义对应的名字和解码器。 + var MyLayerType = gopacket.RegisterLayerType(12345, gopacket.LayerTypeMetadata{Name: "MyLayerType", Decoder: gopacket.DecodeFunc(decodeMyLayer)}) + + // 实现 MyLayer + type MyLayer struct { + StrangeHeader []byte + payload []byte + } + func (m MyLayer) LayerType() gopacket.LayerType { return MyLayerType } + func (m MyLayer) LayerContents() []byte { return m.StrangeHeader } + func (m MyLayer) LayerPayload() []byte { return m.payload } + + // 现在实现一个解码器... 这个解码器会去掉数据包的前 4 个字节。 + func decodeMyLayer(data []byte, p gopacket.PacketBuilder) error { + // 添加 MyLayer + p.AddLayer(&MyLayer{data[:4], data[4:]}) + // 决定如何处理数据包的剩余部分 + return p.NextDecoder(layers.LayerTypeEthernet) + } + + // 最后,解码你的数据包: + p := gopacket.NewPacket(data, MyLayerType, gopacket.Lazy) See the docs for Decoder and PacketBuilder for more details on how coding decoders works, or look at RegisterLayerType and RegisterEndpointType to see how to add layer/endpoint types to gopacket. - - -Fast Decoding With DecodingLayerParser - -TLDR: DecodingLayerParser takes about 10% of the time as NewPacket to decode -packet data, but only for known packet stacks. - -Basic decoding using gopacket.NewPacket or PacketSource.Packets is somewhat slow -due to its need to allocate a new packet and every respective layer. It's very -versatile and can handle all known layer types, but sometimes you really only -care about a specific set of layers regardless, so that versatility is wasted. - -DecodingLayerParser avoids memory allocation altogether by decoding packet -layers directly into preallocated objects, which you can then reference to get -the packet's information. A quick example: - - func main() { - var eth layers.Ethernet - var ip4 layers.IPv4 - var ip6 layers.IPv6 - var tcp layers.TCP - parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, ð, &ip4, &ip6, &tcp) - decoded := []gopacket.LayerType{} - for packetData := range somehowGetPacketData() { - if err := parser.DecodeLayers(packetData, &decoded); err != nil { - fmt.Fprintf(os.Stderr, "Could not decode layers: %v\n", err) - continue - } - for _, layerType := range decoded { - switch layerType { - case layers.LayerTypeIPv6: - fmt.Println(" IP6 ", ip6.SrcIP, ip6.DstIP) - case layers.LayerTypeIPv4: - fmt.Println(" IP4 ", ip4.SrcIP, ip4.DstIP) - } - } - } - } - -The important thing to note here is that the parser is modifying the passed in -layers (eth, ip4, ip6, tcp) instead of allocating new ones, thus greatly -speeding up the decoding process. It's even branching based on layer type... -it'll handle an (eth, ip4, tcp) or (eth, ip6, tcp) stack. However, it won't -handle any other type... since no other decoders were passed in, an (eth, ip4, -udp) stack will stop decoding after ip4, and only pass back [LayerTypeEthernet, -LayerTypeIPv4] through the 'decoded' slice (along with an error saying it can't -decode a UDP packet). - -Unfortunately, not all layers can be used by DecodingLayerParser... only those -implementing the DecodingLayer interface are usable. Also, it's possible to -create DecodingLayers that are not themselves Layers... see -layers.IPv6ExtensionSkipper for an example of this. - -Faster And Customized Decoding with DecodingLayerContainer - -By default, DecodingLayerParser uses native map to store and search for a layer -to decode. Though being versatile, in some cases this solution may be not so -optimal. For example, if you have only few layers faster operations may be -provided by sparse array indexing or linear array scan. - -To accomodate these scenarios, DecodingLayerContainer interface is introduced -along with its implementations: DecodingLayerSparse, DecodingLayerArray and -DecodingLayerMap. You can specify a container implementation to -DecodingLayerParser with SetDecodingLayerContainer method. Example: - - dlp := gopacket.NewDecodingLayerParser(LayerTypeEthernet) - dlp.SetDecodingLayerContainer(gopacket.DecodingLayerSparse(nil)) - var eth layers.Ethernet - dlp.AddDecodingLayer(ð) - // ... add layers and use DecodingLayerParser as usual... +您可以去查看 Decoder 和 PacketBuilder 的文档,以获取更多关于编写解码器的细节, +或者查看 RegisterLayerType 和 RegisterEndpointType 以了解如何向 gopacket 添加层/端点类型。 + +# 使用 DecodingLayerParser 快速解码 + +你的文档写太长了,我本来是不会看的, +但你的总结又很好地弥补了这一点(Too Long; Didn't Read. TLDR): +DecodingLayerParser 解码数据包只需要 NewPacket 解码的 10% 时间, +但它仅支持具有已知协议栈的数据包。 + + +使用 gopacket.NewPacket 或 PacketSource.Packets 的基本解码会有一些慢, +这是因为它需要为每个数据包和每个相应的层分配新的内存。 +它非常灵活,可以处理所有已知的层类型,但有时您只关心特定的一组层, +因此有时这种灵活性是多余的。 + +DecodingLayerParser 通过直接将数据包层解码到预分配的对象中来避免内存分配, +然后您可以引用这些对象来获取数据包的信息。 +一个快速示例如下: + + func main() { + var eth layers.Ethernet + var ip4 layers.IPv4 + var ip6 layers.IPv6 + var tcp layers.TCP + parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, ð, &ip4, &ip6, &tcp) + decoded := []gopacket.LayerType{} + for packetData := range somehowGetPacketData() { + if err := parser.DecodeLayers(packetData, &decoded); err != nil { + fmt.Fprintf(os.Stderr, "无法解码网络层: %v\n", err) + continue + } + for _, layerType := range decoded { + switch layerType { + case layers.LayerTypeIPv6: + fmt.Println(" IP6 ", ip6.SrcIP, ip6.DstIP) + case layers.LayerTypeIPv4: + fmt.Println(" IP4 ", ip4.SrcIP, ip4.DstIP) + } + } + } + } + +值得注意的是,解析器(Parser)修改了传入的层(eth、ip4、ip6、tcp)而不是分配新的层, +从而大大加快了解码过程。它甚至根据层类型进行分支…… +它将只会处理(eth、ip4、tcp)或(eth、ip6、tcp)协议栈。而不会处理任何其他类型…… +因为没有传入其他解码器,所以(eth、ip4、udp)协议栈将会在 ip4 后停止解码, +并且只通过“decoded”切片返回 [LayerTypeEthernet, LayerTypeIPv4](以及一个error,表示无法解码 UDP 数据包)。 + +很遗憾,并非所有层都可以被 DecodingLayerParser 使用…… +只有实现了 DecodingLayer 接口的层才能被使用。 +此外,是有可能创建 DecodingLayer 的,而这些 DecodingLayer 本身并不是 Layer…… +请查看 layers.IPv6ExtensionSkipper 以获取这方面的示例。 + +使用 DecodingLayerContainer 来快速并自定义解码 + +尽管它很灵活,但在某些情况下,这种解决方案可能不是最佳的。 +例如,如果您只有几个层,那么稀疏数组索引或线性数组扫描可能提供更快的操作。 + +为了适应这些情况,gopacket引入了 DecodingLayerContainer 接口及其实现: +DecodingLayerSparse、DecodingLayerArray 和 DecodingLayerMap。 +您可以使用 SetDecodingLayerContainer 方法为 DecodingLayerParser 指定容器实现。 +示例如下: + + dlp := gopacket.NewDecodingLayerParser(LayerTypeEthernet) + dlp.SetDecodingLayerContainer(gopacket.DecodingLayerSparse(nil)) + var eth layers.Ethernet + dlp.AddDecodingLayer(ð) + // ... 如同正常情况一样添加层并且使用 DecodingLayerParser... To skip one level of indirection (though sacrificing some capabilities) you may also use DecodingLayerContainer as a decoding tool as it is. In this case you have to handle unknown layer types and layer panics by yourself. Example: +若想要跳过一层"套娃"(Level of Indirection) (尽管这会牺牲一些功能), +您也可以将 DecodingLayerContainer 作为解码工具使用。 + + func main() { + var eth layers.Ethernet + var ip4 layers.IPv4 + var ip6 layers.IPv6 + var tcp layers.TCP + dlc := gopacket.DecodingLayerContainer(gopacket.DecodingLayerArray(nil)) + dlc = dlc.Put(ð) + dlc = dlc.Put(&ip4) + dlc = dlc.Put(&ip6) + dlc = dlc.Put(&tcp) + // 你也可以指定一些有意义的 DecodeFeedback + decoder := dlc.LayersDecoder(LayerTypeEthernet, gopacket.NilDecodeFeedback) + decoded := make([]gopacket.LayerType, 0, 20) + for packetData := range somehowGetPacketData() { + lt, err := decoder(packetData, &decoded) + if err != nil { + fmt.Fprintf(os.Stderr, "解码网络层失败: %v\n", err) + continue + } + if lt != gopacket.LayerTypeZero { + fmt.Fprintf(os.Stderr, "未知的层类型: %v\n", lt) + continue + } + for _, layerType := range decoded { + // 像上面展示的那样检查解码的层类型 + } + } + } + +当层(layers)所使用的 LayerType 值可以被解码, +并且层的数量不多时,DecodingLayerSparse 是最快速及最高效的, +当层的数量很多时,DecodingLayerSparse 可能会导致更大的内存占用。 +DecodingLayerArray 则十分紧凑,并且主要用于解码层数量不多的情况 +(最多 ~10-15,但请自行进行基准测试), +而 DecodingLayerMap 则更加灵活,同时也是 DecodingLayerParser 的默认选择。 +请参阅 layers 子包中的测试和基准测试,以进一步查看使用示例和性能测量。 + +如果您想使用自己的内部数据包解码逻辑, +也可以选择实现自己的 DecodingLayerContainer。 + +创建数据包 + +除了提供解码数据包的能力,gopacket 还允许您从头开始创建数据包。 +许多 gopacket 层实现了 SerializableLayer 接口; +这些层可以按以下方式序列化为 []byte 数组: + + + ip := &layers.IPv4{ + SrcIP: net.IP{1, 2, 3, 4}, + DstIP: net.IP{5, 6, 7, 8}, + // 诸如此类... + } + buf := gopacket.NewSerializeBuffer() + opts := gopacket.SerializeOptions{} // 您可以从 SerializeOptions 中了解到具体细节. + err := ip.SerializeTo(buf, opts) + if err != nil { panic(err) } + fmt.Println(buf.Bytes()) // 输出一个包含序列化 IPv4 层的字节切片。 + +SerializeTO 将给定的层添加到 SerializeBuffer 的**首部**, +并将当前缓冲区的 Bytes() 切片视为当前序列化层的有效载荷。 +因此,您可以通过以相反的顺序序列化一组层(例如,Payload、TCP、IP、Ethernet) +来序列化整个数据包。 +SerializeBuffer 的 SerializeLayers 函数是一个可以做到这一点的辅助函数。 + +生成一个(空的且无用的,因为没有设置任何字段)以太网数据包, +例如,您可以运行: + + buf := gopacket.NewSerializeBuffer() + opts := gopacket.SerializeOptions{} + gopacket.SerializeLayers(buf, opts, + &layers.Ethernet{}, + &layers.IPv4{}, + &layers.TCP{}, + gopacket.Payload([]byte{1, 2, 3, 4})) + packetData := buf.Bytes() + +最后一点提醒 + +如果您使用 gopacket,您几乎肯定会希望确保导入了 gopacket/layers, +因为当导入时,它会设置所有的 LayerType 变量, +并填充了许多有趣的变量/映射(DecodersByLayerName 等)。 +因此,即使您不直接使用任何 layers 函数,也建议您使用以下导入: + + import ( + _ "github.com/tochusc/gopacket/layers" + ) + + TochusC AOSP Lab. 2024 - func main() { - var eth layers.Ethernet - var ip4 layers.IPv4 - var ip6 layers.IPv6 - var tcp layers.TCP - dlc := gopacket.DecodingLayerContainer(gopacket.DecodingLayerArray(nil)) - dlc = dlc.Put(ð) - dlc = dlc.Put(&ip4) - dlc = dlc.Put(&ip6) - dlc = dlc.Put(&tcp) - // you may specify some meaningful DecodeFeedback - decoder := dlc.LayersDecoder(LayerTypeEthernet, gopacket.NilDecodeFeedback) - decoded := make([]gopacket.LayerType, 0, 20) - for packetData := range somehowGetPacketData() { - lt, err := decoder(packetData, &decoded) - if err != nil { - fmt.Fprintf(os.Stderr, "Could not decode layers: %v\n", err) - continue - } - if lt != gopacket.LayerTypeZero { - fmt.Fprintf(os.Stderr, "unknown layer type: %v\n", lt) - continue - } - for _, layerType := range decoded { - // examine decoded layertypes just as already shown above - } - } - } - -DecodingLayerSparse is the fastest but most effective when LayerType values -that layers in use can decode are not large because otherwise that would lead -to bigger memory footprint. DecodingLayerArray is very compact and primarily -usable if the number of decoding layers is not big (up to ~10-15, but please do -your own benchmarks). DecodingLayerMap is the most versatile one and used by -DecodingLayerParser by default. Please refer to tests and benchmarks in layers -subpackage to further examine usage examples and performance measurements. - -You may also choose to implement your own DecodingLayerContainer if you want to -make use of your own internal packet decoding logic. - -Creating Packet Data - -As well as offering the ability to decode packet data, gopacket will allow you -to create packets from scratch, as well. A number of gopacket layers implement -the SerializableLayer interface; these layers can be serialized to a []byte in -the following manner: - - ip := &layers.IPv4{ - SrcIP: net.IP{1, 2, 3, 4}, - DstIP: net.IP{5, 6, 7, 8}, - // etc... - } - buf := gopacket.NewSerializeBuffer() - opts := gopacket.SerializeOptions{} // See SerializeOptions for more details. - err := ip.SerializeTo(buf, opts) - if err != nil { panic(err) } - fmt.Println(buf.Bytes()) // prints out a byte slice containing the serialized IPv4 layer. - -SerializeTo PREPENDS the given layer onto the SerializeBuffer, and they treat -the current buffer's Bytes() slice as the payload of the serializing layer. -Therefore, you can serialize an entire packet by serializing a set of layers in -reverse order (Payload, then TCP, then IP, then Ethernet, for example). The -SerializeBuffer's SerializeLayers function is a helper that does exactly that. - -To generate a (empty and useless, because no fields are set) -Ethernet(IPv4(TCP(Payload))) packet, for example, you can run: - - buf := gopacket.NewSerializeBuffer() - opts := gopacket.SerializeOptions{} - gopacket.SerializeLayers(buf, opts, - &layers.Ethernet{}, - &layers.IPv4{}, - &layers.TCP{}, - gopacket.Payload([]byte{1, 2, 3, 4})) - packetData := buf.Bytes() - -A Final Note - -If you use gopacket, you'll almost definitely want to make sure gopacket/layers -is imported, since when imported it sets all the LayerType variables and fills -in a lot of interesting variables/maps (DecodersByLayerName, etc). Therefore, -it's recommended that even if you don't use any layers functions directly, you still import with: - - import ( - _ "github.com/tochusc/gopacket/layers" - ) */ + package gopacket diff --git a/dumpcommand/tcpdump.go b/dumpcommand/tcpdump.go index 999ea2fed..ecdc149b9 100644 --- a/dumpcommand/tcpdump.go +++ b/dumpcommand/tcpdump.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/examples/afpacket/afpacket.go b/examples/afpacket/afpacket.go index a719ec9e9..5184d639f 100644 --- a/examples/afpacket/afpacket.go +++ b/examples/afpacket/afpacket.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2018 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/examples/arpscan/arpscan.go b/examples/arpscan/arpscan.go index 3380eded9..eea919a10 100644 --- a/examples/arpscan/arpscan.go +++ b/examples/arpscan/arpscan.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -6,9 +7,9 @@ // arpscan implements ARP scanning of all interfaces' local networks using // gopacket and its subpackages. This example shows, among other things: -// * Generating and sending packet data -// * Reading in packet data and interpreting it -// * Use of the 'pcap' subpackage for reading/writing +// - Generating and sending packet data +// - Reading in packet data and interpreting it +// - Use of the 'pcap' subpackage for reading/writing package main import ( diff --git a/examples/bidirectional/main.go b/examples/bidirectional/main.go index 55297555c..fafdbef5c 100644 --- a/examples/bidirectional/main.go +++ b/examples/bidirectional/main.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/examples/bytediff/main.go b/examples/bytediff/main.go index ef5ed94e9..4e94e7cb3 100644 --- a/examples/bytediff/main.go +++ b/examples/bytediff/main.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/examples/httpassembly/main.go b/examples/httpassembly/main.go index 7ba15636f..c50203386 100644 --- a/examples/httpassembly/main.go +++ b/examples/httpassembly/main.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/examples/pcapdump/main.go b/examples/pcapdump/main.go index f59a30d54..dd25a8327 100644 --- a/examples/pcapdump/main.go +++ b/examples/pcapdump/main.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/examples/pcaplay/main.go b/examples/pcaplay/main.go index 0bc1a2b86..0245cd265 100644 --- a/examples/pcaplay/main.go +++ b/examples/pcaplay/main.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/examples/pfdump/main.go b/examples/pfdump/main.go index cce562a97..426958118 100644 --- a/examples/pfdump/main.go +++ b/examples/pfdump/main.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/examples/reassemblydump/main.go b/examples/reassemblydump/main.go index 3ec04077e..db1594807 100644 --- a/examples/reassemblydump/main.go +++ b/examples/reassemblydump/main.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/examples/statsassembly/main.go b/examples/statsassembly/main.go index 2221149a7..1a96f1639 100644 --- a/examples/statsassembly/main.go +++ b/examples/statsassembly/main.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/examples/synscan/main.go b/examples/synscan/main.go index 0ad5993f7..34f81c05c 100644 --- a/examples/synscan/main.go +++ b/examples/synscan/main.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/examples/util/util.go b/examples/util/util.go index 0f698fb92..13a2e6730 100644 --- a/examples/util/util.go +++ b/examples/util/util.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -19,10 +20,10 @@ var cpuprofile = flag.String("cpuprofile", "", "Where to write CPU profile") // Run starts up stuff at the beginning of a main function, and returns a // function to defer until the function completes. It should be used like this: // -// func main() { -// defer util.Run()() -// ... stuff ... -// } +// func main() { +// defer util.Run()() +// ... stuff ... +// } func Run() func() { flag.Parse() if *cpuprofile != "" { diff --git a/flows.go b/flows.go index a00c88398..efd511e26 100644 --- a/flows.go +++ b/flows.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layerclass.go b/layerclass.go index 775cd0987..570e22c19 100644 --- a/layerclass.go +++ b/layerclass.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/arp.go b/layers/arp.go index 1f87fac96..50e6d3702 100644 --- a/layers/arp.go +++ b/layers/arp.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // diff --git a/layers/base.go b/layers/base.go index 822bef8be..903300b1c 100644 --- a/layers/base.go +++ b/layers/base.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/cdp.go b/layers/cdp.go index 2fb9ab25b..48609d436 100644 --- a/layers/cdp.go +++ b/layers/cdp.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/ctp.go b/layers/ctp.go index 7dfbfb0d6..77c988b9d 100644 --- a/layers/ctp.go +++ b/layers/ctp.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/dhcpv4.go b/layers/dhcpv4.go index cde577dcb..df3d2641a 100644 --- a/layers/dhcpv4.go +++ b/layers/dhcpv4.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2016 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -78,7 +79,7 @@ func (o DHCPMsgType) String() string { } } -//DHCPMagic is the RFC 2131 "magic cooke" for DHCP. +// DHCPMagic is the RFC 2131 "magic cooke" for DHCP. var DHCPMagic uint32 = 0x63825363 // DHCPv4 contains data for a single DHCP packet. diff --git a/layers/dhcpv6.go b/layers/dhcpv6.go index d77ec64c7..c19a84ccd 100644 --- a/layers/dhcpv6.go +++ b/layers/dhcpv6.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2018 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/dns.go b/layers/dns.go index f77e7d7ad..a91246922 100644 --- a/layers/dns.go +++ b/layers/dns.go @@ -1284,8 +1284,7 @@ func (dnskey DNSKEY) encode(data []byte, offset int) { binary.BigEndian.PutUint16(data[offset:], uint16(dnskey.Flags)) data[offset+2] = uint8(dnskey.Protocol) data[offset+3] = uint8(dnskey.Algorithm) - offset += 4 - copy(data[offset:], dnskey.PublicKey) + copy(data[offset+4:], dnskey.PublicKey) } // DNSKEYFlag common values diff --git a/layers/doc.go b/layers/doc.go index 8d123d9fb..0554a8ec0 100644 --- a/layers/doc.go +++ b/layers/doc.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/dot1q.go b/layers/dot1q.go index 80a6b07fe..69f9678eb 100644 --- a/layers/dot1q.go +++ b/layers/dot1q.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // diff --git a/layers/dot1q_test.go b/layers/dot1q_test.go index 564c09ffb..a5af09e37 100644 --- a/layers/dot1q_test.go +++ b/layers/dot1q_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/eap.go b/layers/eap.go index 4109e5cf4..4955b099a 100644 --- a/layers/eap.go +++ b/layers/eap.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/eapol.go b/layers/eapol.go index 1796b84b2..c53e6f2c1 100644 --- a/layers/eapol.go +++ b/layers/eapol.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/endpoints.go b/layers/endpoints.go index f7d7442d8..6ad0140e6 100644 --- a/layers/endpoints.go +++ b/layers/endpoints.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/enums.go b/layers/enums.go index e240af690..724e1ca5b 100644 --- a/layers/enums.go +++ b/layers/enums.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // diff --git a/layers/enums_generated.go b/layers/enums_generated.go index be6239294..19814eda8 100644 --- a/layers/enums_generated.go +++ b/layers/enums_generated.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. package layers diff --git a/layers/erspan2.go b/layers/erspan2.go index e8c3ee2d5..5f616bc5a 100644 --- a/layers/erspan2.go +++ b/layers/erspan2.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2018 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/erspan2_test.go b/layers/erspan2_test.go index f831da043..f89bbe807 100644 --- a/layers/erspan2_test.go +++ b/layers/erspan2_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2018 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/etherip.go b/layers/etherip.go index 1e8288bcd..3457763d2 100644 --- a/layers/etherip.go +++ b/layers/etherip.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/ethernet.go b/layers/ethernet.go index 46adf7066..51beaa19a 100644 --- a/layers/ethernet.go +++ b/layers/ethernet.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // diff --git a/layers/fddi.go b/layers/fddi.go index 4cdb0f941..01074a535 100644 --- a/layers/fddi.go +++ b/layers/fddi.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/gen.go b/layers/gen.go index ab7a0c001..5fa1c57ad 100644 --- a/layers/gen.go +++ b/layers/gen.go @@ -1,15 +1,17 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. +//go:build ignore // +build ignore // This binary pulls known ports from IANA, and uses them to populate // iana_ports.go's TCPPortNames and UDPPortNames maps. // -// go run gen.go | gofmt > iana_ports.go +// go run gen.go | gofmt > iana_ports.go package main import ( diff --git a/layers/gen2.go b/layers/gen2.go index 9543b1d57..e54868aea 100644 --- a/layers/gen2.go +++ b/layers/gen2.go @@ -1,14 +1,16 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. +//go:build ignore // +build ignore // This binary handles creating string constants and function templates for enums. // -// go run gen.go | gofmt > enums_generated.go +// go run gen.go | gofmt > enums_generated.go package main import ( diff --git a/layers/geneve.go b/layers/geneve.go index 46d10e59c..8158e810d 100644 --- a/layers/geneve.go +++ b/layers/geneve.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2016 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/geneve_test.go b/layers/geneve_test.go index 92ec2ce8f..0925baf5f 100644 --- a/layers/geneve_test.go +++ b/layers/geneve_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2016 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/gre.go b/layers/gre.go index 0219e32b4..2354ee12c 100644 --- a/layers/gre.go +++ b/layers/gre.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/gre_test.go b/layers/gre_test.go index f82810876..76826f37d 100644 --- a/layers/gre_test.go +++ b/layers/gre_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -15,15 +16,16 @@ import ( ) // testPacketGRE is the packet: -// 15:08:08.003196 IP 192.168.1.1 > 192.168.1.2: GREv0, length 88: IP 172.16.1.1 > 172.16.2.1: ICMP echo request, id 4724, seq 1, length 64 -// 0x0000: 3a56 6b69 595e 8e7a 12c3 a971 0800 4500 :VkiY^.z...q..E. -// 0x0010: 006c 843c 4000 402f 32d3 c0a8 0101 c0a8 .l.<@.@/2....... -// 0x0020: 0102 0000 0800 4500 0054 0488 4000 4001 ......E..T..@.@. -// 0x0030: dafe ac10 0101 ac10 0201 0800 82c4 1274 ...............t -// 0x0040: 0001 c892 a354 0000 0000 380c 0000 0000 .....T....8..... -// 0x0050: 0000 1011 1213 1415 1617 1819 1a1b 1c1d ................ -// 0x0060: 1e1f 2021 2223 2425 2627 2829 2a2b 2c2d ...!"#$%&'()*+,- -// 0x0070: 2e2f 3031 3233 3435 3637 ./01234567 +// +// 15:08:08.003196 IP 192.168.1.1 > 192.168.1.2: GREv0, length 88: IP 172.16.1.1 > 172.16.2.1: ICMP echo request, id 4724, seq 1, length 64 +// 0x0000: 3a56 6b69 595e 8e7a 12c3 a971 0800 4500 :VkiY^.z...q..E. +// 0x0010: 006c 843c 4000 402f 32d3 c0a8 0101 c0a8 .l.<@.@/2....... +// 0x0020: 0102 0000 0800 4500 0054 0488 4000 4001 ......E..T..@.@. +// 0x0030: dafe ac10 0101 ac10 0201 0800 82c4 1274 ...............t +// 0x0040: 0001 c892 a354 0000 0000 380c 0000 0000 .....T....8..... +// 0x0050: 0000 1011 1213 1415 1617 1819 1a1b 1c1d ................ +// 0x0060: 1e1f 2021 2223 2425 2627 2829 2a2b 2c2d ...!"#$%&'()*+,- +// 0x0070: 2e2f 3031 3233 3435 3637 ./01234567 var testPacketGRE = []byte{ 0x3a, 0x56, 0x6b, 0x69, 0x59, 0x5e, 0x8e, 0x7a, 0x12, 0xc3, 0xa9, 0x71, 0x08, 0x00, 0x45, 0x00, 0x00, 0x6c, 0x84, 0x3c, 0x40, 0x00, 0x40, 0x2f, 0x32, 0xd3, 0xc0, 0xa8, 0x01, 0x01, 0xc0, 0xa8, @@ -132,16 +134,17 @@ func BenchmarkEncodePacketGRE(b *testing.B) { } // testPacketEthernetOverGRE is the packet: -// 11:01:38.124768 IP 192.168.1.1 > 192.168.1.2: GREv0, length 102: IP 172.16.1.1 > 172.16.1.2: ICMP echo request, id 3842, seq 1, length 64 -// 0x0000: ea6b 4cd3 5513 d6b9 d880 56ef 0800 4500 .kL.U.....V...E. -// 0x0010: 007a 0acd 4000 402f ac34 c0a8 0101 c0a8 .z..@.@/.4...... -// 0x0020: 0102 0000 6558 aa6a 36e6 c630 6e32 3ec7 ....eX.j6..0n2>. -// 0x0030: 9def 0800 4500 0054 d970 4000 4001 0715 ....E..T.p@.@... -// 0x0040: ac10 0101 ac10 0102 0800 3f15 0f02 0001 ..........?..... -// 0x0050: 82d9 b154 0000 0000 b5e6 0100 0000 0000 ...T............ -// 0x0060: 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f ................ -// 0x0070: 2021 2223 2425 2627 2829 2a2b 2c2d 2e2f .!"#$%&'()*+,-./ -// 0x0080: 3031 3233 3435 3637 01234567 +// +// 11:01:38.124768 IP 192.168.1.1 > 192.168.1.2: GREv0, length 102: IP 172.16.1.1 > 172.16.1.2: ICMP echo request, id 3842, seq 1, length 64 +// 0x0000: ea6b 4cd3 5513 d6b9 d880 56ef 0800 4500 .kL.U.....V...E. +// 0x0010: 007a 0acd 4000 402f ac34 c0a8 0101 c0a8 .z..@.@/.4...... +// 0x0020: 0102 0000 6558 aa6a 36e6 c630 6e32 3ec7 ....eX.j6..0n2>. +// 0x0030: 9def 0800 4500 0054 d970 4000 4001 0715 ....E..T.p@.@... +// 0x0040: ac10 0101 ac10 0102 0800 3f15 0f02 0001 ..........?..... +// 0x0050: 82d9 b154 0000 0000 b5e6 0100 0000 0000 ...T............ +// 0x0060: 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f ................ +// 0x0070: 2021 2223 2425 2627 2829 2a2b 2c2d 2e2f .!"#$%&'()*+,-./ +// 0x0080: 3031 3233 3435 3637 01234567 var testPacketEthernetOverGRE = []byte{ 0xea, 0x6b, 0x4c, 0xd3, 0x55, 0x13, 0xd6, 0xb9, 0xd8, 0x80, 0x56, 0xef, 0x08, 0x00, 0x45, 0x00, 0x00, 0x7a, 0x0a, 0xcd, 0x40, 0x00, 0x40, 0x2f, 0xac, 0x34, 0xc0, 0xa8, 0x01, 0x01, 0xc0, 0xa8, diff --git a/layers/iana_ports.go b/layers/iana_ports.go index ddcf3ecdb..6bd226e8d 100644 --- a/layers/iana_ports.go +++ b/layers/iana_ports.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. package layers diff --git a/layers/icmp4.go b/layers/icmp4.go index 1ffae1a39..512692bc6 100644 --- a/layers/icmp4.go +++ b/layers/icmp4.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // diff --git a/layers/icmp6.go b/layers/icmp6.go index c2cc5834e..2a9fdb102 100644 --- a/layers/icmp6.go +++ b/layers/icmp6.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // diff --git a/layers/icmp6msg.go b/layers/icmp6msg.go index 272102b89..1b4b713af 100644 --- a/layers/icmp6msg.go +++ b/layers/icmp6msg.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // diff --git a/layers/igmp.go b/layers/igmp.go index ef38a9670..51369b85f 100644 --- a/layers/igmp.go +++ b/layers/igmp.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // @@ -93,8 +94,9 @@ type IGMP struct { // IGMPv1or2 stores header details for an IGMPv1 or IGMPv2 packet. // -// 0 1 2 3 -// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +// 0 1 2 3 +// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +// // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Type | Max Resp Time | Checksum | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -204,8 +206,9 @@ func (i *IGMP) decodeIGMPv3MembershipReport(data []byte) error { return nil } -// 0 1 2 3 -// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +// 0 1 2 3 +// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +// // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | Type = 0x11 | Max Resp Code | Checksum | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ diff --git a/layers/ip4.go b/layers/ip4.go index c15efdfd2..bcd3bdf30 100644 --- a/layers/ip4.go +++ b/layers/ip4.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // diff --git a/layers/ip4_test.go b/layers/ip4_test.go index dc9e7f8ff..f78f8e7db 100644 --- a/layers/ip4_test.go +++ b/layers/ip4_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/ip6.go b/layers/ip6.go index c0a767e7f..f7e4b76f8 100644 --- a/layers/ip6.go +++ b/layers/ip6.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // diff --git a/layers/ipsec.go b/layers/ipsec.go index 239b338c0..6da2104e6 100644 --- a/layers/ipsec.go +++ b/layers/ipsec.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/layertypes.go b/layers/layertypes.go index 8fb68fa4f..0033f994e 100644 --- a/layers/layertypes.go +++ b/layers/layertypes.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/lcm.go b/layers/lcm.go index 1563d388a..d20500860 100644 --- a/layers/lcm.go +++ b/layers/lcm.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2018 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -29,8 +30,9 @@ const ( // variety of programming languages. // // References -// https://lcm-proj.github.io/ -// https://github.com/lcm-proj/lcm +// +// https://lcm-proj.github.io/ +// https://github.com/lcm-proj/lcm type LCM struct { // Common (short & fragmented header) fields Magic uint32 diff --git a/layers/lcm_test.go b/layers/lcm_test.go index effac42ac..76d76d720 100644 --- a/layers/lcm_test.go +++ b/layers/lcm_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2018 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/linux_sll.go b/layers/linux_sll.go index e89ee2a24..dfc3adc53 100644 --- a/layers/linux_sll.go +++ b/layers/linux_sll.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/llc.go b/layers/llc.go index c61899d71..66c91e923 100644 --- a/layers/llc.go +++ b/layers/llc.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -71,9 +72,10 @@ func (l *LLC) NextLayerType() gopacket.LayerType { // SNAP is used inside LLC. See // http://standards.ieee.org/getieee802/download/802-2001.pdf. // From http://en.wikipedia.org/wiki/Subnetwork_Access_Protocol: -// "[T]he Subnetwork Access Protocol (SNAP) is a mechanism for multiplexing, -// on networks using IEEE 802.2 LLC, more protocols than can be distinguished -// by the 8-bit 802.2 Service Access Point (SAP) fields." +// +// "[T]he Subnetwork Access Protocol (SNAP) is a mechanism for multiplexing, +// on networks using IEEE 802.2 LLC, more protocols than can be distinguished +// by the 8-bit 802.2 Service Access Point (SAP) fields." type SNAP struct { BaseLayer OrganizationalCode []byte diff --git a/layers/lldp.go b/layers/lldp.go index 0f07384ce..4090cfe21 100644 --- a/layers/lldp.go +++ b/layers/lldp.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -240,7 +241,7 @@ type LinkLayerDiscoveryInfo struct { Unknown []LinkLayerDiscoveryValue // undecoded TLVs } -/// IEEE 802.1 TLV Subtypes +// / IEEE 802.1 TLV Subtypes const ( LLDP8021SubtypePortVLANID uint8 = 1 LLDP8021SubtypeProtocolVLANID uint8 = 2 diff --git a/layers/loopback.go b/layers/loopback.go index 949d0ecf4..e1d1d4a24 100644 --- a/layers/loopback.go +++ b/layers/loopback.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/mpls.go b/layers/mpls.go index fe0c3da9c..05ea05818 100644 --- a/layers/mpls.go +++ b/layers/mpls.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -26,9 +27,11 @@ func (m *MPLS) LayerType() gopacket.LayerType { return LayerTypeMPLS } // ProtocolGuessingDecoder attempts to guess the protocol of the bytes it's // given, then decode the packet accordingly. Its algorithm for guessing is: -// If the packet starts with byte 0x45-0x4F: IPv4 -// If the packet starts with byte 0x60-0x6F: IPv6 -// Otherwise: Error +// +// If the packet starts with byte 0x45-0x4F: IPv4 +// If the packet starts with byte 0x60-0x6F: IPv6 +// Otherwise: Error +// // See draft-hsmit-isis-aal5mux-00.txt for more detail on this approach. type ProtocolGuessingDecoder struct{} diff --git a/layers/mpls_test.go b/layers/mpls_test.go index 6d78344d3..c0b014f0b 100644 --- a/layers/mpls_test.go +++ b/layers/mpls_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2016 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/ndp.go b/layers/ndp.go index 6f918cd3c..65ea25c49 100644 --- a/layers/ndp.go +++ b/layers/ndp.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/ntp.go b/layers/ntp.go index 59f4d6372..d97728651 100644 --- a/layers/ntp.go +++ b/layers/ntp.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2016 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -160,56 +161,55 @@ import ( // The current version of NTP (NTP V4)'s RFC (V4 - RFC 5905) contains // the following diagram for the NTP record format: -// 0 1 2 3 -// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// |LI | VN |Mode | Stratum | Poll | Precision | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | Root Delay | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | Root Dispersion | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | Reference ID | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | | -// + Reference Timestamp (64) + -// | | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | | -// + Origin Timestamp (64) + -// | | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | | -// + Receive Timestamp (64) + -// | | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | | -// + Transmit Timestamp (64) + -// | | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | | -// . . -// . Extension Field 1 (variable) . -// . . -// | | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | | -// . . -// . Extension Field 2 (variable) . -// . . -// | | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | Key Identifier | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | | -// | dgst (128) | -// | | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// From http://www.ietf.org/rfc/rfc5905.txt +// 0 1 2 3 +// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// |LI | VN |Mode | Stratum | Poll | Precision | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | Root Delay | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | Root Dispersion | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | Reference ID | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | | +// + Reference Timestamp (64) + +// | | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | | +// + Origin Timestamp (64) + +// | | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | | +// + Receive Timestamp (64) + +// | | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | | +// + Transmit Timestamp (64) + +// | | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | | +// . . +// . Extension Field 1 (variable) . +// . . +// | | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | | +// . . +// . Extension Field 2 (variable) . +// . . +// | | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | Key Identifier | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | | +// | dgst (128) | +// | | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// From http://www.ietf.org/rfc/rfc5905.txt // // The fields "Extension Field 1 (variable)" and later are optional fields, // and so we can set a minimum NTP record size of 48 bytes. -// const ntpMinimumRecordSizeInBytes int = 48 //****************************************************************************** diff --git a/layers/ntp_test.go b/layers/ntp_test.go index 46212c8ea..918b65d51 100644 --- a/layers/ntp_test.go +++ b/layers/ntp_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2016 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -10,10 +11,11 @@ package layers import ( "crypto/rand" - "github.com/tochusc/gopacket" "io" "reflect" "testing" + + "github.com/tochusc/gopacket" ) //****************************************************************************** diff --git a/layers/pflog.go b/layers/pflog.go index cce2e86f2..46152a546 100644 --- a/layers/pflog.go +++ b/layers/pflog.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/ports.go b/layers/ports.go index e0d2a3e8e..1d74ead36 100644 --- a/layers/ports.go +++ b/layers/ports.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/ppp.go b/layers/ppp.go index 8c0611cf4..1b98887b7 100644 --- a/layers/ppp.go +++ b/layers/ppp.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/pppoe.go b/layers/pppoe.go index 3bde601c9..94235a0ed 100644 --- a/layers/pppoe.go +++ b/layers/pppoe.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/radiotap_test.go b/layers/radiotap_test.go index fab98e4ae..648679c51 100644 --- a/layers/radiotap_test.go +++ b/layers/radiotap_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -11,9 +12,10 @@ import ( ) // testPacketRadiotap0 is the packet: -// 09:34:34.799438 1.0 Mb/s 2412 MHz 11b -58dB signal antenna 7 Acknowledgment RA:88:1f:a1:ae:9d:cb -// 0x0000: 0000 1200 2e48 0000 1002 6c09 a000 c607 .....H....l..... -// 0x0010: 0000 d400 0000 881f a1ae 9dcb c630 4b4b .............0KK +// +// 09:34:34.799438 1.0 Mb/s 2412 MHz 11b -58dB signal antenna 7 Acknowledgment RA:88:1f:a1:ae:9d:cb +// 0x0000: 0000 1200 2e48 0000 1002 6c09 a000 c607 .....H....l..... +// 0x0010: 0000 d400 0000 881f a1ae 9dcb c630 4b4b .............0KK var testPacketRadiotap0 = []byte{ 0x00, 0x00, 0x12, 0x00, 0x2e, 0x48, 0x00, 0x00, 0x10, 0x02, 0x6c, 0x09, 0xa0, 0x00, 0xc6, 0x07, 0x00, 0x00, 0xd4, 0x00, 0x00, 0x00, 0x88, 0x1f, 0xa1, 0xae, 0x9d, 0xcb, 0xc6, 0x30, 0x4b, 0x4b, @@ -40,11 +42,12 @@ func BenchmarkDecodePacketRadiotap0(b *testing.B) { } // testPacketRadiotap1 is the packet: -// 05:24:21.380948 2412 MHz 11g -36dB signal antenna 5 65.0 Mb/s MCS 7 20 MHz lon GI -// 0x0000: 0000 1500 2a48 0800 1000 6c09 8004 dc05 ....*H....l..... -// 0x0010: 0000 0700 0748 112c 0000 3a9d aaf0 191c .....H.,..:..... -// 0x0020: aba7 f213 9d00 3a9d aaf0 1970 b2ee a9f1 ......:....p.... -// 0x0030: 16 . +// +// 05:24:21.380948 2412 MHz 11g -36dB signal antenna 5 65.0 Mb/s MCS 7 20 MHz lon GI +// 0x0000: 0000 1500 2a48 0800 1000 6c09 8004 dc05 ....*H....l..... +// 0x0010: 0000 0700 0748 112c 0000 3a9d aaf0 191c .....H.,..:..... +// 0x0020: aba7 f213 9d00 3a9d aaf0 1970 b2ee a9f1 ......:....p.... +// 0x0030: 16 . var testPacketRadiotap1 = []byte{ 0x00, 0x00, 0x15, 0x00, 0x2a, 0x48, 0x08, 0x00, 0x10, 0x00, 0x6c, 0x09, 0x80, 0x04, 0xdc, 0x05, 0x00, 0x00, 0x07, 0x00, 0x07, 0x48, 0x11, 0x2c, 0x00, 0x00, 0x3a, 0x9d, 0xaa, 0xf0, 0x19, 0x1c, diff --git a/layers/rudp.go b/layers/rudp.go index aa2f48c72..6792b47bb 100644 --- a/layers/rudp.go +++ b/layers/rudp.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/sctp.go b/layers/sctp.go index 256728684..5af480b72 100644 --- a/layers/sctp.go +++ b/layers/sctp.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/stp_test.go b/layers/stp_test.go index 9970fc2ad..3e2d3506c 100644 --- a/layers/stp_test.go +++ b/layers/stp_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2021 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/tcp.go b/layers/tcp.go index 0ae0fcedc..66464eb25 100644 --- a/layers/tcp.go +++ b/layers/tcp.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // diff --git a/layers/tcpip.go b/layers/tcpip.go index dd18e0b8f..826145d10 100644 --- a/layers/tcpip.go +++ b/layers/tcpip.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // diff --git a/layers/udp.go b/layers/udp.go index 5d7419297..e706cc3f9 100644 --- a/layers/udp.go +++ b/layers/udp.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // diff --git a/layers/udplite.go b/layers/udplite.go index 3700334ca..1f312ef37 100644 --- a/layers/udplite.go +++ b/layers/udplite.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // diff --git a/layers/vrrp.go b/layers/vrrp.go index f09209c35..cc80c1d30 100644 --- a/layers/vrrp.go +++ b/layers/vrrp.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2016 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/vrrp_test.go b/layers/vrrp_test.go index 6a16f4ce6..801bd8a59 100644 --- a/layers/vrrp_test.go +++ b/layers/vrrp_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2016 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -6,16 +7,18 @@ package layers import ( - "github.com/tochusc/gopacket" "testing" + + "github.com/tochusc/gopacket" ) // vrrpPacketPriority100 is the packet: -// 06:12:21.813317 IP 192.168.0.30 > 224.0.0.18: VRRPv2, Advertisement, vrid 1, prio 100, authtype none, intvl 1s, length 20 -// 0x0000: 0100 5e00 0012 0000 5e00 0101 0800 45c0 ..^.....^.....E. -// 0x0010: 0028 0000 0000 ff70 19cd c0a8 001e e000 .(.....p........ -// 0x0020: 0012 2101 6401 0001 ba52 c0a8 0001 0000 ..!.d....R...... -// 0x0030: 0000 0000 0000 0000 0000 0000 ............ +// +// 06:12:21.813317 IP 192.168.0.30 > 224.0.0.18: VRRPv2, Advertisement, vrid 1, prio 100, authtype none, intvl 1s, length 20 +// 0x0000: 0100 5e00 0012 0000 5e00 0101 0800 45c0 ..^.....^.....E. +// 0x0010: 0028 0000 0000 ff70 19cd c0a8 001e e000 .(.....p........ +// 0x0020: 0012 2101 6401 0001 ba52 c0a8 0001 0000 ..!.d....R...... +// 0x0030: 0000 0000 0000 0000 0000 0000 ............ var vrrpPacketPriority100 = []byte{ 0x01, 0x00, 0x5e, 0x00, 0x00, 0x12, 0x00, 0x00, 0x5e, 0x00, 0x01, 0x01, 0x08, 0x00, 0x45, 0xc0, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0xff, 0x70, 0x19, 0xcd, 0xc0, 0xa8, 0x00, 0x1e, 0xe0, 0x00, diff --git a/layers/vxlan.go b/layers/vxlan.go index ba67f7fbb..094b2cb9a 100644 --- a/layers/vxlan.go +++ b/layers/vxlan.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2016 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/layers/vxlan_test.go b/layers/vxlan_test.go index cafac3eb5..4fa2a2633 100644 --- a/layers/vxlan_test.go +++ b/layers/vxlan_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2016 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -7,9 +8,10 @@ package layers import ( - "github.com/tochusc/gopacket" "reflect" "testing" + + "github.com/tochusc/gopacket" ) // VXLAN is specifed in RFC 7348 diff --git a/layertype.go b/layertype.go index 3abfee1e9..05632def9 100644 --- a/layertype.go +++ b/layertype.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/macs/benchmark_test.go b/macs/benchmark_test.go index 33af5c263..15e917213 100644 --- a/macs/benchmark_test.go +++ b/macs/benchmark_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/macs/doc.go b/macs/doc.go index c0d32a8c0..7bb9a2f47 100644 --- a/macs/doc.go +++ b/macs/doc.go @@ -1,12 +1,12 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. -// Package macs provides an in-memory mapping of all valid Ethernet MAC address -// prefixes to their associated organization. +// macs 包提供了所有有效以太网 MAC 地址前缀到其关联组织的内存映射。 // -// The ValidMACPrefixMap map maps 3-byte prefixes to organization strings. It -// can be updated using 'go run gen.go' in this directory. +// ValidMACPrefixMap 映射了 3 字节前缀到组织字符串的映射。 +// 并且可以使用 'go run gen.go' 来更新。 package macs diff --git a/macs/gen.go b/macs/gen.go index 1fb685fac..d60cda874 100644 --- a/macs/gen.go +++ b/macs/gen.go @@ -1,16 +1,18 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. +//go:build ignore // +build ignore // This binary pulls the list of known MAC // prefixes from IEEE and writes them out to a go file which is compiled // into gopacket. It should be run as follows: // -// go run gen.go | gofmt > valid_mac_prefixes.go +// go run gen.go | gofmt > valid_mac_prefixes.go package main import ( diff --git a/macs/valid_mac_prefixes.go b/macs/valid_mac_prefixes.go index 3d60e489e..b0159e173 100644 --- a/macs/valid_mac_prefixes.go +++ b/macs/valid_mac_prefixes.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/packet.go b/packet.go index 3a7c4b3d8..cc3a6c3bc 100644 --- a/packet.go +++ b/packet.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -205,9 +206,10 @@ func (p *packet) recoverDecodeError() { // in a single line, with no trailing newline. This function is specifically // designed to do the right thing for most layers... it follows the following // rules: -// * If the Layer has a String function, just output that. -// * Otherwise, output all exported fields in the layer, recursing into -// exported slices and structs. +// - If the Layer has a String function, just output that. +// - Otherwise, output all exported fields in the layer, recursing into +// exported slices and structs. +// // NOTE: This is NOT THE SAME AS fmt's "%#v". %#v will output both exported // and unexported fields... many times packet layers contain unexported stuff // that would just mess up the output of the layer, see for example the @@ -247,11 +249,12 @@ func LayerDump(l Layer) string { // LayerString for more details. // // Params: -// i - value to write out -// anonymous: if we're currently recursing an anonymous member of a struct -// writeSpace: if we've already written a value in a struct, and need to -// write a space before writing more. This happens when we write various -// anonymous values, and need to keep writing more. +// +// i - value to write out +// anonymous: if we're currently recursing an anonymous member of a struct +// writeSpace: if we've already written a value in a struct, and need to +// write a space before writing more. This happens when we write various +// anonymous values, and need to keep writing more. func layerString(v reflect.Value, anonymous bool, writeSpace bool) string { // Let String() functions take precedence. if v.CanInterface() { @@ -748,18 +751,19 @@ type ZeroCopyPacketDataSource interface { // There are currently two different methods for reading packets in through // a PacketSource: // -// Reading With Packets Function +// # Reading With Packets Function // // This method is the most convenient and easiest to code, but lacks // flexibility. Packets returns a 'chan Packet', then asynchronously writes // packets into that channel. Packets uses a blocking channel, and closes // it if an io.EOF is returned by the underlying PacketDataSource. All other // PacketDataSource errors are ignored and discarded. -// for packet := range packetSource.Packets() { -// ... -// } // -// Reading With NextPacket Function +// for packet := range packetSource.Packets() { +// ... +// } +// +// # Reading With NextPacket Function // // This method is the most flexible, and exposes errors that may be // encountered by the underlying PacketDataSource. It's also the fastest @@ -767,16 +771,17 @@ type ZeroCopyPacketDataSource interface { // read/write. However, it requires the user to handle errors, most // importantly the io.EOF error in cases where packets are being read from // a file. -// for { -// packet, err := packetSource.NextPacket() -// if err == io.EOF { -// break -// } else if err != nil { -// log.Println("Error:", err) -// continue -// } -// handlePacket(packet) // Do something with each packet. -// } +// +// for { +// packet, err := packetSource.NextPacket() +// if err == io.EOF { +// break +// } else if err != nil { +// log.Println("Error:", err) +// continue +// } +// handlePacket(packet) // Do something with each packet. +// } type PacketSource struct { source PacketDataSource decoder Decoder @@ -850,9 +855,9 @@ func (p *PacketSource) packetsToChannel() { // PacketDataSource returns an io.EOF error, the channel will be closed. // If any other error is encountered, it is ignored. // -// for packet := range packetSource.Packets() { -// handlePacket(packet) // Do something with each packet. -// } +// for packet := range packetSource.Packets() { +// handlePacket(packet) // Do something with each packet. +// } // // If called more than once, returns the same channel. func (p *PacketSource) Packets() chan Packet { diff --git a/packet_test.go b/packet_test.go index bd0544888..adc16abd0 100644 --- a/packet_test.go +++ b/packet_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/parser.go b/parser.go index 4a4676f1c..432e79a15 100644 --- a/parser.go +++ b/parser.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -255,47 +256,48 @@ func (l *DecodingLayerParser) SetDecodingLayerContainer(dlc DecodingLayerContain // instead it overwrites the layers that already exist. // // Example usage: -// func main() { -// var eth layers.Ethernet -// var ip4 layers.IPv4 -// var ip6 layers.IPv6 -// var tcp layers.TCP -// var udp layers.UDP -// var payload gopacket.Payload -// parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, ð, &ip4, &ip6, &tcp, &udp, &payload) -// var source gopacket.PacketDataSource = getMyDataSource() -// decodedLayers := make([]gopacket.LayerType, 0, 10) -// for { -// data, _, err := source.ReadPacketData() -// if err != nil { -// fmt.Println("Error reading packet data: ", err) -// continue -// } -// fmt.Println("Decoding packet") -// err = parser.DecodeLayers(data, &decodedLayers) -// for _, typ := range decodedLayers { -// fmt.Println(" Successfully decoded layer type", typ) -// switch typ { -// case layers.LayerTypeEthernet: -// fmt.Println(" Eth ", eth.SrcMAC, eth.DstMAC) -// case layers.LayerTypeIPv4: -// fmt.Println(" IP4 ", ip4.SrcIP, ip4.DstIP) -// case layers.LayerTypeIPv6: -// fmt.Println(" IP6 ", ip6.SrcIP, ip6.DstIP) -// case layers.LayerTypeTCP: -// fmt.Println(" TCP ", tcp.SrcPort, tcp.DstPort) -// case layers.LayerTypeUDP: -// fmt.Println(" UDP ", udp.SrcPort, udp.DstPort) -// } -// } -// if decodedLayers.Truncated { -// fmt.Println(" Packet has been truncated") -// } -// if err != nil { -// fmt.Println(" Error encountered:", err) -// } -// } -// } +// +// func main() { +// var eth layers.Ethernet +// var ip4 layers.IPv4 +// var ip6 layers.IPv6 +// var tcp layers.TCP +// var udp layers.UDP +// var payload gopacket.Payload +// parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, ð, &ip4, &ip6, &tcp, &udp, &payload) +// var source gopacket.PacketDataSource = getMyDataSource() +// decodedLayers := make([]gopacket.LayerType, 0, 10) +// for { +// data, _, err := source.ReadPacketData() +// if err != nil { +// fmt.Println("Error reading packet data: ", err) +// continue +// } +// fmt.Println("Decoding packet") +// err = parser.DecodeLayers(data, &decodedLayers) +// for _, typ := range decodedLayers { +// fmt.Println(" Successfully decoded layer type", typ) +// switch typ { +// case layers.LayerTypeEthernet: +// fmt.Println(" Eth ", eth.SrcMAC, eth.DstMAC) +// case layers.LayerTypeIPv4: +// fmt.Println(" IP4 ", ip4.SrcIP, ip4.DstIP) +// case layers.LayerTypeIPv6: +// fmt.Println(" IP6 ", ip6.SrcIP, ip6.DstIP) +// case layers.LayerTypeTCP: +// fmt.Println(" TCP ", tcp.SrcPort, tcp.DstPort) +// case layers.LayerTypeUDP: +// fmt.Println(" UDP ", udp.SrcPort, udp.DstPort) +// } +// } +// if decodedLayers.Truncated { +// fmt.Println(" Packet has been truncated") +// } +// if err != nil { +// fmt.Println(" Error encountered:", err) +// } +// } +// } // // If DecodeLayers is unable to decode the next layer type, it will return the // error UnsupportedLayerType. diff --git a/pcap/doc.go b/pcap/doc.go index 7ab03b0b7..892bf6c6b 100644 --- a/pcap/doc.go +++ b/pcap/doc.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -5,108 +6,113 @@ // tree. /* -Package pcap allows users of gopacket to read packets off the wire or from -pcap files. +pcap 允许 gopacket 的使用者从网络或者 pcap 文件中读取数据包。 -This package is meant to be used with its parent, -http://github.com/tochusc/gopacket, although it can also be used independently -if you just want to get packet data from the wire. +pcap 包是 gopacket 的子包,http://github.com/tochusc/gopacket, +虽然它也可以独立使用,如果你仅仅只是想从网络中获取数据包的话。 Depending on libpcap version, os support, or file timestamp resolution, nanosecond resolution is used for the internal timestamps. Returned timestamps are always scaled to nanosecond resolution due to the usage of time.Time. libpcap must be at least version 1.5 to support nanosecond timestamps. OpenLive supports only microsecond resolution. - -Reading PCAP Files - -The following code can be used to read in data from a pcap file. - - if handle, err := pcap.OpenOffline("/path/to/my/file"); err != nil { - panic(err) - } else { - packetSource := gopacket.NewPacketSource(handle, handle.LinkType()) - for packet := range packetSource.Packets() { - handlePacket(packet) // Do something with a packet here. - } - } - -Reading Live Packets - -The following code can be used to read in data from a live device, in this case -"eth0". Be aware, that OpenLive only supports microsecond resolution. - - if handle, err := pcap.OpenLive("eth0", 1600, true, pcap.BlockForever); err != nil { - panic(err) - } else if err := handle.SetBPFFilter("tcp and port 80"); err != nil { // optional - panic(err) - } else { - packetSource := gopacket.NewPacketSource(handle, handle.LinkType()) - for packet := range packetSource.Packets() { - handlePacket(packet) // Do something with a packet here. - } - } - -Inactive Handles - -Newer PCAP functionality requires the concept of an 'inactive' PCAP handle. -Instead of constantly adding new arguments to pcap_open_live, users now call -pcap_create to create a handle, set it up with a bunch of optional function -calls, then call pcap_activate to activate it. This library mirrors that -mechanism, for those that want to expose/use these new features: - - inactive, err := pcap.NewInactiveHandle(deviceName) - if err != nil { - log.Fatal(err) - } - defer inactive.CleanUp() - - // Call various functions on inactive to set it up the way you'd like: - if err = inactive.SetTimeout(time.Minute); err != nil { - log.Fatal(err) - } else if err = inactive.SetTimestampSource("foo"); err != nil { - log.Fatal(err) - } - - // Finally, create the actual handle by calling Activate: - handle, err := inactive.Activate() // after this, inactive is no longer valid - if err != nil { - log.Fatal(err) - } - defer handle.Close() - - // Now use your handle as you see fit. - -PCAP Timeouts +依赖于 libpcap 的版本,操作系统的支持,或文件时间戳的分辨率的不同, +pcap 内部时间戳使用的是纳秒分辨率。 +因为使用了 time.Time,pcap 返回的时间戳总是缩放到纳秒分辨率。 +libpcap 必须至少是 1.5 版本才支持纳秒时间戳,而OpenLive 则仅支持微秒分辨率。 + +读取 PCAP 文件 + +以下代码可以用来从一个 pcap 文件中读取数据包。 + + if handle, err := pcap.OpenOffline("/path/to/my/file"); err != nil { + panic(err) + } else { + packetSource := gopacket.NewPacketSource(handle, handle.LinkType()) + for packet := range packetSource.Packets() { + handlePacket(packet) // 使用数据包做些什么事情之类的 + } + } + +读取网络数据包 + +以下代码可以用来从一个网络设备中读取数据包,比如 "eth0"。 +注意,OpenLive 仅支持微秒分辨率。 + + if handle, err := pcap.OpenLive("eth0", 1600, true, pcap.BlockForever); err != nil { + panic(err) + } else if err := handle.SetBPFFilter("tcp and port 80"); err != nil { // optional + panic(err) + } else { + packetSource := gopacket.NewPacketSource(handle, handle.LinkType()) + for packet := range packetSource.Packets() { + handlePacket(packet) // 使用数据包做些什么事情之类的 + } + } + +未激活句柄 + +较新版本的 PCAP 中引入了“未激活”PCAP句柄的概念。 +现在,用户不再需要不断地向 pcap_open_live 添加新的参数,而是调用 pcap_create 来创建一个句柄, +然后使用一堆可选的函数调用来设置它,再调用 pcap_activate 来激活它。 +该库也引入了这种机制,来为那些想要体验/使用这些新功能的人提供支持: + + inactive, err := pcap.NewInactiveHandle(deviceName) + if err != nil { + log.Fatal(err) + } + defer inactive.CleanUp() + + // 调用 inactive 上的各种函数来设置句柄 + if err = inactive.SetTimeout(time.Minute); err != nil { + log.Fatal(err) + } else if err = inactive.SetTimestampSource("foo"); err != nil { + log.Fatal(err) + } + + // 最后,通过调用 Activate 来创建实际的句柄: + handle, err := inactive.Activate() // after this, inactive is no longer valid + if err != nil { + log.Fatal(err) + } + defer handle.Close() + + // Now use your handle as you see fit. + +# PCAP 超时 pcap.OpenLive and pcap.SetTimeout both take timeouts. If you don't care about timeouts, just pass in BlockForever, which should do what you expect with minimal fuss. +pcap.OpenLive 以及 pcap.SetTimeout 都接受超时参数。 +如果你不关心超时时间,只需传入 BlockForever, +不用麻烦,这样一般会按照你的预期来运作。 + +将超时时间设置为 0 不是推荐行为。一些平台,比如 Macs, +(http://www.manpages.info/macosx/pcap.3.html) 写到: + + 读取超时时间(Read Timeout)的作用是,当一个数据包被接收时, + 不一定立即返回,而是等待一段时间,来允许更多的数据包到达, + 并且一次从操作系统内核中读取多个数据包。 + +这意味着如果你只捕获一个数据包,内核可能会决定等待“超时“时间, +以便更多的数据包与之一起返回。因此,超时时间为 0 意味着“永远等待更多的数据包”, +这样...很不好。 -A timeout of 0 is not recommended. Some platforms, like Macs -(http://www.manpages.info/macosx/pcap.3.html) say: - The read timeout is used to arrange that the read not necessarily return - immediately when a packet is seen, but that it wait for some amount of time - to allow more packets to arrive and to read multiple packets from the OS - kernel in one operation. -This means that if you only capture one packet, the kernel might decide to wait -'timeout' for more packets to batch with it before returning. A timeout of -0, then, means 'wait forever for more packets', which is... not good. +为了解决这个问题,pcap 引入了以下行为: +如果传入了负超时时间,我们会在句柄中设置正超时时间, +然后当产生超时错误时,pcap 会在 ReadPacketData/ZeroCopyReadPacketData 中进行内部循环, -To get around this, we've introduced the following behavior: if a negative -timeout is passed in, we set the positive timeout in the handle, then loop -internally in ReadPacketData/ZeroCopyReadPacketData when we see timeout -errors. +# PCAP 文件写入 -PCAP File Writing +pcap 包并没有实现 PCAP 文件写入。 +但是,gopacket/pcapgo 实现了! 如果您想写 PCAP 文件,请去查看那里。 -This package does not implement PCAP file writing. However, gopacket/pcapgo -does! Look there if you'd like to write PCAP files. +# Windows用户的注意事项 -Note For Windows Users +gopacket 可以使用 winpcap 或 npcap。如果两者同时安装,npcap 会被优先使用。 +确保正确的 Windows 服务已经被加载(npcap 用于 npcap,npf 用于 winpcap)。 -gopacket can use winpcap or npcap. If both are installed at the same time, -npcap is preferred. Make sure the right windows service is loaded (npcap for npcap -and npf for winpcap). +TochusC AOSP Lab. 2024 */ package pcap diff --git a/pcap/gopacket_benchmark/benchmark.go b/pcap/gopacket_benchmark/benchmark.go index 09fcba041..5a929c6d0 100644 --- a/pcap/gopacket_benchmark/benchmark.go +++ b/pcap/gopacket_benchmark/benchmark.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/pcap/pcap.go b/pcap/pcap.go index ffddd72d4..e47122937 100644 --- a/pcap/pcap.go +++ b/pcap/pcap.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // diff --git a/pcap/pcap_test.go b/pcap/pcap_test.go index bbb7149ae..63e2f102f 100644 --- a/pcap/pcap_test.go +++ b/pcap/pcap_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/pcap/pcap_tester.go b/pcap/pcap_tester.go index 218d27ed3..9e020a235 100644 --- a/pcap/pcap_tester.go +++ b/pcap/pcap_tester.go @@ -1,9 +1,11 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. +//go:build ignore // +build ignore // This binary tests that PCAP packet capture is working correctly by issuing diff --git a/pcap/pcap_unix.go b/pcap/pcap_unix.go index a548016a2..5e1d64e5d 100644 --- a/pcap/pcap_unix.go +++ b/pcap/pcap_unix.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // @@ -5,6 +6,7 @@ // that can be found in the LICENSE file in the root of the source // tree. // +//go:build !windows // +build !windows package pcap diff --git a/pcap/pcap_windows.go b/pcap/pcap_windows.go index d2bfb6dc2..851f1c8b5 100644 --- a/pcap/pcap_windows.go +++ b/pcap/pcap_windows.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // diff --git a/pcap/pcapgo_test.go b/pcap/pcapgo_test.go index aca7f642f..3c858fe32 100644 --- a/pcap/pcapgo_test.go +++ b/pcap/pcapgo_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/pcapgo/capture.go b/pcapgo/capture.go index 5869d3d23..fbfeaf6b5 100644 --- a/pcapgo/capture.go +++ b/pcapgo/capture.go @@ -1,8 +1,10 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. +//go:build linux && go1.9 // +build linux,go1.9 package pcapgo diff --git a/pcapgo/capture_test.go b/pcapgo/capture_test.go index 8be7fa5ed..5ff67a569 100644 --- a/pcapgo/capture_test.go +++ b/pcapgo/capture_test.go @@ -1,8 +1,10 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. +//go:build linux && go1.9 // +build linux,go1.9 package pcapgo_test diff --git a/pcapgo/write.go b/pcapgo/write.go index 5ef20c8f8..b46348913 100755 --- a/pcapgo/write.go +++ b/pcapgo/write.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -38,18 +39,18 @@ const versionMinor = 4 // an append), you must call WriteFileHeader before WritePacket. Packet // timestamps are written with nanosecond precision. // -// // Write a new file: -// f, _ := os.Create("/tmp/file.pcap") -// w := pcapgo.NewWriterNanos(f) -// w.WriteFileHeader(65536, layers.LinkTypeEthernet) // new file, must do this. -// w.WritePacket(gopacket.CaptureInfo{...}, data1) -// f.Close() -// // Append to existing file (must have same snaplen and linktype) -// f2, _ := os.OpenFile("/tmp/fileNano.pcap", os.O_APPEND, 0700) -// w2 := pcapgo.NewWriter(f2) -// // no need for file header, it's already written. -// w2.WritePacket(gopacket.CaptureInfo{...}, data2) -// f2.Close() +// // Write a new file: +// f, _ := os.Create("/tmp/file.pcap") +// w := pcapgo.NewWriterNanos(f) +// w.WriteFileHeader(65536, layers.LinkTypeEthernet) // new file, must do this. +// w.WritePacket(gopacket.CaptureInfo{...}, data1) +// f.Close() +// // Append to existing file (must have same snaplen and linktype) +// f2, _ := os.OpenFile("/tmp/fileNano.pcap", os.O_APPEND, 0700) +// w2 := pcapgo.NewWriter(f2) +// // no need for file header, it's already written. +// w2.WritePacket(gopacket.CaptureInfo{...}, data2) +// f2.Close() func NewWriterNanos(w io.Writer) *Writer { return &Writer{w: w, tsScaler: nanosPerNano} } @@ -59,18 +60,18 @@ func NewWriterNanos(w io.Writer) *Writer { // an append), you must call WriteFileHeader before WritePacket. // Packet timestamps are written witn microsecond precision. // -// // Write a new file: -// f, _ := os.Create("/tmp/file.pcap") -// w := pcapgo.NewWriter(f) -// w.WriteFileHeader(65536, layers.LinkTypeEthernet) // new file, must do this. -// w.WritePacket(gopacket.CaptureInfo{...}, data1) -// f.Close() -// // Append to existing file (must have same snaplen and linktype) -// f2, _ := os.OpenFile("/tmp/file.pcap", os.O_APPEND, 0700) -// w2 := pcapgo.NewWriter(f2) -// // no need for file header, it's already written. -// w2.WritePacket(gopacket.CaptureInfo{...}, data2) -// f2.Close() +// // Write a new file: +// f, _ := os.Create("/tmp/file.pcap") +// w := pcapgo.NewWriter(f) +// w.WriteFileHeader(65536, layers.LinkTypeEthernet) // new file, must do this. +// w.WritePacket(gopacket.CaptureInfo{...}, data1) +// f.Close() +// // Append to existing file (must have same snaplen and linktype) +// f2, _ := os.OpenFile("/tmp/file.pcap", os.O_APPEND, 0700) +// w2 := pcapgo.NewWriter(f2) +// // no need for file header, it's already written. +// w2.WritePacket(gopacket.CaptureInfo{...}, data2) +// f2.Close() func NewWriter(w io.Writer) *Writer { return &Writer{w: w, tsScaler: nanosPerMicro} } diff --git a/pcapgo/write_test.go b/pcapgo/write_test.go index fb7144826..fa12adb68 100644 --- a/pcapgo/write_test.go +++ b/pcapgo/write_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/pfring/doc.go b/pfring/doc.go index 0c7229c8b..3a573a097 100644 --- a/pfring/doc.go +++ b/pfring/doc.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/pfring/pfring.go b/pfring/pfring.go index 9b625107f..a47d7ccae 100644 --- a/pfring/pfring.go +++ b/pfring/pfring.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // Copyright 2009-2011 Andreas Krennmair. All rights reserved. // @@ -206,9 +207,10 @@ func (r *Ring) ReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error // to old bytes when using ZeroCopyReadPacketData... if you need to keep data past // the next time you call ZeroCopyReadPacketData, use ReadPacketData, which copies // the bytes into a new buffer for you. -// data1, _, _ := handle.ZeroCopyReadPacketData() -// // do everything you want with data1 here, copying bytes out of it if you'd like to keep them around. -// data2, _, _ := handle.ZeroCopyReadPacketData() // invalidates bytes in data1 +// +// data1, _, _ := handle.ZeroCopyReadPacketData() +// // do everything you want with data1 here, copying bytes out of it if you'd like to keep them around. +// data2, _, _ := handle.ZeroCopyReadPacketData() // invalidates bytes in data1 func (r *Ring) ZeroCopyReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error) { r.mu.Lock() err = r.getNextBufPtrLocked(&ci) diff --git a/reassembly/cap2test.go b/reassembly/cap2test.go index f7b39fea9..486a185e7 100644 --- a/reassembly/cap2test.go +++ b/reassembly/cap2test.go @@ -1,9 +1,11 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. +//go:build ignore // +build ignore package main diff --git a/reassembly/memory.go b/reassembly/memory.go index 2c657f6d8..77ad631d6 100644 --- a/reassembly/memory.go +++ b/reassembly/memory.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/reassembly/tcpassembly.go b/reassembly/tcpassembly.go index 5b8247b22..850ad193b 100644 --- a/reassembly/tcpassembly.go +++ b/reassembly/tcpassembly.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -52,9 +53,11 @@ type Sequence int64 // Difference defines an ordering for comparing TCP sequences that's safe for // roll-overs. It returns: -// > 0 : if t comes after s -// < 0 : if t comes before s -// 0 : if t == s +// +// > 0 : if t comes after s +// < 0 : if t comes before s +// 0 : if t == s +// // The number returned is the sequence difference, so 4.Difference(8) will // return 4. // @@ -356,9 +359,9 @@ func (lp *livePacket) release(*pageCache) int { // it to create a new Stream for every TCP stream. // // assembly will, in order: -// 1) Create the stream via StreamFactory.New -// 2) Call ReassembledSG 0 or more times, passing in reassembled TCP data in order -// 3) Call ReassemblyComplete one time, after which the stream is dereferenced by assembly. +// 1. Create the stream via StreamFactory.New +// 2. Call ReassembledSG 0 or more times, passing in reassembled TCP data in order +// 3. Call ReassemblyComplete one time, after which the stream is dereferenced by assembly. type Stream interface { // Tell whether the TCP packet should be accepted, start could be modified to force a start even if no SYN have been seen Accept(tcp *layers.TCP, ci gopacket.CaptureInfo, dir TCPFlowDirection, nextSeq Sequence, start *bool, ac AssemblerContext) bool @@ -517,7 +520,7 @@ type AssemblerOptions struct { // applications written in Go. The Assembler uses the following methods to be // as fast as possible, to keep packet processing speedy: // -// Avoids Lock Contention +// # Avoids Lock Contention // // Assemblers locks connections, but each connection has an individual lock, and // rarely will two Assemblers be looking at the same connection. Assemblers @@ -537,7 +540,7 @@ type AssemblerOptions struct { // avoiding all lock contention. Only when different Assemblers could receive // packets for the same Stream should a StreamPool be shared between them. // -// Avoids Memory Copying +// # Avoids Memory Copying // // In the common case, handling of a single TCP packet should result in zero // memory allocations. The Assembler will look up the connection, figure out @@ -545,7 +548,7 @@ type AssemblerOptions struct { // the appropriate connection's handling code. Only if a packet arrives out of // order is its contents copied and stored in memory for later. // -// Avoids Memory Allocation +// # Avoids Memory Allocation // // Assemblers try very hard to not use memory allocation unless absolutely // necessary. Packet data for sequential packets is passed directly to streams @@ -632,9 +635,9 @@ type assemblerAction struct { // // Each AssembleWithContext call results in, in order: // -// zero or one call to StreamFactory.New, creating a stream -// zero or one call to ReassembledSG on a single stream -// zero or one call to ReassemblyComplete on the same stream +// zero or one call to StreamFactory.New, creating a stream +// zero or one call to ReassembledSG on a single stream +// zero or one call to ReassemblyComplete on the same stream func (a *Assembler) AssembleWithContext(netFlow gopacket.Flow, t *layers.TCP, ac AssemblerContext) { var conn *connection var half *halfconnection @@ -1114,7 +1117,6 @@ func (a *Assembler) sendToConnection(conn *connection, half *halfconnection, ac return nextSeq } -// func (a *Assembler) addPending(half *halfconnection, firstSeq Sequence) int { if half.saved == nil { return 0 diff --git a/reassembly/tcpassembly_test.go b/reassembly/tcpassembly_test.go index ed3d661f7..2b3d57a5d 100644 --- a/reassembly/tcpassembly_test.go +++ b/reassembly/tcpassembly_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/reassembly/tcpcheck.go b/reassembly/tcpcheck.go index 066a29311..6785d3647 100644 --- a/reassembly/tcpcheck.go +++ b/reassembly/tcpcheck.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/reassembly/tcpcheck_test.go b/reassembly/tcpcheck_test.go index bac912c3e..a1fbf7ec6 100644 --- a/reassembly/tcpcheck_test.go +++ b/reassembly/tcpcheck_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/routing/common.go b/routing/common.go index a6746d490..200207672 100644 --- a/routing/common.go +++ b/routing/common.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/routing/other.go b/routing/other.go index b53fea944..6ac019d76 100644 --- a/routing/other.go +++ b/routing/other.go @@ -1,9 +1,11 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. +//go:build !linux // +build !linux // Package routing is currently only supported in Linux, but the build system requires a valid go file for all architectures. diff --git a/routing/routing.go b/routing/routing.go index 8c906972b..b152f6267 100644 --- a/routing/routing.go +++ b/routing/routing.go @@ -1,9 +1,11 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. +//go:build linux // +build linux // Package routing provides a very basic but mostly functional implementation of diff --git a/routing/routing_test.go b/routing/routing_test.go index dfe5b1bd9..30b532420 100644 --- a/routing/routing_test.go +++ b/routing/routing_test.go @@ -1,9 +1,11 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. +//go:build linux // +build linux package routing diff --git a/tcpassembly/assembly.go b/tcpassembly/assembly.go index 710886340..2804db8ca 100644 --- a/tcpassembly/assembly.go +++ b/tcpassembly/assembly.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -42,9 +43,11 @@ type Sequence int64 // Difference defines an ordering for comparing TCP sequences that's safe for // roll-overs. It returns: -// > 0 : if t comes after s -// < 0 : if t comes before s -// 0 : if t == s +// +// > 0 : if t comes after s +// < 0 : if t comes before s +// 0 : if t == s +// // The number returned is the sequence difference, so 4.Difference(8) will // return 4. // @@ -164,9 +167,9 @@ func (c *pageCache) replace(p *page) { // it to create a new Stream for every TCP stream. // // assembly will, in order: -// 1) Create the stream via StreamFactory.New -// 2) Call Reassembled 0 or more times, passing in reassembled TCP data in order -// 3) Call ReassemblyComplete one time, after which the stream is dereferenced by assembly. +// 1. Create the stream via StreamFactory.New +// 2. Call Reassembled 0 or more times, passing in reassembled TCP data in order +// 3. Call ReassemblyComplete one time, after which the stream is dereferenced by assembly. type Stream interface { // Reassembled is called zero or more times. assembly guarantees // that the set of all Reassembly objects passed in during all @@ -419,7 +422,7 @@ type AssemblerOptions struct { // applications written in Go. The Assembler uses the following methods to be // as fast as possible, to keep packet processing speedy: // -// Avoids Lock Contention +// # Avoids Lock Contention // // Assemblers locks connections, but each connection has an individual lock, and // rarely will two Assemblers be looking at the same connection. Assemblers @@ -439,7 +442,7 @@ type AssemblerOptions struct { // avoiding all lock contention. Only when different Assemblers could receive // packets for the same Stream should a StreamPool be shared between them. // -// Avoids Memory Copying +// # Avoids Memory Copying // // In the common case, handling of a single TCP packet should result in zero // memory allocations. The Assembler will look up the connection, figure out @@ -447,7 +450,7 @@ type AssemblerOptions struct { // the appropriate connection's handling code. Only if a packet arrives out of // order is its contents copied and stored in memory for later. // -// Avoids Memory Allocation +// # Avoids Memory Allocation // // Assemblers try very hard to not use memory allocation unless absolutely // necessary. Packet data for sequential packets is passed directly to streams @@ -527,9 +530,9 @@ func (a *Assembler) Assemble(netFlow gopacket.Flow, t *layers.TCP) { // // Each Assemble call results in, in order: // -// zero or one calls to StreamFactory.New, creating a stream -// zero or one calls to Reassembled on a single stream -// zero or one calls to ReassemblyComplete on the same stream +// zero or one calls to StreamFactory.New, creating a stream +// zero or one calls to Reassembled on a single stream +// zero or one calls to ReassemblyComplete on the same stream func (a *Assembler) AssembleWithTimestamp(netFlow gopacket.Flow, t *layers.TCP, timestamp time.Time) { // Ignore empty TCP packets if !t.SYN && !t.FIN && !t.RST && len(t.LayerPayload()) == 0 { diff --git a/tcpassembly/assembly_test.go b/tcpassembly/assembly_test.go index bf3be35b5..a1712c30e 100644 --- a/tcpassembly/assembly_test.go +++ b/tcpassembly/assembly_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/tcpassembly/tcpreader/reader.go b/tcpassembly/tcpreader/reader.go index f5d6ab718..f149325bf 100644 --- a/tcpassembly/tcpreader/reader.go +++ b/tcpassembly/tcpreader/reader.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -16,28 +17,28 @@ // sniffing HTTP traffic. Using ReaderStream, this is relatively easy to set // up: // -// // Create our StreamFactory -// type httpStreamFactory struct {} -// func (f *httpStreamFactory) New(a, b gopacket.Flow) tcpassembly.Stream { -// r := tcpreader.NewReaderStream() -// go printRequests(&r, a, b) -// return &r -// } -// func printRequests(r io.Reader, a, b gopacket.Flow) { -// // Convert to bufio, since that's what ReadRequest wants. -// buf := bufio.NewReader(r) -// for { -// if req, err := http.ReadRequest(buf); err == io.EOF { -// return -// } else if err != nil { -// log.Println("Error parsing HTTP requests:", err) -// } else { -// fmt.Println(a, b) -// fmt.Println("HTTP REQUEST:", req) -// fmt.Println("Body contains", tcpreader.DiscardBytesToEOF(req.Body), "bytes") -// } -// } -// } +// // Create our StreamFactory +// type httpStreamFactory struct {} +// func (f *httpStreamFactory) New(a, b gopacket.Flow) tcpassembly.Stream { +// r := tcpreader.NewReaderStream() +// go printRequests(&r, a, b) +// return &r +// } +// func printRequests(r io.Reader, a, b gopacket.Flow) { +// // Convert to bufio, since that's what ReadRequest wants. +// buf := bufio.NewReader(r) +// for { +// if req, err := http.ReadRequest(buf); err == io.EOF { +// return +// } else if err != nil { +// log.Println("Error parsing HTTP requests:", err) +// } else { +// fmt.Println(a, b) +// fmt.Println("HTTP REQUEST:", req) +// fmt.Println("Body contains", tcpreader.DiscardBytesToEOF(req.Body), "bytes") +// } +// } +// } // // Using just this code, we're able to reference a powerful, built-in library // for HTTP request parsing to do all the dirty-work of parsing requests from @@ -89,20 +90,20 @@ func DiscardBytesToEOF(r io.Reader) (discarded int) { // a common pattern to do this by starting a goroutine in the factory's New // method: // -// type myStreamHandler struct { -// r ReaderStream -// } -// func (m *myStreamHandler) run() { -// // Do something here that reads all of the ReaderStream, or your assembly -// // will block. -// fmt.Println(tcpreader.DiscardBytesToEOF(&m.r)) -// } -// func (f *myStreamFactory) New(a, b gopacket.Flow) tcpassembly.Stream { -// s := &myStreamHandler{} -// go s.run() -// // Return the ReaderStream as the stream that assembly should populate. -// return &s.r -// } +// type myStreamHandler struct { +// r ReaderStream +// } +// func (m *myStreamHandler) run() { +// // Do something here that reads all of the ReaderStream, or your assembly +// // will block. +// fmt.Println(tcpreader.DiscardBytesToEOF(&m.r)) +// } +// func (f *myStreamFactory) New(a, b gopacket.Flow) tcpassembly.Stream { +// s := &myStreamHandler{} +// go s.run() +// // Return the ReaderStream as the stream that assembly should populate. +// return &s.r +// } type ReaderStream struct { ReaderStreamOptions reassembled chan []tcpassembly.Reassembly diff --git a/tcpassembly/tcpreader/reader_test.go b/tcpassembly/tcpreader/reader_test.go index 875cbbe24..4c75af118 100644 --- a/tcpassembly/tcpreader/reader_test.go +++ b/tcpassembly/tcpreader/reader_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license diff --git a/writer.go b/writer.go index 5d303dc4a..bb035ded5 100644 --- a/writer.go +++ b/writer.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license @@ -69,9 +70,9 @@ type SerializeOptions struct { // byte slices returned by any previous Bytes() call (the same buffer is // reused). // -// 1) Reusing a write buffer is generally much faster than creating a new one, +// 1. Reusing a write buffer is generally much faster than creating a new one, // and with the default implementation it avoids additional memory allocations. -// 2) If a byte slice from a previous Bytes() call will continue to be used, +// 2. If a byte slice from a previous Bytes() call will continue to be used, // it's better to create a new SerializeBuffer. // // The Clear method is specifically designed to minimize memory allocations for @@ -197,12 +198,13 @@ func (w *serializeBuffer) PushLayer(l LayerType) { // invalidates all slices previously returned by w.Bytes() // // Example: -// buf := gopacket.NewSerializeBuffer() -// opts := gopacket.SerializeOptions{} -// gopacket.SerializeLayers(buf, opts, a, b, c) -// firstPayload := buf.Bytes() // contains byte representation of a(b(c)) -// gopacket.SerializeLayers(buf, opts, d, e, f) -// secondPayload := buf.Bytes() // contains byte representation of d(e(f)). firstPayload is now invalidated, since the SerializeLayers call Clears buf. +// +// buf := gopacket.NewSerializeBuffer() +// opts := gopacket.SerializeOptions{} +// gopacket.SerializeLayers(buf, opts, a, b, c) +// firstPayload := buf.Bytes() // contains byte representation of a(b(c)) +// gopacket.SerializeLayers(buf, opts, d, e, f) +// secondPayload := buf.Bytes() // contains byte representation of d(e(f)). firstPayload is now invalidated, since the SerializeLayers call Clears buf. func SerializeLayers(w SerializeBuffer, opts SerializeOptions, layers ...SerializableLayer) error { w.Clear() for i := len(layers) - 1; i >= 0; i-- { diff --git a/writer_test.go b/writer_test.go index e19069b7e..1fdf8d11f 100644 --- a/writer_test.go +++ b/writer_test.go @@ -1,3 +1,4 @@ +// Copyright 2024 TochusC. All rights reserved. // Copyright 2012 Google, Inc. All rights reserved. // // Use of this source code is governed by a BSD-style license