Vendor update gopacket and unix package
This commit is contained in:
1 parent
54d24e65ef
commit
43d3339b39
319 files changed
+91339
-13246
No files matched your search
+74
@@ -0,0 +1,74 @@
|
||||
// Copyright 2019 The GoPacket Authors. 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.
|
||||
|
||||
// This file contains necessary structs/constants generated from libpcap headers with cgo -godefs
|
||||
// generated with: generate_defs.exe
|
||||
// DO NOT MODIFY
|
||||
|
||||
package pcap
|
||||
|
||||
import "syscall"
|
||||
|
||||
const errorBufferSize = 0x100
|
||||
|
||||
const (
|
||||
pcapErrorNotActivated = -0x3
|
||||
pcapErrorActivated = -0x4
|
||||
pcapWarningPromisc = 0x2
|
||||
pcapErrorNoSuchDevice = -0x5
|
||||
pcapErrorDenied = -0x8
|
||||
pcapErrorNotUp = -0x9
|
||||
pcapError = -0x1
|
||||
pcapWarning = 0x1
|
||||
pcapDIN = 0x1
|
||||
pcapDOUT = 0x2
|
||||
pcapDINOUT = 0x0
|
||||
pcapNetmaskUnknown = 0xffffffff
|
||||
pcapTstampPrecisionMicro = 0x0
|
||||
pcapTstampPrecisionNano = 0x1
|
||||
)
|
||||
|
||||
type timeval struct {
|
||||
Sec int32
|
||||
Usec int32
|
||||
}
|
||||
type pcapPkthdr struct {
|
||||
Ts timeval
|
||||
Caplen uint32
|
||||
Len uint32
|
||||
}
|
||||
type pcapTPtr uintptr
|
||||
type pcapBpfInstruction struct {
|
||||
Code uint16
|
||||
Jt uint8
|
||||
Jf uint8
|
||||
K uint32
|
||||
}
|
||||
type pcapBpfProgram struct {
|
||||
Len uint32
|
||||
Insns *pcapBpfInstruction
|
||||
}
|
||||
type pcapStats struct {
|
||||
Recv uint32
|
||||
Drop uint32
|
||||
Ifdrop uint32
|
||||
}
|
||||
type pcapCint int32
|
||||
type pcapIf struct {
|
||||
Next *pcapIf
|
||||
Name *int8
|
||||
Description *int8
|
||||
Addresses *pcapAddr
|
||||
Flags uint32
|
||||
}
|
||||
|
||||
type pcapAddr struct {
|
||||
Next *pcapAddr
|
||||
Addr *syscall.RawSockaddr
|
||||
Netmask *syscall.RawSockaddr
|
||||
Broadaddr *syscall.RawSockaddr
|
||||
Dstaddr *syscall.RawSockaddr
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
// Copyright 2019 The GoPacket Authors. 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.
|
||||
|
||||
// This file contains necessary structs/constants generated from libpcap headers with cgo -godefs
|
||||
// generated with: generate_defs.exe
|
||||
// DO NOT MODIFY
|
||||
|
||||
package pcap
|
||||
|
||||
import "syscall"
|
||||
|
||||
const errorBufferSize = 0x100
|
||||
|
||||
const (
|
||||
pcapErrorNotActivated = -0x3
|
||||
pcapErrorActivated = -0x4
|
||||
pcapWarningPromisc = 0x2
|
||||
pcapErrorNoSuchDevice = -0x5
|
||||
pcapErrorDenied = -0x8
|
||||
pcapErrorNotUp = -0x9
|
||||
pcapError = -0x1
|
||||
pcapWarning = 0x1
|
||||
pcapDIN = 0x1
|
||||
pcapDOUT = 0x2
|
||||
pcapDINOUT = 0x0
|
||||
pcapNetmaskUnknown = 0xffffffff
|
||||
pcapTstampPrecisionMicro = 0x0
|
||||
pcapTstampPrecisionNano = 0x1
|
||||
)
|
||||
|
||||
type timeval struct {
|
||||
Sec int32
|
||||
Usec int32
|
||||
}
|
||||
type pcapPkthdr struct {
|
||||
Ts timeval
|
||||
Caplen uint32
|
||||
Len uint32
|
||||
}
|
||||
type pcapTPtr uintptr
|
||||
type pcapBpfInstruction struct {
|
||||
Code uint16
|
||||
Jt uint8
|
||||
Jf uint8
|
||||
K uint32
|
||||
}
|
||||
type pcapBpfProgram struct {
|
||||
Len uint32
|
||||
Pad_cgo_0 [4]byte
|
||||
Insns *pcapBpfInstruction
|
||||
}
|
||||
type pcapStats struct {
|
||||
Recv uint32
|
||||
Drop uint32
|
||||
Ifdrop uint32
|
||||
}
|
||||
type pcapCint int32
|
||||
type pcapIf struct {
|
||||
Next *pcapIf
|
||||
Name *int8
|
||||
Description *int8
|
||||
Addresses *pcapAddr
|
||||
Flags uint32
|
||||
Pad_cgo_0 [4]byte
|
||||
}
|
||||
|
||||
type pcapAddr struct {
|
||||
Next *pcapAddr
|
||||
Addr *syscall.RawSockaddr
|
||||
Netmask *syscall.RawSockaddr
|
||||
Broadaddr *syscall.RawSockaddr
|
||||
Dstaddr *syscall.RawSockaddr
|
||||
}
|
||||
+11
-5
@@ -12,6 +12,12 @@ This package is meant to be used with its parent,
|
||||
http://github.com/google/gopacket, although it can also be used independently
|
||||
if you just want to get packet data from the wire.
|
||||
|
||||
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.
|
||||
@@ -28,7 +34,7 @@ The following code can be used to read in data from a pcap file.
|
||||
Reading Live Packets
|
||||
|
||||
The following code can be used to read in data from a live device, in this case
|
||||
"eth0".
|
||||
"eth0". Be aware, that OpenLive only supports microsecond resolution.
|
||||
|
||||
if handle, err := pcap.OpenLive("eth0", 1600, true, pcap.BlockForever); err != nil {
|
||||
panic(err)
|
||||
@@ -97,10 +103,10 @@ PCAP File Writing
|
||||
This package does not implement PCAP file writing. However, gopacket/pcapgo
|
||||
does! Look there if you'd like to write PCAP files.
|
||||
|
||||
Note For Windows 10 Users
|
||||
Note For Windows Users
|
||||
|
||||
If you're trying to use 64-bit winpcap on Windows 10, you might have to do
|
||||
the crazy hijinks detailed at
|
||||
http://stackoverflow.com/questions/38047858/compile-gopacket-on-windows-64bit
|
||||
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).
|
||||
*/
|
||||
package pcap
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
// Copyright 2019 The GoPacket Authors. 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.
|
||||
|
||||
// +build ignore
|
||||
|
||||
package main
|
||||
|
||||
// This file generates the godefs needed for the windows version.
|
||||
// Rebuild is only necessary if additional libpcap functionality is implemented, or a new arch is implemented in golang.
|
||||
// Call with go run generate_windows.go [-I includepath]
|
||||
// Needs npcap sdk, go tool cgo, and gofmt to work. Location of npcap includes can be specified with -I
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const header = `// Copyright 2019 The GoPacket Authors. 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.
|
||||
|
||||
// This file contains necessary structs/constants generated from libpcap headers with cgo -godefs
|
||||
// generated with: %s
|
||||
// DO NOT MODIFY
|
||||
|
||||
`
|
||||
|
||||
const source = `
|
||||
package pcap
|
||||
|
||||
//#include <pcap.h>
|
||||
import "C"
|
||||
|
||||
import "syscall" // needed for RawSockaddr
|
||||
|
||||
const errorBufferSize = C.PCAP_ERRBUF_SIZE
|
||||
|
||||
const (
|
||||
pcapErrorNotActivated = C.PCAP_ERROR_NOT_ACTIVATED
|
||||
pcapErrorActivated = C.PCAP_ERROR_ACTIVATED
|
||||
pcapWarningPromisc = C.PCAP_WARNING_PROMISC_NOTSUP
|
||||
pcapErrorNoSuchDevice = C.PCAP_ERROR_NO_SUCH_DEVICE
|
||||
pcapErrorDenied = C.PCAP_ERROR_PERM_DENIED
|
||||
pcapErrorNotUp = C.PCAP_ERROR_IFACE_NOT_UP
|
||||
pcapError = C.PCAP_ERROR
|
||||
pcapWarning = C.PCAP_WARNING
|
||||
pcapDIN = C.PCAP_D_IN
|
||||
pcapDOUT = C.PCAP_D_OUT
|
||||
pcapDINOUT = C.PCAP_D_INOUT
|
||||
pcapNetmaskUnknown = C.PCAP_NETMASK_UNKNOWN
|
||||
pcapTstampPrecisionMicro = C.PCAP_TSTAMP_PRECISION_MICRO
|
||||
pcapTstampPrecisionNano = C.PCAP_TSTAMP_PRECISION_NANO
|
||||
)
|
||||
|
||||
type timeval C.struct_timeval
|
||||
type pcapPkthdr C.struct_pcap_pkthdr
|
||||
type pcapTPtr uintptr
|
||||
type pcapBpfInstruction C.struct_bpf_insn
|
||||
type pcapBpfProgram C.struct_bpf_program
|
||||
type pcapStats C.struct_pcap_stat
|
||||
type pcapCint C.int
|
||||
type pcapIf C.struct_pcap_if
|
||||
// +godefs map struct_sockaddr syscall.RawSockaddr
|
||||
type pcapAddr C.struct_pcap_addr
|
||||
`
|
||||
|
||||
var includes = flag.String("I", "C:\\npcap-sdk-1.01\\Include", "Include path containing libpcap headers")
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
|
||||
infile, err := ioutil.TempFile(".", "defs.*.go")
|
||||
if err != nil {
|
||||
log.Fatal("Couldn't create temporary source file: ", err)
|
||||
}
|
||||
defer infile.Close()
|
||||
defer os.Remove(infile.Name())
|
||||
|
||||
_, err = infile.WriteString(source)
|
||||
if err != nil {
|
||||
log.Fatalf("Couldn't write definitions to temporary file %s: %s", infile.Name(), err)
|
||||
}
|
||||
err = infile.Close()
|
||||
if err != nil {
|
||||
log.Fatalf("Couldn't close temporary source file %s: %s", infile.Name(), err)
|
||||
}
|
||||
|
||||
archs := []string{"386", "amd64"}
|
||||
for _, arch := range archs {
|
||||
env := append(os.Environ(), "GOARCH="+arch)
|
||||
cmd := exec.Command("go", "tool", "cgo", "-godefs", "--", "-I", *includes, infile.Name())
|
||||
cmd.Env = env
|
||||
cmd.Stderr = os.Stderr
|
||||
var generated bytes.Buffer
|
||||
cmd.Stdout = &generated
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
log.Fatalf("Couldn't generated defs for %s: %s\n", arch, err)
|
||||
}
|
||||
|
||||
cmd = exec.Command("gofmt")
|
||||
cmd.Env = env
|
||||
cmd.Stderr = os.Stderr
|
||||
outName := fmt.Sprintf("defs_windows_%s.go", arch)
|
||||
out, err := os.Create(outName)
|
||||
if err != nil {
|
||||
log.Fatalf("Couldn't open file %s: %s", outName, err)
|
||||
}
|
||||
cmd.Stdout = out
|
||||
in, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
log.Fatal("Couldn't create input pipe for gofmt: ", err)
|
||||
}
|
||||
err = cmd.Start()
|
||||
if err != nil {
|
||||
log.Fatal("Couldn't start gofmt: ", err)
|
||||
}
|
||||
|
||||
_, err = fmt.Fprintf(in, header, strings.Join(append([]string{filepath.Base(os.Args[0])}, os.Args[1:]...), " "))
|
||||
if err != nil {
|
||||
log.Fatal("Couldn't write header to gofmt: ", err)
|
||||
}
|
||||
|
||||
for {
|
||||
line, err := generated.ReadBytes('\n')
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
// remove godefs comments
|
||||
if bytes.HasPrefix(line, []byte("//")) {
|
||||
continue
|
||||
}
|
||||
_, err = in.Write(line)
|
||||
if err != nil {
|
||||
log.Fatal("Couldn't write line to gofmt: ", err)
|
||||
}
|
||||
}
|
||||
in.Close()
|
||||
err = cmd.Wait()
|
||||
if err != nil {
|
||||
log.Fatal("gofmt failed: ", err)
|
||||
}
|
||||
out.Close()
|
||||
}
|
||||
}
|
||||
+266
-405
File diff suppressed because it is too large.
Load diff
+2
-3
@@ -15,7 +15,6 @@ import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
@@ -35,7 +34,7 @@ func generatePackets() {
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
ifaces, err := net.Interfaces()
|
||||
ifaces, err := pcap.FindAllDevs()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
@@ -51,7 +50,7 @@ func main() {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func tryCapture(iface net.Interface) error {
|
||||
func tryCapture(iface pcap.Interface) error {
|
||||
if iface.Name[:2] == "lo" {
|
||||
return errors.New("skipping loopback")
|
||||
}
|
||||
|
||||
+648
-6
@@ -9,9 +9,131 @@
|
||||
|
||||
package pcap
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/google/gopacket"
|
||||
|
||||
"github.com/google/gopacket/layers"
|
||||
)
|
||||
|
||||
/*
|
||||
#cgo solaris LDFLAGS: -L /opt/local/lib -lpcap
|
||||
#cgo linux LDFLAGS: -lpcap
|
||||
#cgo dragonfly LDFLAGS: -lpcap
|
||||
#cgo freebsd LDFLAGS: -lpcap
|
||||
#cgo openbsd LDFLAGS: -lpcap
|
||||
#cgo netbsd LDFLAGS: -lpcap
|
||||
#cgo darwin LDFLAGS: -lpcap
|
||||
#include <stdlib.h>
|
||||
#include <pcap.h>
|
||||
#include <stdint.h>
|
||||
|
||||
// Some old versions of pcap don't define this constant.
|
||||
#ifndef PCAP_NETMASK_UNKNOWN
|
||||
#define PCAP_NETMASK_UNKNOWN 0xffffffff
|
||||
#endif
|
||||
|
||||
// libpcap doesn't actually export its version in a #define-guardable way,
|
||||
// so we have to use other defined things to differentiate versions.
|
||||
// We assume at least libpcap v1.1 at the moment.
|
||||
// See http://upstream-tracker.org/versions/libpcap.html
|
||||
|
||||
#ifndef PCAP_ERROR_TSTAMP_PRECISION_NOTSUP // < v1.5
|
||||
#define PCAP_ERROR_TSTAMP_PRECISION_NOTSUP -12
|
||||
|
||||
int pcap_set_immediate_mode(pcap_t *p, int mode) {
|
||||
return PCAP_ERROR;
|
||||
}
|
||||
|
||||
// libpcap version < v1.5 doesn't have timestamp precision (everything is microsecond)
|
||||
//
|
||||
// This means *_tstamp_* functions and macros are missing. Therefore, we emulate these
|
||||
// functions here and pretend the setting the precision works. This is actually the way
|
||||
// the pcap_open_offline_with_tstamp_precision works, because it doesn't return an error
|
||||
// if it was not possible to set the precision, which depends on support by the given file.
|
||||
// => The rest of the functions always pretend as if they could set nano precision and
|
||||
// verify the actual precision with pcap_get_tstamp_precision, which is emulated for <v1.5
|
||||
// to always return micro resolution.
|
||||
|
||||
#define PCAP_TSTAMP_PRECISION_MICRO 0
|
||||
#define PCAP_TSTAMP_PRECISION_NANO 1
|
||||
|
||||
pcap_t *pcap_open_offline_with_tstamp_precision(const char *fname, u_int precision,
|
||||
char *errbuf) {
|
||||
return pcap_open_offline(fname, errbuf);
|
||||
}
|
||||
|
||||
int pcap_set_tstamp_precision(pcap_t *p, int tstamp_precision) {
|
||||
if (tstamp_precision == PCAP_TSTAMP_PRECISION_MICRO)
|
||||
return 0;
|
||||
return PCAP_ERROR_TSTAMP_PRECISION_NOTSUP;
|
||||
}
|
||||
|
||||
int pcap_get_tstamp_precision(pcap_t *p) {
|
||||
return PCAP_TSTAMP_PRECISION_MICRO
|
||||
}
|
||||
|
||||
#ifndef PCAP_TSTAMP_HOST // < v1.2
|
||||
|
||||
int pcap_set_tstamp_type(pcap_t* p, int t) { return -1; }
|
||||
int pcap_list_tstamp_types(pcap_t* p, int** t) { return 0; }
|
||||
void pcap_free_tstamp_types(int *tstamp_types) {}
|
||||
const char* pcap_tstamp_type_val_to_name(int t) {
|
||||
return "pcap timestamp types not supported";
|
||||
}
|
||||
int pcap_tstamp_type_name_to_val(const char* t) {
|
||||
return PCAP_ERROR;
|
||||
}
|
||||
|
||||
#endif // < v1.2
|
||||
#endif // < v1.5
|
||||
|
||||
#ifndef PCAP_ERROR_PROMISC_PERM_DENIED
|
||||
#define PCAP_ERROR_PROMISC_PERM_DENIED -11
|
||||
#endif
|
||||
|
||||
// Windows, Macs, and Linux all use different time types. Joy.
|
||||
#ifdef __APPLE__
|
||||
#define gopacket_time_secs_t __darwin_time_t
|
||||
#define gopacket_time_usecs_t __darwin_suseconds_t
|
||||
#elif __ANDROID__
|
||||
#define gopacket_time_secs_t __kernel_time_t
|
||||
#define gopacket_time_usecs_t __kernel_suseconds_t
|
||||
#elif __GLIBC__
|
||||
#define gopacket_time_secs_t __time_t
|
||||
#define gopacket_time_usecs_t __suseconds_t
|
||||
#else // Some form of linux/bsd/etc...
|
||||
#include <sys/param.h>
|
||||
#ifdef __OpenBSD__
|
||||
#define gopacket_time_secs_t u_int32_t
|
||||
#define gopacket_time_usecs_t u_int32_t
|
||||
#else
|
||||
#define gopacket_time_secs_t time_t
|
||||
#define gopacket_time_usecs_t suseconds_t
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// The things we do to avoid pointers escaping to the heap...
|
||||
// According to https://github.com/the-tcpdump-group/libpcap/blob/1131a7c26c6f4d4772e4a2beeaf7212f4dea74ac/pcap.c#L398-L406 ,
|
||||
// the return value of pcap_next_ex could be greater than 1 for success.
|
||||
// Let's just make it 1 if it comes bigger than 1.
|
||||
int pcap_next_ex_escaping(pcap_t *p, uintptr_t pkt_hdr, uintptr_t pkt_data) {
|
||||
int ex = pcap_next_ex(p, (struct pcap_pkthdr**)(pkt_hdr), (const u_char**)(pkt_data));
|
||||
if (ex > 1) {
|
||||
ex = 1;
|
||||
}
|
||||
return ex;
|
||||
}
|
||||
|
||||
int pcap_offline_filter_escaping(struct bpf_program *fp, uintptr_t pkt_hdr, uintptr_t pkt) {
|
||||
return pcap_offline_filter(fp, (struct pcap_pkthdr*)(pkt_hdr), (const u_char*)(pkt));
|
||||
}
|
||||
|
||||
// pcap_wait returns when the next packet is available or the timeout expires.
|
||||
// Since it uses pcap_get_selectable_fd, it will not work in Windows.
|
||||
@@ -38,21 +160,526 @@ int pcap_wait(pcap_t *p, int usec) {
|
||||
// block indefinitely if no timeout provided
|
||||
return select(fd+1, &fds, NULL, NULL, NULL);
|
||||
}
|
||||
|
||||
// libpcap version < v1.5 doesn't have timestamp precision (everything is microsecond)
|
||||
// see pcap.go for an explanation of why precision is ignored
|
||||
#ifndef PCAP_ERROR_TSTAMP_PRECISION_NOTSUP // < v1.5
|
||||
pcap_t *pcap_fopen_offline_with_tstamp_precision(FILE *fp, u_int precision,
|
||||
char *errbuf) {
|
||||
return pcap_fopen_offline(fp, errbuf);
|
||||
}
|
||||
#endif // < v1.5
|
||||
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"unsafe"
|
||||
const errorBufferSize = C.PCAP_ERRBUF_SIZE
|
||||
|
||||
const (
|
||||
pcapErrorNotActivated = C.PCAP_ERROR_NOT_ACTIVATED
|
||||
pcapErrorActivated = C.PCAP_ERROR_ACTIVATED
|
||||
pcapWarningPromisc = C.PCAP_WARNING_PROMISC_NOTSUP
|
||||
pcapErrorNoSuchDevice = C.PCAP_ERROR_NO_SUCH_DEVICE
|
||||
pcapErrorDenied = C.PCAP_ERROR_PERM_DENIED
|
||||
pcapErrorNotUp = C.PCAP_ERROR_IFACE_NOT_UP
|
||||
pcapWarning = C.PCAP_WARNING
|
||||
pcapDIN = C.PCAP_D_IN
|
||||
pcapDOUT = C.PCAP_D_OUT
|
||||
pcapDINOUT = C.PCAP_D_INOUT
|
||||
pcapNetmaskUnknown = C.PCAP_NETMASK_UNKNOWN
|
||||
pcapTstampPrecisionMicro = C.PCAP_TSTAMP_PRECISION_MICRO
|
||||
pcapTstampPrecisionNano = C.PCAP_TSTAMP_PRECISION_NANO
|
||||
)
|
||||
|
||||
func (p *Handle) openLive() error {
|
||||
type pcapPkthdr C.struct_pcap_pkthdr
|
||||
type pcapTPtr *C.struct_pcap
|
||||
type pcapBpfProgram C.struct_bpf_program
|
||||
|
||||
func (h *pcapPkthdr) getSec() int64 {
|
||||
return int64(h.ts.tv_sec)
|
||||
}
|
||||
|
||||
func (h *pcapPkthdr) getUsec() int64 {
|
||||
return int64(h.ts.tv_usec)
|
||||
}
|
||||
|
||||
func (h *pcapPkthdr) getLen() int {
|
||||
return int(h.len)
|
||||
}
|
||||
|
||||
func (h *pcapPkthdr) getCaplen() int {
|
||||
return int(h.caplen)
|
||||
}
|
||||
|
||||
func pcapGetTstampPrecision(cptr pcapTPtr) int {
|
||||
return int(C.pcap_get_tstamp_precision(cptr))
|
||||
}
|
||||
|
||||
func pcapSetTstampPrecision(cptr pcapTPtr, precision int) error {
|
||||
ret := C.pcap_set_tstamp_precision(cptr, C.int(precision))
|
||||
if ret < 0 {
|
||||
return errors.New(C.GoString(C.pcap_geterr(cptr)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func statusError(status C.int) error {
|
||||
return errors.New(C.GoString(C.pcap_statustostr(status)))
|
||||
}
|
||||
|
||||
func pcapOpenLive(device string, snaplen int, pro int, timeout int) (*Handle, error) {
|
||||
buf := (*C.char)(C.calloc(errorBufferSize, 1))
|
||||
defer C.free(unsafe.Pointer(buf))
|
||||
|
||||
dev := C.CString(device)
|
||||
defer C.free(unsafe.Pointer(dev))
|
||||
|
||||
cptr := C.pcap_open_live(dev, C.int(snaplen), C.int(pro), C.int(timeout), buf)
|
||||
if cptr == nil {
|
||||
return nil, errors.New(C.GoString(buf))
|
||||
}
|
||||
return &Handle{cptr: cptr}, nil
|
||||
}
|
||||
|
||||
func openOffline(file string) (handle *Handle, err error) {
|
||||
buf := (*C.char)(C.calloc(errorBufferSize, 1))
|
||||
defer C.free(unsafe.Pointer(buf))
|
||||
cf := C.CString(file)
|
||||
defer C.free(unsafe.Pointer(cf))
|
||||
|
||||
cptr := C.pcap_open_offline_with_tstamp_precision(cf, C.PCAP_TSTAMP_PRECISION_NANO, buf)
|
||||
if cptr == nil {
|
||||
return nil, errors.New(C.GoString(buf))
|
||||
}
|
||||
return &Handle{cptr: cptr}, nil
|
||||
}
|
||||
|
||||
func (p *Handle) pcapClose() {
|
||||
if p.cptr != nil {
|
||||
C.pcap_close(p.cptr)
|
||||
}
|
||||
p.cptr = nil
|
||||
}
|
||||
|
||||
func (p *Handle) pcapGeterr() error {
|
||||
return errors.New(C.GoString(C.pcap_geterr(p.cptr)))
|
||||
}
|
||||
|
||||
func (p *Handle) pcapStats() (*Stats, error) {
|
||||
var cstats C.struct_pcap_stat
|
||||
if C.pcap_stats(p.cptr, &cstats) < 0 {
|
||||
return nil, p.pcapGeterr()
|
||||
}
|
||||
return &Stats{
|
||||
PacketsReceived: int(cstats.ps_recv),
|
||||
PacketsDropped: int(cstats.ps_drop),
|
||||
PacketsIfDropped: int(cstats.ps_ifdrop),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// for libpcap < 1.8 pcap_compile is NOT thread-safe, so protect it.
|
||||
var pcapCompileMu sync.Mutex
|
||||
|
||||
func (p *Handle) pcapCompile(expr string, maskp uint32) (pcapBpfProgram, error) {
|
||||
var bpf pcapBpfProgram
|
||||
cexpr := C.CString(expr)
|
||||
defer C.free(unsafe.Pointer(cexpr))
|
||||
|
||||
pcapCompileMu.Lock()
|
||||
defer pcapCompileMu.Unlock()
|
||||
if C.pcap_compile(p.cptr, (*C.struct_bpf_program)(&bpf), cexpr, 1, C.bpf_u_int32(maskp)) < 0 {
|
||||
return bpf, p.pcapGeterr()
|
||||
}
|
||||
return bpf, nil
|
||||
}
|
||||
|
||||
func (p pcapBpfProgram) free() {
|
||||
C.pcap_freecode((*C.struct_bpf_program)(&p))
|
||||
}
|
||||
|
||||
func (p pcapBpfProgram) toBPFInstruction() []BPFInstruction {
|
||||
bpfInsn := (*[bpfInstructionBufferSize]C.struct_bpf_insn)(unsafe.Pointer(p.bf_insns))[0:p.bf_len:p.bf_len]
|
||||
bpfInstruction := make([]BPFInstruction, len(bpfInsn), len(bpfInsn))
|
||||
|
||||
for i, v := range bpfInsn {
|
||||
bpfInstruction[i].Code = uint16(v.code)
|
||||
bpfInstruction[i].Jt = uint8(v.jt)
|
||||
bpfInstruction[i].Jf = uint8(v.jf)
|
||||
bpfInstruction[i].K = uint32(v.k)
|
||||
}
|
||||
return bpfInstruction
|
||||
}
|
||||
|
||||
func pcapBpfProgramFromInstructions(bpfInstructions []BPFInstruction) pcapBpfProgram {
|
||||
var bpf pcapBpfProgram
|
||||
bpf.bf_len = C.u_int(len(bpfInstructions))
|
||||
cbpfInsns := C.calloc(C.size_t(len(bpfInstructions)), C.size_t(unsafe.Sizeof(bpfInstructions[0])))
|
||||
gbpfInsns := (*[bpfInstructionBufferSize]C.struct_bpf_insn)(cbpfInsns)
|
||||
|
||||
for i, v := range bpfInstructions {
|
||||
gbpfInsns[i].code = C.u_short(v.Code)
|
||||
gbpfInsns[i].jt = C.u_char(v.Jt)
|
||||
gbpfInsns[i].jf = C.u_char(v.Jf)
|
||||
gbpfInsns[i].k = C.bpf_u_int32(v.K)
|
||||
}
|
||||
|
||||
bpf.bf_insns = (*C.struct_bpf_insn)(cbpfInsns)
|
||||
return bpf
|
||||
}
|
||||
|
||||
func pcapLookupnet(device string) (netp, maskp uint32, err error) {
|
||||
errorBuf := (*C.char)(C.calloc(errorBufferSize, 1))
|
||||
defer C.free(unsafe.Pointer(errorBuf))
|
||||
dev := C.CString(device)
|
||||
defer C.free(unsafe.Pointer(dev))
|
||||
if C.pcap_lookupnet(
|
||||
dev,
|
||||
(*C.bpf_u_int32)(unsafe.Pointer(&netp)),
|
||||
(*C.bpf_u_int32)(unsafe.Pointer(&maskp)),
|
||||
errorBuf,
|
||||
) < 0 {
|
||||
return 0, 0, errors.New(C.GoString(errorBuf))
|
||||
// We can't lookup the network, but that could be because the interface
|
||||
// doesn't have an IPv4.
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (b *BPF) pcapOfflineFilter(ci gopacket.CaptureInfo, data []byte) bool {
|
||||
hdr := (*C.struct_pcap_pkthdr)(&b.hdr)
|
||||
hdr.ts.tv_sec = C.gopacket_time_secs_t(ci.Timestamp.Unix())
|
||||
hdr.ts.tv_usec = C.gopacket_time_usecs_t(ci.Timestamp.Nanosecond() / 1000)
|
||||
hdr.caplen = C.bpf_u_int32(len(data)) // Trust actual length over ci.Length.
|
||||
hdr.len = C.bpf_u_int32(ci.Length)
|
||||
dataptr := (*C.u_char)(unsafe.Pointer(&data[0]))
|
||||
return C.pcap_offline_filter_escaping((*C.struct_bpf_program)(&b.bpf),
|
||||
C.uintptr_t(uintptr(unsafe.Pointer(hdr))),
|
||||
C.uintptr_t(uintptr(unsafe.Pointer(dataptr)))) != 0
|
||||
}
|
||||
|
||||
func (p *Handle) pcapSetfilter(bpf pcapBpfProgram) error {
|
||||
if C.pcap_setfilter(p.cptr, (*C.struct_bpf_program)(&bpf)) < 0 {
|
||||
return p.pcapGeterr()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Handle) pcapListDatalinks() (datalinks []Datalink, err error) {
|
||||
var dltbuf *C.int
|
||||
|
||||
n := int(C.pcap_list_datalinks(p.cptr, &dltbuf))
|
||||
if n < 0 {
|
||||
return nil, p.pcapGeterr()
|
||||
}
|
||||
|
||||
defer C.pcap_free_datalinks(dltbuf)
|
||||
|
||||
datalinks = make([]Datalink, n)
|
||||
|
||||
dltArray := (*[1 << 28]C.int)(unsafe.Pointer(dltbuf))
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
datalinks[i].Name = pcapDatalinkValToName(int((*dltArray)[i]))
|
||||
datalinks[i].Description = pcapDatalinkValToDescription(int((*dltArray)[i]))
|
||||
}
|
||||
|
||||
return datalinks, nil
|
||||
}
|
||||
|
||||
func pcapOpenDead(linkType layers.LinkType, captureLength int) (*Handle, error) {
|
||||
cptr := C.pcap_open_dead(C.int(linkType), C.int(captureLength))
|
||||
if cptr == nil {
|
||||
return nil, errors.New("error opening dead capture")
|
||||
}
|
||||
|
||||
return &Handle{cptr: cptr}, nil
|
||||
}
|
||||
|
||||
func (p *Handle) pcapNextPacketEx() NextError {
|
||||
// This horrible magic allows us to pass a ptr-to-ptr to pcap_next_ex
|
||||
// without causing that ptr-to-ptr to itself be allocated on the heap.
|
||||
// Since Handle itself survives through the duration of the pcap_next_ex
|
||||
// call, this should be perfectly safe for GC stuff, etc.
|
||||
|
||||
return NextError(C.pcap_next_ex_escaping(p.cptr, C.uintptr_t(uintptr(unsafe.Pointer(&p.pkthdr))), C.uintptr_t(uintptr(unsafe.Pointer(&p.bufptr)))))
|
||||
}
|
||||
|
||||
func (p *Handle) pcapDatalink() layers.LinkType {
|
||||
return layers.LinkType(C.pcap_datalink(p.cptr))
|
||||
}
|
||||
|
||||
func (p *Handle) pcapSetDatalink(dlt layers.LinkType) error {
|
||||
if C.pcap_set_datalink(p.cptr, C.int(dlt)) < 0 {
|
||||
return p.pcapGeterr()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func pcapDatalinkValToName(dlt int) string {
|
||||
return C.GoString(C.pcap_datalink_val_to_name(C.int(dlt)))
|
||||
}
|
||||
|
||||
func pcapDatalinkValToDescription(dlt int) string {
|
||||
return C.GoString(C.pcap_datalink_val_to_description(C.int(dlt)))
|
||||
}
|
||||
|
||||
func pcapDatalinkNameToVal(name string) int {
|
||||
cptr := C.CString(name)
|
||||
defer C.free(unsafe.Pointer(cptr))
|
||||
return int(C.pcap_datalink_name_to_val(cptr))
|
||||
}
|
||||
|
||||
func pcapLibVersion() string {
|
||||
return C.GoString(C.pcap_lib_version())
|
||||
}
|
||||
|
||||
func (p *Handle) isOpen() bool {
|
||||
return p.cptr != nil
|
||||
}
|
||||
|
||||
type pcapDevices struct {
|
||||
all, cur *C.pcap_if_t
|
||||
}
|
||||
|
||||
func (p pcapDevices) free() {
|
||||
C.pcap_freealldevs((*C.pcap_if_t)(p.all))
|
||||
}
|
||||
|
||||
func (p *pcapDevices) next() bool {
|
||||
if p.cur == nil {
|
||||
p.cur = p.all
|
||||
if p.cur == nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
if p.cur.next == nil {
|
||||
return false
|
||||
}
|
||||
p.cur = p.cur.next
|
||||
return true
|
||||
}
|
||||
|
||||
func (p pcapDevices) name() string {
|
||||
return C.GoString(p.cur.name)
|
||||
}
|
||||
|
||||
func (p pcapDevices) description() string {
|
||||
return C.GoString(p.cur.description)
|
||||
}
|
||||
|
||||
func (p pcapDevices) flags() uint32 {
|
||||
return uint32(p.cur.flags)
|
||||
}
|
||||
|
||||
type pcapAddresses struct {
|
||||
all, cur *C.pcap_addr_t
|
||||
}
|
||||
|
||||
func (p *pcapAddresses) next() bool {
|
||||
if p.cur == nil {
|
||||
p.cur = p.all
|
||||
if p.cur == nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
if p.cur.next == nil {
|
||||
return false
|
||||
}
|
||||
p.cur = p.cur.next
|
||||
return true
|
||||
}
|
||||
|
||||
func (p pcapAddresses) addr() *syscall.RawSockaddr {
|
||||
return (*syscall.RawSockaddr)(unsafe.Pointer(p.cur.addr))
|
||||
}
|
||||
|
||||
func (p pcapAddresses) netmask() *syscall.RawSockaddr {
|
||||
return (*syscall.RawSockaddr)(unsafe.Pointer(p.cur.netmask))
|
||||
}
|
||||
|
||||
func (p pcapAddresses) broadaddr() *syscall.RawSockaddr {
|
||||
return (*syscall.RawSockaddr)(unsafe.Pointer(p.cur.broadaddr))
|
||||
}
|
||||
|
||||
func (p pcapAddresses) dstaddr() *syscall.RawSockaddr {
|
||||
return (*syscall.RawSockaddr)(unsafe.Pointer(p.cur.dstaddr))
|
||||
}
|
||||
|
||||
func (p pcapDevices) addresses() pcapAddresses {
|
||||
return pcapAddresses{all: p.cur.addresses}
|
||||
}
|
||||
|
||||
func pcapFindAllDevs() (pcapDevices, error) {
|
||||
var buf *C.char
|
||||
buf = (*C.char)(C.calloc(errorBufferSize, 1))
|
||||
defer C.free(unsafe.Pointer(buf))
|
||||
var alldevsp pcapDevices
|
||||
|
||||
if C.pcap_findalldevs((**C.pcap_if_t)(&alldevsp.all), buf) < 0 {
|
||||
return pcapDevices{}, errors.New(C.GoString(buf))
|
||||
}
|
||||
return alldevsp, nil
|
||||
}
|
||||
|
||||
func (p *Handle) pcapSendpacket(data []byte) error {
|
||||
if C.pcap_sendpacket(p.cptr, (*C.u_char)(&data[0]), (C.int)(len(data))) < 0 {
|
||||
return p.pcapGeterr()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Handle) pcapSetdirection(direction Direction) error {
|
||||
if status := C.pcap_setdirection(p.cptr, (C.pcap_direction_t)(direction)); status < 0 {
|
||||
return statusError(status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Handle) pcapSnapshot() int {
|
||||
return int(C.pcap_snapshot(p.cptr))
|
||||
}
|
||||
|
||||
func (t TimestampSource) pcapTstampTypeValToName() string {
|
||||
return C.GoString(C.pcap_tstamp_type_val_to_name(C.int(t)))
|
||||
}
|
||||
|
||||
func pcapTstampTypeNameToVal(s string) (TimestampSource, error) {
|
||||
cs := C.CString(s)
|
||||
defer C.free(unsafe.Pointer(cs))
|
||||
t := C.pcap_tstamp_type_name_to_val(cs)
|
||||
if t < 0 {
|
||||
return 0, statusError(t)
|
||||
}
|
||||
return TimestampSource(t), nil
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapGeterr() error {
|
||||
return errors.New(C.GoString(C.pcap_geterr(p.cptr)))
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapActivate() (*Handle, activateError) {
|
||||
ret := activateError(C.pcap_activate(p.cptr))
|
||||
if ret != aeNoError {
|
||||
return nil, ret
|
||||
}
|
||||
h := &Handle{
|
||||
cptr: p.cptr,
|
||||
}
|
||||
p.cptr = nil
|
||||
return h, ret
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapClose() {
|
||||
if p.cptr != nil {
|
||||
C.pcap_close(p.cptr)
|
||||
}
|
||||
}
|
||||
|
||||
func pcapCreate(device string) (*InactiveHandle, error) {
|
||||
buf := (*C.char)(C.calloc(errorBufferSize, 1))
|
||||
defer C.free(unsafe.Pointer(buf))
|
||||
dev := C.CString(device)
|
||||
defer C.free(unsafe.Pointer(dev))
|
||||
|
||||
cptr := C.pcap_create(dev, buf)
|
||||
if cptr == nil {
|
||||
return nil, errors.New(C.GoString(buf))
|
||||
}
|
||||
return &InactiveHandle{cptr: cptr}, nil
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapSetSnaplen(snaplen int) error {
|
||||
if status := C.pcap_set_snaplen(p.cptr, C.int(snaplen)); status < 0 {
|
||||
return statusError(status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapSetPromisc(promisc bool) error {
|
||||
var pro C.int
|
||||
if promisc {
|
||||
pro = 1
|
||||
}
|
||||
if status := C.pcap_set_promisc(p.cptr, pro); status < 0 {
|
||||
return statusError(status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapSetTimeout(timeout time.Duration) error {
|
||||
if status := C.pcap_set_timeout(p.cptr, C.int(timeoutMillis(timeout))); status < 0 {
|
||||
return statusError(status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapListTstampTypes() (out []TimestampSource) {
|
||||
var types *C.int
|
||||
n := int(C.pcap_list_tstamp_types(p.cptr, &types))
|
||||
if n < 0 {
|
||||
return // public interface doesn't have error :(
|
||||
}
|
||||
defer C.pcap_free_tstamp_types(types)
|
||||
typesArray := (*[1 << 28]C.int)(unsafe.Pointer(types))
|
||||
for i := 0; i < n; i++ {
|
||||
out = append(out, TimestampSource((*typesArray)[i]))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapSetTstampType(t TimestampSource) error {
|
||||
if status := C.pcap_set_tstamp_type(p.cptr, C.int(t)); status < 0 {
|
||||
return statusError(status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapSetRfmon(monitor bool) error {
|
||||
var mon C.int
|
||||
if monitor {
|
||||
mon = 1
|
||||
}
|
||||
switch canset := C.pcap_can_set_rfmon(p.cptr); canset {
|
||||
case 0:
|
||||
return CannotSetRFMon
|
||||
case 1:
|
||||
// success
|
||||
default:
|
||||
return statusError(canset)
|
||||
}
|
||||
if status := C.pcap_set_rfmon(p.cptr, mon); status != 0 {
|
||||
return statusError(status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapSetBufferSize(bufferSize int) error {
|
||||
if status := C.pcap_set_buffer_size(p.cptr, C.int(bufferSize)); status < 0 {
|
||||
return statusError(status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapSetImmediateMode(mode bool) error {
|
||||
var md C.int
|
||||
if mode {
|
||||
md = 1
|
||||
}
|
||||
if status := C.pcap_set_immediate_mode(p.cptr, md); status < 0 {
|
||||
return statusError(status)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Handle) setNonBlocking() error {
|
||||
buf := (*C.char)(C.calloc(errorBufferSize, 1))
|
||||
defer C.free(unsafe.Pointer(buf))
|
||||
|
||||
// Change the device to non-blocking, we'll use pcap_wait to wait until the
|
||||
// handle is ready to read.
|
||||
if v := C.pcap_setnonblock(p.cptr, 1, buf); v == -1 {
|
||||
if v := C.pcap_setnonblock(p.cptr, 1, buf); v < -1 {
|
||||
return errors.New(C.GoString(buf))
|
||||
}
|
||||
|
||||
@@ -67,5 +694,20 @@ func (p *Handle) waitForPacket() {
|
||||
usec := timeoutMillis(p.timeout) * 1000
|
||||
usec -= 100
|
||||
|
||||
C.pcap_wait(p.cptr, usec)
|
||||
C.pcap_wait(p.cptr, C.int(usec))
|
||||
}
|
||||
|
||||
// openOfflineFile returns contents of input file as a *Handle.
|
||||
func openOfflineFile(file *os.File) (handle *Handle, err error) {
|
||||
buf := (*C.char)(C.calloc(errorBufferSize, 1))
|
||||
defer C.free(unsafe.Pointer(buf))
|
||||
cmode := C.CString("rb")
|
||||
defer C.free(unsafe.Pointer(cmode))
|
||||
cf := C.fdopen(C.int(file.Fd()), cmode)
|
||||
|
||||
cptr := C.pcap_fopen_offline_with_tstamp_precision(cf, C.PCAP_TSTAMP_PRECISION_NANO, buf)
|
||||
if cptr == nil {
|
||||
return nil, errors.New(C.GoString(buf))
|
||||
}
|
||||
return &Handle{cptr: cptr}, nil
|
||||
}
|
||||
+788
-1
@@ -8,10 +8,779 @@
|
||||
package pcap
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/google/gopacket"
|
||||
"github.com/google/gopacket/layers"
|
||||
)
|
||||
|
||||
func (p *Handle) openLive() error {
|
||||
const npcapPath = "\\Npcap"
|
||||
|
||||
func initDllPath(kernel32 syscall.Handle) {
|
||||
setDllDirectory, err := syscall.GetProcAddress(kernel32, "SetDllDirectoryA")
|
||||
if err != nil {
|
||||
// we can't do anything since SetDllDirectoryA is missing - fall back to use first wpcap.dll we encounter
|
||||
return
|
||||
}
|
||||
getSystemDirectory, err := syscall.GetProcAddress(kernel32, "GetSystemDirectoryA")
|
||||
if err != nil {
|
||||
// we can't do anything since SetDllDirectoryA is missing - fall back to use first wpcap.dll we encounter
|
||||
return
|
||||
}
|
||||
buf := make([]byte, 4096)
|
||||
r, _, _ := syscall.Syscall(getSystemDirectory, 2, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), 0)
|
||||
if r == 0 || r > 4096-uintptr(len(npcapPath))-1 {
|
||||
// we can't do anything since SetDllDirectoryA is missing - fall back to use first wpcap.dll we encounter
|
||||
return
|
||||
}
|
||||
copy(buf[r:], npcapPath)
|
||||
_, _, _ = syscall.Syscall(setDllDirectory, 1, uintptr(unsafe.Pointer(&buf[0])), 0, 0)
|
||||
// ignore errors here - we just fallback to load wpcap.dll from default locations
|
||||
}
|
||||
|
||||
// loadedDllPath will hold the full pathname of the loaded wpcap.dll after init if possible
|
||||
var loadedDllPath = "wpcap.dll"
|
||||
|
||||
func initLoadedDllPath(kernel32 syscall.Handle) {
|
||||
getModuleFileName, err := syscall.GetProcAddress(kernel32, "GetModuleFileNameA")
|
||||
if err != nil {
|
||||
// we can't get the filename of the loaded module in this case - just leave default of wpcap.dll
|
||||
return
|
||||
}
|
||||
buf := make([]byte, 4096)
|
||||
r, _, _ := syscall.Syscall(getModuleFileName, 3, uintptr(wpcapHandle), uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
|
||||
if r == 0 {
|
||||
// we can't get the filename of the loaded module in this case - just leave default of wpcap.dll
|
||||
return
|
||||
}
|
||||
loadedDllPath = string(buf[:int(r)])
|
||||
}
|
||||
|
||||
func mustLoad(fun string) uintptr {
|
||||
addr, err := syscall.GetProcAddress(wpcapHandle, fun)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("Couldn't load function %s from %s", fun, loadedDllPath))
|
||||
}
|
||||
return addr
|
||||
}
|
||||
|
||||
func mightLoad(fun string) uintptr {
|
||||
addr, err := syscall.GetProcAddress(wpcapHandle, fun)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return addr
|
||||
}
|
||||
|
||||
func byteSliceToString(bval []byte) string {
|
||||
for i := range bval {
|
||||
if bval[i] == 0 {
|
||||
return string(bval[:i])
|
||||
}
|
||||
}
|
||||
return string(bval[:])
|
||||
}
|
||||
|
||||
// bytePtrToString returns a string copied from pointer to a null terminated byte array
|
||||
// WARNING: ONLY SAFE WITH IF r POINTS TO C MEMORY!
|
||||
// govet will complain about this function for the reason stated above
|
||||
func bytePtrToString(r uintptr) string {
|
||||
if r == 0 {
|
||||
return ""
|
||||
}
|
||||
bval := (*[1 << 30]byte)(unsafe.Pointer(r))
|
||||
return byteSliceToString(bval[:])
|
||||
}
|
||||
|
||||
var wpcapHandle syscall.Handle
|
||||
var msvcrtHandle syscall.Handle
|
||||
var (
|
||||
callocPtr,
|
||||
pcapStrerrorPtr,
|
||||
pcapStatustostrPtr,
|
||||
pcapOpenLivePtr,
|
||||
pcapOpenOfflinePtr,
|
||||
pcapClosePtr,
|
||||
pcapGeterrPtr,
|
||||
pcapStatsPtr,
|
||||
pcapCompilePtr,
|
||||
pcapFreecodePtr,
|
||||
pcapLookupnetPtr,
|
||||
pcapOfflineFilterPtr,
|
||||
pcapSetfilterPtr,
|
||||
pcapListDatalinksPtr,
|
||||
pcapFreeDatalinksPtr,
|
||||
pcapDatalinkValToNamePtr,
|
||||
pcapDatalinkValToDescriptionPtr,
|
||||
pcapOpenDeadPtr,
|
||||
pcapNextExPtr,
|
||||
pcapDatalinkPtr,
|
||||
pcapSetDatalinkPtr,
|
||||
pcapDatalinkNameToValPtr,
|
||||
pcapLibVersionPtr,
|
||||
pcapFreealldevsPtr,
|
||||
pcapFindalldevsPtr,
|
||||
pcapSendpacketPtr,
|
||||
pcapSetdirectionPtr,
|
||||
pcapSnapshotPtr,
|
||||
pcapTstampTypeValToNamePtr,
|
||||
pcapTstampTypeNameToValPtr,
|
||||
pcapListTstampTypesPtr,
|
||||
pcapFreeTstampTypesPtr,
|
||||
pcapSetTstampTypePtr,
|
||||
pcapGetTstampPrecisionPtr,
|
||||
pcapSetTstampPrecisionPtr,
|
||||
pcapOpenOfflineWithTstampPrecisionPtr,
|
||||
pcapHOpenOfflineWithTstampPrecisionPtr,
|
||||
pcapActivatePtr,
|
||||
pcapCreatePtr,
|
||||
pcapSetSnaplenPtr,
|
||||
pcapSetPromiscPtr,
|
||||
pcapSetTimeoutPtr,
|
||||
pcapCanSetRfmonPtr,
|
||||
pcapSetRfmonPtr,
|
||||
pcapSetBufferSizePtr,
|
||||
pcapSetImmediateModePtr,
|
||||
pcapHopenOfflinePtr uintptr
|
||||
)
|
||||
|
||||
func init() {
|
||||
kernel32, err := syscall.LoadLibrary("kernel32.dll")
|
||||
if err != nil {
|
||||
panic("couldn't load kernel32.dll")
|
||||
}
|
||||
defer syscall.FreeLibrary(kernel32)
|
||||
|
||||
initDllPath(kernel32)
|
||||
|
||||
wpcapHandle, err = syscall.LoadLibrary("wpcap.dll")
|
||||
if err != nil {
|
||||
panic("Couldn't load wpcap.dll")
|
||||
}
|
||||
initLoadedDllPath(kernel32)
|
||||
msvcrtHandle, err = syscall.LoadLibrary("msvcrt.dll")
|
||||
if err != nil {
|
||||
panic("Couldn't load msvcrt.dll")
|
||||
}
|
||||
callocPtr, err = syscall.GetProcAddress(msvcrtHandle, "calloc")
|
||||
if err != nil {
|
||||
panic("Couldn't get calloc function")
|
||||
}
|
||||
|
||||
pcapStrerrorPtr = mustLoad("pcap_strerror")
|
||||
pcapStatustostrPtr = mightLoad("pcap_statustostr") // not available on winpcap
|
||||
pcapOpenLivePtr = mustLoad("pcap_open_live")
|
||||
pcapOpenOfflinePtr = mustLoad("pcap_open_offline")
|
||||
pcapClosePtr = mustLoad("pcap_close")
|
||||
pcapGeterrPtr = mustLoad("pcap_geterr")
|
||||
pcapStatsPtr = mustLoad("pcap_stats")
|
||||
pcapCompilePtr = mustLoad("pcap_compile")
|
||||
pcapFreecodePtr = mustLoad("pcap_freecode")
|
||||
pcapLookupnetPtr = mustLoad("pcap_lookupnet")
|
||||
pcapOfflineFilterPtr = mustLoad("pcap_offline_filter")
|
||||
pcapSetfilterPtr = mustLoad("pcap_setfilter")
|
||||
pcapListDatalinksPtr = mustLoad("pcap_list_datalinks")
|
||||
pcapFreeDatalinksPtr = mustLoad("pcap_free_datalinks")
|
||||
pcapDatalinkValToNamePtr = mustLoad("pcap_datalink_val_to_name")
|
||||
pcapDatalinkValToDescriptionPtr = mustLoad("pcap_datalink_val_to_description")
|
||||
pcapOpenDeadPtr = mustLoad("pcap_open_dead")
|
||||
pcapNextExPtr = mustLoad("pcap_next_ex")
|
||||
pcapDatalinkPtr = mustLoad("pcap_datalink")
|
||||
pcapSetDatalinkPtr = mustLoad("pcap_set_datalink")
|
||||
pcapDatalinkNameToValPtr = mustLoad("pcap_datalink_name_to_val")
|
||||
pcapLibVersionPtr = mustLoad("pcap_lib_version")
|
||||
pcapFreealldevsPtr = mustLoad("pcap_freealldevs")
|
||||
pcapFindalldevsPtr = mustLoad("pcap_findalldevs")
|
||||
pcapSendpacketPtr = mustLoad("pcap_sendpacket")
|
||||
pcapSetdirectionPtr = mustLoad("pcap_setdirection")
|
||||
pcapSnapshotPtr = mustLoad("pcap_snapshot")
|
||||
//libpcap <1.2 doesn't have pcap_*_tstamp_* functions
|
||||
pcapTstampTypeValToNamePtr = mightLoad("pcap_tstamp_type_val_to_name")
|
||||
pcapTstampTypeNameToValPtr = mightLoad("pcap_tstamp_type_name_to_val")
|
||||
pcapListTstampTypesPtr = mightLoad("pcap_list_tstamp_types")
|
||||
pcapFreeTstampTypesPtr = mightLoad("pcap_free_tstamp_types")
|
||||
pcapSetTstampTypePtr = mightLoad("pcap_set_tstamp_type")
|
||||
pcapGetTstampPrecisionPtr = mightLoad("pcap_get_tstamp_precision")
|
||||
pcapSetTstampPrecisionPtr = mightLoad("pcap_set_tstamp_precision")
|
||||
pcapOpenOfflineWithTstampPrecisionPtr = mightLoad("pcap_open_offline_with_tstamp_precision")
|
||||
pcapHOpenOfflineWithTstampPrecisionPtr = mightLoad("pcap_hopen_offline_with_tstamp_precision")
|
||||
pcapActivatePtr = mustLoad("pcap_activate")
|
||||
pcapCreatePtr = mustLoad("pcap_create")
|
||||
pcapSetSnaplenPtr = mustLoad("pcap_set_snaplen")
|
||||
pcapSetPromiscPtr = mustLoad("pcap_set_promisc")
|
||||
pcapSetTimeoutPtr = mustLoad("pcap_set_timeout")
|
||||
//winpcap does not support rfmon
|
||||
pcapCanSetRfmonPtr = mightLoad("pcap_can_set_rfmon")
|
||||
pcapSetRfmonPtr = mightLoad("pcap_set_rfmon")
|
||||
pcapSetBufferSizePtr = mustLoad("pcap_set_buffer_size")
|
||||
//libpcap <1.5 does not have pcap_set_immediate_mode
|
||||
pcapSetImmediateModePtr = mightLoad("pcap_set_immediate_mode")
|
||||
pcapHopenOfflinePtr = mustLoad("pcap_hopen_offline")
|
||||
}
|
||||
|
||||
func (h *pcapPkthdr) getSec() int64 {
|
||||
return int64(h.Ts.Sec)
|
||||
}
|
||||
|
||||
func (h *pcapPkthdr) getUsec() int64 {
|
||||
return int64(h.Ts.Usec)
|
||||
}
|
||||
|
||||
func (h *pcapPkthdr) getLen() int {
|
||||
return int(h.Len)
|
||||
}
|
||||
|
||||
func (h *pcapPkthdr) getCaplen() int {
|
||||
return int(h.Caplen)
|
||||
}
|
||||
|
||||
func statusError(status pcapCint) error {
|
||||
var ret uintptr
|
||||
if pcapStatustostrPtr == 0 {
|
||||
ret, _, _ = syscall.Syscall(pcapStrerrorPtr, 1, uintptr(status), 0, 0)
|
||||
} else {
|
||||
ret, _, _ = syscall.Syscall(pcapStatustostrPtr, 1, uintptr(status), 0, 0)
|
||||
}
|
||||
return errors.New(bytePtrToString(ret))
|
||||
}
|
||||
|
||||
func pcapGetTstampPrecision(cptr pcapTPtr) int {
|
||||
if pcapGetTstampPrecisionPtr == 0 {
|
||||
return pcapTstampPrecisionMicro
|
||||
}
|
||||
ret, _, _ := syscall.Syscall(pcapGetTstampPrecisionPtr, 1, uintptr(cptr), 0, 0)
|
||||
return int(pcapCint(ret))
|
||||
}
|
||||
|
||||
func pcapSetTstampPrecision(cptr pcapTPtr, precision int) error {
|
||||
if pcapSetTstampPrecisionPtr == 0 {
|
||||
return errors.New("Not supported")
|
||||
}
|
||||
ret, _, _ := syscall.Syscall(pcapSetTstampPrecisionPtr, 2, uintptr(cptr), uintptr(precision), 0)
|
||||
if pcapCint(ret) < 0 {
|
||||
return errors.New("Not supported")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func pcapOpenLive(device string, snaplen int, pro int, timeout int) (*Handle, error) {
|
||||
buf := make([]byte, errorBufferSize)
|
||||
dev, err := syscall.BytePtrFromString(device)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cptr, _, _ := syscall.Syscall6(pcapOpenLivePtr, 5, uintptr(unsafe.Pointer(dev)), uintptr(snaplen), uintptr(pro), uintptr(timeout), uintptr(unsafe.Pointer(&buf[0])), 0)
|
||||
|
||||
if cptr == 0 {
|
||||
return nil, errors.New(byteSliceToString(buf))
|
||||
}
|
||||
return &Handle{cptr: pcapTPtr(cptr)}, nil
|
||||
}
|
||||
|
||||
func openOffline(file string) (handle *Handle, err error) {
|
||||
buf := make([]byte, errorBufferSize)
|
||||
f, err := syscall.BytePtrFromString(file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var cptr uintptr
|
||||
if pcapOpenOfflineWithTstampPrecisionPtr == 0 {
|
||||
cptr, _, _ = syscall.Syscall(pcapOpenOfflinePtr, 2, uintptr(unsafe.Pointer(f)), uintptr(unsafe.Pointer(&buf[0])), 0)
|
||||
} else {
|
||||
cptr, _, _ = syscall.Syscall(pcapOpenOfflineWithTstampPrecisionPtr, 3, uintptr(unsafe.Pointer(f)), uintptr(pcapTstampPrecisionNano), uintptr(unsafe.Pointer(&buf[0])))
|
||||
}
|
||||
|
||||
if cptr == 0 {
|
||||
return nil, errors.New(byteSliceToString(buf))
|
||||
}
|
||||
|
||||
h := &Handle{cptr: pcapTPtr(cptr)}
|
||||
return h, nil
|
||||
}
|
||||
|
||||
func (p *Handle) pcapClose() {
|
||||
if p.cptr != 0 {
|
||||
_, _, _ = syscall.Syscall(pcapClosePtr, 1, uintptr(p.cptr), 0, 0)
|
||||
}
|
||||
p.cptr = 0
|
||||
}
|
||||
|
||||
func (p *Handle) pcapGeterr() error {
|
||||
ret, _, _ := syscall.Syscall(pcapGeterrPtr, 1, uintptr(p.cptr), 0, 0)
|
||||
return errors.New(bytePtrToString(ret))
|
||||
}
|
||||
|
||||
func (p *Handle) pcapStats() (*Stats, error) {
|
||||
var cstats pcapStats
|
||||
ret, _, _ := syscall.Syscall(pcapStatsPtr, 2, uintptr(p.cptr), uintptr(unsafe.Pointer(&cstats)), 0)
|
||||
if pcapCint(ret) < 0 {
|
||||
return nil, p.pcapGeterr()
|
||||
}
|
||||
return &Stats{
|
||||
PacketsReceived: int(cstats.Recv),
|
||||
PacketsDropped: int(cstats.Drop),
|
||||
PacketsIfDropped: int(cstats.Ifdrop),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// for libpcap < 1.8 pcap_compile is NOT thread-safe, so protect it.
|
||||
var pcapCompileMu sync.Mutex
|
||||
|
||||
func (p *Handle) pcapCompile(expr string, maskp uint32) (pcapBpfProgram, error) {
|
||||
var bpf pcapBpfProgram
|
||||
cexpr, err := syscall.BytePtrFromString(expr)
|
||||
if err != nil {
|
||||
return pcapBpfProgram{}, err
|
||||
}
|
||||
pcapCompileMu.Lock()
|
||||
defer pcapCompileMu.Unlock()
|
||||
res, _, _ := syscall.Syscall6(pcapCompilePtr, 5, uintptr(p.cptr), uintptr(unsafe.Pointer(&bpf)), uintptr(unsafe.Pointer(cexpr)), uintptr(1), uintptr(maskp), 0)
|
||||
if pcapCint(res) < 0 {
|
||||
return bpf, p.pcapGeterr()
|
||||
}
|
||||
return bpf, nil
|
||||
}
|
||||
|
||||
func (p pcapBpfProgram) free() {
|
||||
_, _, _ = syscall.Syscall(pcapFreecodePtr, 1, uintptr(unsafe.Pointer(&p)), 0, 0)
|
||||
}
|
||||
|
||||
func (p pcapBpfProgram) toBPFInstruction() []BPFInstruction {
|
||||
bpfInsn := (*[bpfInstructionBufferSize]pcapBpfInstruction)(unsafe.Pointer(p.Insns))[0:p.Len:p.Len]
|
||||
bpfInstruction := make([]BPFInstruction, len(bpfInsn), len(bpfInsn))
|
||||
|
||||
for i, v := range bpfInsn {
|
||||
bpfInstruction[i].Code = v.Code
|
||||
bpfInstruction[i].Jt = v.Jt
|
||||
bpfInstruction[i].Jf = v.Jf
|
||||
bpfInstruction[i].K = v.K
|
||||
}
|
||||
return bpfInstruction
|
||||
}
|
||||
|
||||
func pcapBpfProgramFromInstructions(bpfInstructions []BPFInstruction) pcapBpfProgram {
|
||||
var bpf pcapBpfProgram
|
||||
bpf.Len = uint32(len(bpfInstructions))
|
||||
cbpfInsns, _, _ := syscall.Syscall(callocPtr, 2, uintptr(len(bpfInstructions)), uintptr(unsafe.Sizeof(bpfInstructions[0])), 0)
|
||||
gbpfInsns := (*[bpfInstructionBufferSize]pcapBpfInstruction)(unsafe.Pointer(cbpfInsns))
|
||||
|
||||
for i, v := range bpfInstructions {
|
||||
gbpfInsns[i].Code = v.Code
|
||||
gbpfInsns[i].Jt = v.Jt
|
||||
gbpfInsns[i].Jf = v.Jf
|
||||
gbpfInsns[i].K = v.K
|
||||
}
|
||||
|
||||
bpf.Insns = (*pcapBpfInstruction)(unsafe.Pointer(cbpfInsns))
|
||||
return bpf
|
||||
}
|
||||
|
||||
func pcapLookupnet(device string) (netp, maskp uint32, err error) {
|
||||
buf := make([]byte, errorBufferSize)
|
||||
dev, err := syscall.BytePtrFromString(device)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
e, _, _ := syscall.Syscall6(pcapLookupnetPtr, 4, uintptr(unsafe.Pointer(dev)), uintptr(unsafe.Pointer(&netp)), uintptr(unsafe.Pointer(&maskp)), uintptr(unsafe.Pointer(&buf[0])), 0, 0)
|
||||
if pcapCint(e) < 0 {
|
||||
return 0, 0, errors.New(byteSliceToString(buf))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (b *BPF) pcapOfflineFilter(ci gopacket.CaptureInfo, data []byte) bool {
|
||||
var hdr pcapPkthdr
|
||||
hdr.Ts.Sec = int32(ci.Timestamp.Unix())
|
||||
hdr.Ts.Usec = int32(ci.Timestamp.Nanosecond() / 1000)
|
||||
hdr.Caplen = uint32(len(data)) // Trust actual length over ci.Length.
|
||||
hdr.Len = uint32(ci.Length)
|
||||
e, _, _ := syscall.Syscall(pcapOfflineFilterPtr, 3, uintptr(unsafe.Pointer(&b.bpf)), uintptr(unsafe.Pointer(&hdr)), uintptr(unsafe.Pointer(&data[0])))
|
||||
return e != 0
|
||||
}
|
||||
|
||||
func (p *Handle) pcapSetfilter(bpf pcapBpfProgram) error {
|
||||
e, _, _ := syscall.Syscall(pcapSetfilterPtr, 2, uintptr(p.cptr), uintptr(unsafe.Pointer(&bpf)), 0)
|
||||
if pcapCint(e) < 0 {
|
||||
return p.pcapGeterr()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Handle) pcapListDatalinks() (datalinks []Datalink, err error) {
|
||||
var dltbuf *pcapCint
|
||||
ret, _, _ := syscall.Syscall(pcapListDatalinksPtr, 2, uintptr(p.cptr), uintptr(unsafe.Pointer(&dltbuf)), 0)
|
||||
|
||||
n := int(pcapCint(ret))
|
||||
|
||||
if n < 0 {
|
||||
return nil, p.pcapGeterr()
|
||||
}
|
||||
defer syscall.Syscall(pcapFreeDatalinksPtr, 1, uintptr(unsafe.Pointer(dltbuf)), 0, 0)
|
||||
|
||||
datalinks = make([]Datalink, n)
|
||||
|
||||
dltArray := (*[1 << 28]pcapCint)(unsafe.Pointer(dltbuf))
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
datalinks[i].Name = pcapDatalinkValToName(int((*dltArray)[i]))
|
||||
datalinks[i].Description = pcapDatalinkValToDescription(int((*dltArray)[i]))
|
||||
}
|
||||
|
||||
return datalinks, nil
|
||||
}
|
||||
|
||||
func pcapOpenDead(linkType layers.LinkType, captureLength int) (*Handle, error) {
|
||||
cptr, _, _ := syscall.Syscall(pcapOpenDeadPtr, 2, uintptr(linkType), uintptr(captureLength), 0)
|
||||
if cptr == 0 {
|
||||
return nil, errors.New("error opening dead capture")
|
||||
}
|
||||
|
||||
return &Handle{cptr: pcapTPtr(cptr)}, nil
|
||||
}
|
||||
|
||||
func (p *Handle) pcapNextPacketEx() NextError {
|
||||
r, _, _ := syscall.Syscall(pcapNextExPtr, 3, uintptr(p.cptr), uintptr(unsafe.Pointer(&p.pkthdr)), uintptr(unsafe.Pointer(&p.bufptr)))
|
||||
ret := pcapCint(r)
|
||||
// According to https://github.com/the-tcpdump-group/libpcap/blob/1131a7c26c6f4d4772e4a2beeaf7212f4dea74ac/pcap.c#L398-L406 ,
|
||||
// the return value of pcap_next_ex could be greater than 1 for success.
|
||||
// Let's just make it 1 if it comes bigger than 1.
|
||||
if ret > 1 {
|
||||
ret = 1
|
||||
}
|
||||
return NextError(ret)
|
||||
}
|
||||
|
||||
func (p *Handle) pcapDatalink() layers.LinkType {
|
||||
ret, _, _ := syscall.Syscall(pcapDatalinkPtr, 1, uintptr(p.cptr), 0, 0)
|
||||
return layers.LinkType(ret)
|
||||
}
|
||||
|
||||
func (p *Handle) pcapSetDatalink(dlt layers.LinkType) error {
|
||||
ret, _, _ := syscall.Syscall(pcapSetDatalinkPtr, 2, uintptr(p.cptr), uintptr(dlt), 0)
|
||||
if pcapCint(ret) < 0 {
|
||||
return p.pcapGeterr()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func pcapDatalinkValToName(dlt int) string {
|
||||
ret, _, _ := syscall.Syscall(pcapDatalinkValToNamePtr, 1, uintptr(dlt), 0, 0)
|
||||
return bytePtrToString(ret)
|
||||
}
|
||||
|
||||
func pcapDatalinkValToDescription(dlt int) string {
|
||||
ret, _, _ := syscall.Syscall(pcapDatalinkValToDescriptionPtr, 1, uintptr(dlt), 0, 0)
|
||||
return bytePtrToString(ret)
|
||||
}
|
||||
|
||||
func pcapDatalinkNameToVal(name string) int {
|
||||
cptr, err := syscall.BytePtrFromString(name)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
ret, _, _ := syscall.Syscall(pcapDatalinkNameToValPtr, 1, uintptr(unsafe.Pointer(cptr)), 0, 0)
|
||||
return int(pcapCint(ret))
|
||||
}
|
||||
|
||||
func pcapLibVersion() string {
|
||||
ret, _, _ := syscall.Syscall(pcapLibVersionPtr, 0, 0, 0, 0)
|
||||
return bytePtrToString(ret)
|
||||
}
|
||||
|
||||
func (p *Handle) isOpen() bool {
|
||||
return p.cptr != 0
|
||||
}
|
||||
|
||||
type pcapDevices struct {
|
||||
all, cur *pcapIf
|
||||
}
|
||||
|
||||
func (p pcapDevices) free() {
|
||||
syscall.Syscall(pcapFreealldevsPtr, 1, uintptr(unsafe.Pointer(p.all)), 0, 0)
|
||||
}
|
||||
|
||||
func (p *pcapDevices) next() bool {
|
||||
if p.cur == nil {
|
||||
p.cur = p.all
|
||||
if p.cur == nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
if p.cur.Next == nil {
|
||||
return false
|
||||
}
|
||||
p.cur = p.cur.Next
|
||||
return true
|
||||
}
|
||||
|
||||
func (p pcapDevices) name() string {
|
||||
return bytePtrToString(uintptr(unsafe.Pointer(p.cur.Name)))
|
||||
}
|
||||
|
||||
func (p pcapDevices) description() string {
|
||||
return bytePtrToString(uintptr(unsafe.Pointer(p.cur.Description)))
|
||||
}
|
||||
|
||||
func (p pcapDevices) flags() uint32 {
|
||||
return p.cur.Flags
|
||||
}
|
||||
|
||||
type pcapAddresses struct {
|
||||
all, cur *pcapAddr
|
||||
}
|
||||
|
||||
func (p *pcapAddresses) next() bool {
|
||||
if p.cur == nil {
|
||||
p.cur = p.all
|
||||
if p.cur == nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
if p.cur.Next == nil {
|
||||
return false
|
||||
}
|
||||
p.cur = p.cur.Next
|
||||
return true
|
||||
}
|
||||
|
||||
func (p pcapAddresses) addr() *syscall.RawSockaddr {
|
||||
return p.cur.Addr
|
||||
}
|
||||
|
||||
func (p pcapAddresses) netmask() *syscall.RawSockaddr {
|
||||
return p.cur.Netmask
|
||||
}
|
||||
|
||||
func (p pcapAddresses) broadaddr() *syscall.RawSockaddr {
|
||||
return p.cur.Broadaddr
|
||||
}
|
||||
|
||||
func (p pcapAddresses) dstaddr() *syscall.RawSockaddr {
|
||||
return p.cur.Dstaddr
|
||||
}
|
||||
|
||||
func (p pcapDevices) addresses() pcapAddresses {
|
||||
return pcapAddresses{all: p.cur.Addresses}
|
||||
}
|
||||
|
||||
func pcapFindAllDevs() (pcapDevices, error) {
|
||||
buf := make([]byte, errorBufferSize)
|
||||
var alldevsp pcapDevices
|
||||
|
||||
ret, _, _ := syscall.Syscall(pcapFindalldevsPtr, 2, uintptr(unsafe.Pointer(&alldevsp.all)), uintptr(unsafe.Pointer(&buf[0])), 0)
|
||||
|
||||
if pcapCint(ret) < 0 {
|
||||
return pcapDevices{}, errors.New(byteSliceToString(buf))
|
||||
}
|
||||
return alldevsp, nil
|
||||
}
|
||||
|
||||
func (p *Handle) pcapSendpacket(data []byte) error {
|
||||
ret, _, _ := syscall.Syscall(pcapSendpacketPtr, 3, uintptr(p.cptr), uintptr(unsafe.Pointer(&data[0])), uintptr(len(data)))
|
||||
if pcapCint(ret) < 0 {
|
||||
return p.pcapGeterr()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Handle) pcapSetdirection(direction Direction) error {
|
||||
status, _, _ := syscall.Syscall(pcapSetdirectionPtr, 2, uintptr(p.cptr), uintptr(direction), 0)
|
||||
if pcapCint(status) < 0 {
|
||||
return statusError(pcapCint(status))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Handle) pcapSnapshot() int {
|
||||
ret, _, _ := syscall.Syscall(pcapSnapshotPtr, 1, uintptr(p.cptr), 0, 0)
|
||||
return int(pcapCint(ret))
|
||||
}
|
||||
|
||||
func (t TimestampSource) pcapTstampTypeValToName() string {
|
||||
//libpcap <1.2 doesn't have pcap_*_tstamp_* functions
|
||||
if pcapTstampTypeValToNamePtr == 0 {
|
||||
return "pcap timestamp types not supported"
|
||||
}
|
||||
ret, _, _ := syscall.Syscall(pcapTstampTypeValToNamePtr, 1, uintptr(t), 0, 0)
|
||||
return bytePtrToString(ret)
|
||||
}
|
||||
|
||||
func pcapTstampTypeNameToVal(s string) (TimestampSource, error) {
|
||||
//libpcap <1.2 doesn't have pcap_*_tstamp_* functions
|
||||
if pcapTstampTypeNameToValPtr == 0 {
|
||||
return 0, statusError(pcapCint(pcapError))
|
||||
}
|
||||
cs, err := syscall.BytePtrFromString(s)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
ret, _, _ := syscall.Syscall(pcapTstampTypeNameToValPtr, 1, uintptr(unsafe.Pointer(cs)), 0, 0)
|
||||
t := pcapCint(ret)
|
||||
if t < 0 {
|
||||
return 0, statusError(pcapCint(t))
|
||||
}
|
||||
return TimestampSource(t), nil
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapGeterr() error {
|
||||
ret, _, _ := syscall.Syscall(pcapGeterrPtr, 1, uintptr(p.cptr), 0, 0)
|
||||
return errors.New(bytePtrToString(ret))
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapActivate() (*Handle, activateError) {
|
||||
r, _, _ := syscall.Syscall(pcapActivatePtr, 1, uintptr(p.cptr), 0, 0)
|
||||
ret := activateError(pcapCint(r))
|
||||
if ret != aeNoError {
|
||||
return nil, ret
|
||||
}
|
||||
h := &Handle{
|
||||
cptr: p.cptr,
|
||||
}
|
||||
p.cptr = 0
|
||||
return h, ret
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapClose() {
|
||||
if p.cptr != 0 {
|
||||
_, _, _ = syscall.Syscall(pcapClosePtr, 1, uintptr(p.cptr), 0, 0)
|
||||
}
|
||||
p.cptr = 0
|
||||
}
|
||||
|
||||
func pcapCreate(device string) (*InactiveHandle, error) {
|
||||
buf := make([]byte, errorBufferSize)
|
||||
dev, err := syscall.BytePtrFromString(device)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cptr, _, _ := syscall.Syscall(pcapCreatePtr, 2, uintptr(unsafe.Pointer(dev)), uintptr(unsafe.Pointer(&buf[0])), 0)
|
||||
if cptr == 0 {
|
||||
return nil, errors.New(byteSliceToString(buf))
|
||||
}
|
||||
return &InactiveHandle{cptr: pcapTPtr(cptr)}, nil
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapSetSnaplen(snaplen int) error {
|
||||
status, _, _ := syscall.Syscall(pcapSetSnaplenPtr, 2, uintptr(p.cptr), uintptr(snaplen), 0)
|
||||
if pcapCint(status) < 0 {
|
||||
return statusError(pcapCint(status))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapSetPromisc(promisc bool) error {
|
||||
var pro uintptr
|
||||
if promisc {
|
||||
pro = 1
|
||||
}
|
||||
status, _, _ := syscall.Syscall(pcapSetPromiscPtr, 2, uintptr(p.cptr), pro, 0)
|
||||
if pcapCint(status) < 0 {
|
||||
return statusError(pcapCint(status))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapSetTimeout(timeout time.Duration) error {
|
||||
status, _, _ := syscall.Syscall(pcapSetTimeoutPtr, 2, uintptr(p.cptr), uintptr(timeoutMillis(timeout)), 0)
|
||||
|
||||
if pcapCint(status) < 0 {
|
||||
return statusError(pcapCint(status))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapListTstampTypes() (out []TimestampSource) {
|
||||
//libpcap <1.2 doesn't have pcap_*_tstamp_* functions
|
||||
if pcapListTstampTypesPtr == 0 {
|
||||
return
|
||||
}
|
||||
var types *pcapCint
|
||||
ret, _, _ := syscall.Syscall(pcapListTstampTypesPtr, 2, uintptr(p.cptr), uintptr(unsafe.Pointer(&types)), 0)
|
||||
n := int(pcapCint(ret))
|
||||
if n < 0 {
|
||||
return // public interface doesn't have error :(
|
||||
}
|
||||
defer syscall.Syscall(pcapFreeTstampTypesPtr, 1, uintptr(unsafe.Pointer(types)), 0, 0)
|
||||
typesArray := (*[1 << 28]pcapCint)(unsafe.Pointer(types))
|
||||
for i := 0; i < n; i++ {
|
||||
out = append(out, TimestampSource((*typesArray)[i]))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapSetTstampType(t TimestampSource) error {
|
||||
//libpcap <1.2 doesn't have pcap_*_tstamp_* functions
|
||||
if pcapSetTstampTypePtr == 0 {
|
||||
return statusError(pcapError)
|
||||
}
|
||||
status, _, _ := syscall.Syscall(pcapSetTstampTypePtr, 2, uintptr(p.cptr), uintptr(t), 0)
|
||||
if pcapCint(status) < 0 {
|
||||
return statusError(pcapCint(status))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapSetRfmon(monitor bool) error {
|
||||
//winpcap does not support rfmon
|
||||
if pcapCanSetRfmonPtr == 0 {
|
||||
return CannotSetRFMon
|
||||
}
|
||||
var mon uintptr
|
||||
if monitor {
|
||||
mon = 1
|
||||
}
|
||||
canset, _, _ := syscall.Syscall(pcapCanSetRfmonPtr, 1, uintptr(p.cptr), 0, 0)
|
||||
switch canset {
|
||||
case 0:
|
||||
return CannotSetRFMon
|
||||
case 1:
|
||||
// success
|
||||
default:
|
||||
return statusError(pcapCint(canset))
|
||||
}
|
||||
status, _, _ := syscall.Syscall(pcapSetRfmonPtr, 2, uintptr(p.cptr), mon, 0)
|
||||
if status != 0 {
|
||||
return statusError(pcapCint(status))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapSetBufferSize(bufferSize int) error {
|
||||
status, _, _ := syscall.Syscall(pcapSetBufferSizePtr, 2, uintptr(p.cptr), uintptr(bufferSize), 0)
|
||||
if pcapCint(status) < 0 {
|
||||
return statusError(pcapCint(status))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *InactiveHandle) pcapSetImmediateMode(mode bool) error {
|
||||
//libpcap <1.5 does not have pcap_set_immediate_mode
|
||||
if pcapSetImmediateModePtr == 0 {
|
||||
return statusError(pcapError)
|
||||
}
|
||||
var md uintptr
|
||||
if mode {
|
||||
md = 1
|
||||
}
|
||||
status, _, _ := syscall.Syscall(pcapSetImmediateModePtr, 2, uintptr(p.cptr), md, 0)
|
||||
if pcapCint(status) < 0 {
|
||||
return statusError(pcapCint(status))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Handle) setNonBlocking() error {
|
||||
// do nothing
|
||||
return nil
|
||||
}
|
||||
@@ -21,3 +790,21 @@ func (p *Handle) waitForPacket() {
|
||||
// can't use select() so instead just switch goroutines
|
||||
runtime.Gosched()
|
||||
}
|
||||
|
||||
// openOfflineFile returns contents of input file as a *Handle.
|
||||
func openOfflineFile(file *os.File) (handle *Handle, err error) {
|
||||
buf := make([]byte, errorBufferSize)
|
||||
cf := file.Fd()
|
||||
|
||||
var cptr uintptr
|
||||
if pcapOpenOfflineWithTstampPrecisionPtr == 0 {
|
||||
cptr, _, _ = syscall.Syscall(pcapHopenOfflinePtr, 2, cf, uintptr(unsafe.Pointer(&buf[0])), 0)
|
||||
} else {
|
||||
cptr, _, _ = syscall.Syscall(pcapHOpenOfflineWithTstampPrecisionPtr, 3, cf, uintptr(pcapTstampPrecisionNano), uintptr(unsafe.Pointer(&buf[0])))
|
||||
}
|
||||
|
||||
if cptr == 0 {
|
||||
return nil, errors.New(byteSliceToString(buf))
|
||||
}
|
||||
return &Handle{cptr: pcapTPtr(cptr)}, nil
|
||||
}
|
||||
BIN
Binary file not shown.
Reference in new issue
Block a user