Vendor update gopacket and unix package

This commit is contained in:
Manjunath A Kumatagi committed 2019-02-01 21:28:56 -06:00
1 parent 54d24e65ef
commit 43d3339b39
319 files changed
+91339 -13246

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
language: go
go:
- "1.x"
os:
- linux
- osx
before_install:
- go get golang.org/x/lint/golint
- go get honnef.co/go/tools/cmd/staticcheck
- go get -d -t ./...
script:
- go build -tags=gofuzz ./...
- go vet ./...
- staticcheck -ignore 'github.com/mdlayher/raw/raw_bsd.go:SA1019' ./...
- golint -set_exit_status ./...
- go test -v -race ./...
+10
View File
@@ -0,0 +1,10 @@
MIT License
===========
Copyright (C) 2015 Matt Layher
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+12
View File
@@ -0,0 +1,12 @@
raw [![Build Status](https://travis-ci.org/mdlayher/raw.svg?branch=master)](https://travis-ci.org/mdlayher/raw) [![GoDoc](https://godoc.org/github.com/mdlayher/raw?status.svg)](https://godoc.org/github.com/mdlayher/raw) [![Go Report Card](https://goreportcard.com/badge/github.com/mdlayher/raw)](https://goreportcard.com/report/github.com/mdlayher/raw)
===
Package `raw` enables reading and writing data at the device driver level for
a network interface. MIT Licensed.
For more information about using raw sockets with Ethernet frames in Go, check
out my blog post: [Network Protocol Breakdown: Ethernet and Go](https://medium.com/@mdlayher/network-protocol-breakdown-ethernet-and-go-de985d726cc1).
Portions of this code are taken from the Go standard library. The Go
standard library is Copyright (c) 2012 The Go Authors. All rights reserved.
The Go license can be found at https://golang.org/LICENSE.
+189
View File
@@ -0,0 +1,189 @@
// Package raw enables reading and writing data at the device driver level for
// a network interface.
package raw
import (
"errors"
"net"
"time"
"golang.org/x/net/bpf"
)
const (
// Maximum read timeout per syscall.
// It is required because read/recvfrom won't be interrupted on closing of the file descriptor.
readTimeout = 200 * time.Millisecond
)
var (
// ErrNotImplemented is returned when certain functionality is not yet
// implemented for the host operating system.
ErrNotImplemented = errors.New("raw: not implemented")
)
var _ net.Addr = &Addr{}
// Addr is a network address which can be used to contact other machines, using
// their hardware addresses.
type Addr struct {
HardwareAddr net.HardwareAddr
}
// Network returns the address's network name, "raw".
func (a *Addr) Network() string {
return "raw"
}
// String returns the address's hardware address.
func (a *Addr) String() string {
return a.HardwareAddr.String()
}
var _ net.PacketConn = &Conn{}
// Conn is an implementation of the net.PacketConn interface which can send
// and receive data at the network interface device driver level.
type Conn struct {
// packetConn is the operating system-specific implementation of
// a raw connection.
p *packetConn
}
// ReadFrom implements the net.PacketConn ReadFrom method.
func (c *Conn) ReadFrom(b []byte) (int, net.Addr, error) {
return c.p.ReadFrom(b)
}
// WriteTo implements the net.PacketConn WriteTo method.
func (c *Conn) WriteTo(b []byte, addr net.Addr) (int, error) {
return c.p.WriteTo(b, addr)
}
// Close closes the connection.
func (c *Conn) Close() error {
return c.p.Close()
}
// LocalAddr returns the local network address.
func (c *Conn) LocalAddr() net.Addr {
return c.p.LocalAddr()
}
// SetDeadline implements the net.PacketConn SetDeadline method.
func (c *Conn) SetDeadline(t time.Time) error {
return c.p.SetDeadline(t)
}
// SetReadDeadline implements the net.PacketConn SetReadDeadline method.
func (c *Conn) SetReadDeadline(t time.Time) error {
return c.p.SetReadDeadline(t)
}
// SetWriteDeadline implements the net.PacketConn SetWriteDeadline method.
func (c *Conn) SetWriteDeadline(t time.Time) error {
return c.p.SetWriteDeadline(t)
}
var _ bpf.Setter = &Conn{}
// SetBPF attaches an assembled BPF program to the connection.
func (c *Conn) SetBPF(filter []bpf.RawInstruction) error {
return c.p.SetBPF(filter)
}
// SetPromiscuous enables or disables promiscuous mode on the interface, allowing it
// to receive traffic that is not addressed to the interface.
func (c *Conn) SetPromiscuous(b bool) error {
return c.p.SetPromiscuous(b)
}
// Stats contains statistics about a Conn.
type Stats struct {
// The total number of packets received.
Packets uint64
// The number of packets dropped.
Drops uint64
}
// Stats retrieves statistics from the Conn.
//
// Only supported on Linux at this time.
func (c *Conn) Stats() (*Stats, error) {
return c.p.Stats()
}
// ListenPacket creates a net.PacketConn which can be used to send and receive
// data at the network interface device driver level.
//
// ifi specifies the network interface which will be used to send and receive
// data.
//
// proto specifies the protocol (usually the EtherType) which should be
// captured and transmitted. proto, if needed, is automatically converted to
// network byte order (big endian), akin to the htons() function in C.
//
// cfg specifies optional configuration which may be operating system-specific.
// A nil Config is equivalent to the default configuration: send and receive
// data at the network interface device driver level (usually raw Ethernet frames).
func ListenPacket(ifi *net.Interface, proto uint16, cfg *Config) (*Conn, error) {
// A nil config is an empty Config.
if cfg == nil {
cfg = &Config{}
}
p, err := listenPacket(ifi, proto, *cfg)
if err != nil {
return nil, err
}
return &Conn{
p: p,
}, nil
}
// A Config can be used to specify additional options for a Conn.
type Config struct {
// Linux only: call socket(7) with SOCK_DGRAM instead of SOCK_RAW.
// Has no effect on other operating systems.
LinuxSockDGRAM bool
// Experimental: Linux only (for now, but can be ported to BSD):
// disables repeated socket reads due to internal timeouts, at the expense
// of losing the ability to cancel a ReadFrom operation by calling the Close
// method of the net.PacketConn.
//
// Not recommended for programs which may need to open and close multiple
// sockets during program runs. This may save some CPU time by avoiding a
// busy loop for programs which do not need timeouts, or programs which keep
// a single socket open for the entire duration of the program.
NoTimeouts bool
// Linux only: do not accumulate packet socket statistic counters. Packet
// socket statistics are reset on each call to retrieve them via getsockopt,
// but this package's default behavior is to continue accumulating the
// statistics internally per Conn. To use the Linux default behavior of
// resetting statistics on each call to Stats, set this value to true.
NoCumulativeStats bool
}
// htons converts a short (uint16) from host-to-network byte order.
// Thanks to mikioh for this neat trick:
// https://github.com/mikioh/-stdyng/blob/master/afpacket.go
func htons(i uint16) uint16 {
return (i<<8)&0xff00 | i>>8
}
// Copyright (c) 2012 The Go Authors. All rights reserved.
// Source code in this file is based on src/net/interface_linux.go,
// from the Go standard library. The Go license can be found here:
// https://golang.org/LICENSE.
// Taken from:
// https://github.com/golang/go/blob/master/src/net/net.go#L417-L421.
type timeoutError struct{}
func (e *timeoutError) Error() string { return "i/o timeout" }
func (e *timeoutError) Timeout() bool { return true }
func (e *timeoutError) Temporary() bool { return true }
+366
View File
@@ -0,0 +1,366 @@
// +build darwin dragonfly freebsd netbsd openbsd
package raw
import (
"errors"
"fmt"
"net"
"os"
"runtime"
"sync"
"syscall"
"time"
"unsafe"
"golang.org/x/net/bpf"
)
const (
// bpfDIn tells BPF to pass through only incoming packets, so we do not
// receive the packets we send using BPF.
bpfDIn = 0
// osFreeBSD is the GOOS name for FreeBSD.
osFreeBSD = "freebsd"
)
// bpfLen returns the length of the BPF header prepended to each incoming ethernet
// frame. FreeBSD uses a slightly modified header from other BSD variants.
func bpfLen() int {
// Majority of BSD family systems use the bpf_hdr struct, but FreeBSD
// has replaced this with bpf_xhdr, which is longer.
const (
bpfHeaderLen = 18
bpfXHeaderLen = 26
)
if runtime.GOOS == osFreeBSD {
return bpfXHeaderLen
}
return bpfHeaderLen
}
var (
// Must implement net.PacketConn at compile-time.
_ net.PacketConn = &packetConn{}
)
// packetConn is the Linux-specific implementation of net.PacketConn for this
// package.
type packetConn struct {
proto uint16
ifi *net.Interface
f *os.File
fd int
buflen int
// Timeouts set via Set{Read,}Deadline, guarded by mutex
timeoutMu sync.RWMutex
rtimeout time.Time
}
// listenPacket creates a net.PacketConn which can be used to send and receive
// data at the device driver level.
func listenPacket(ifi *net.Interface, proto uint16, _ Config) (*packetConn, error) {
// Config is, as of now, unused on BSD.
// TODO(mdlayher): consider porting NoTimeouts option to BSD if it pans out.
var f *os.File
var err error
// Try to find an available BPF device
for i := 0; i <= 10; i++ {
bpfPath := fmt.Sprintf("/dev/bpf%d", i)
f, err = os.OpenFile(bpfPath, os.O_RDWR, 0666)
if err == nil {
// Found a usable device
break
}
// Device is busy, try the next one
if perr, ok := err.(*os.PathError); ok {
if perr.Err.(syscall.Errno) == syscall.EBUSY {
continue
}
}
return nil, err
}
if f == nil {
return nil, errors.New("unable to open BPF device")
}
fd := int(f.Fd())
if fd == -1 {
return nil, errors.New("unable to open BPF device")
}
// Configure BPF device to send and receive data
buflen, err := configureBPF(fd, ifi, proto)
if err != nil {
return nil, err
}
return &packetConn{
proto: proto,
ifi: ifi,
f: f,
fd: fd,
buflen: buflen,
}, nil
}
// ReadFrom implements the net.PacketConn.ReadFrom method.
func (p *packetConn) ReadFrom(b []byte) (int, net.Addr, error) {
p.timeoutMu.Lock()
deadline := p.rtimeout
p.timeoutMu.Unlock()
buf := make([]byte, p.buflen)
var n int
for {
var timeout time.Duration
if deadline.IsZero() {
timeout = readTimeout
} else {
timeout = deadline.Sub(time.Now())
if timeout > readTimeout {
timeout = readTimeout
}
}
tv, err := newTimeval(timeout)
if err != nil {
return 0, nil, err
}
if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(p.fd), syscall.BIOCSRTIMEOUT, uintptr(unsafe.Pointer(tv))); err != 0 {
return 0, nil, syscall.Errno(err)
}
// Attempt to receive on socket
// The read sycall will NOT be interrupted by closing of the socket
n, err = syscall.Read(p.fd, buf)
if err != nil {
return n, nil, err
}
if n > 0 {
break
}
}
// TODO(mdlayher): consider parsing BPF header if it proves useful.
// BPF header length depends on the platform this code is running on
bpfl := bpfLen()
// Retrieve source MAC address of ethernet header
mac := make(net.HardwareAddr, 6)
copy(mac, buf[bpfl+6:bpfl+12])
// Skip past BPF header to retrieve ethernet frame
out := copy(b, buf[bpfl:bpfl+n])
return out, &Addr{
HardwareAddr: mac,
}, nil
}
// WriteTo implements the net.PacketConn.WriteTo method.
func (p *packetConn) WriteTo(b []byte, _ net.Addr) (int, error) {
return syscall.Write(p.fd, b)
}
// Close closes the connection.
func (p *packetConn) Close() error {
return p.f.Close()
}
// LocalAddr returns the local network address.
func (p *packetConn) LocalAddr() net.Addr {
return &Addr{
HardwareAddr: p.ifi.HardwareAddr,
}
}
// SetDeadline implements the net.PacketConn.SetDeadline method.
func (p *packetConn) SetDeadline(t time.Time) error {
return p.SetReadDeadline(t)
}
// SetReadDeadline implements the net.PacketConn.SetReadDeadline method.
func (p *packetConn) SetReadDeadline(t time.Time) error {
p.timeoutMu.Lock()
p.rtimeout = t
p.timeoutMu.Unlock()
return nil
}
// SetWriteDeadline implements the net.PacketConn.SetWriteDeadline method.
func (p *packetConn) SetWriteDeadline(t time.Time) error {
return ErrNotImplemented
}
// SetBPF attaches an assembled BPF program to a raw net.PacketConn.
func (p *packetConn) SetBPF(filter []bpf.RawInstruction) error {
// Base filter filters traffic based on EtherType
base, err := bpf.Assemble(baseFilter(p.proto))
if err != nil {
return err
}
// Append user filter to base filter, translate to raw format,
// and apply to BPF device
return syscall.SetBpf(p.fd, assembleBpfInsn(append(base, filter...)))
}
// SetPromiscuous enables or disables promiscuous mode on the interface, allowing it
// to receive traffic that is not addressed to the interface.
func (p *packetConn) SetPromiscuous(b bool) error {
m := 1
if !b {
m = 0
}
return syscall.SetBpfPromisc(p.fd, m)
}
// Stats retrieves statistics from the Conn.
func (p *packetConn) Stats() (*Stats, error) {
return nil, ErrNotImplemented
}
// configureBPF configures a BPF device with the specified file descriptor to
// use the specified network and interface and protocol.
func configureBPF(fd int, ifi *net.Interface, proto uint16) (int, error) {
// Use specified interface with BPF device
if err := syscall.SetBpfInterface(fd, ifi.Name); err != nil {
return 0, err
}
// Inform BPF to send us its data immediately
if err := syscall.SetBpfImmediate(fd, 1); err != nil {
return 0, err
}
// Check buffer size of BPF device
buflen, err := syscall.BpfBuflen(fd)
if err != nil {
return 0, err
}
// Do not automatically complete source address in ethernet headers
if err := syscall.SetBpfHeadercmpl(fd, 1); err != nil {
return 0, err
}
// Only retrieve incoming traffic using BPF device
if err := setBPFDirection(fd, bpfDIn); err != nil {
return 0, err
}
// Build and apply base BPF filter which checks for correct EtherType
// on incoming packets
prog, err := bpf.Assemble(baseInterfaceFilter(proto, ifi.MTU))
if err != nil {
return 0, err
}
if err := syscall.SetBpf(fd, assembleBpfInsn(prog)); err != nil {
return 0, err
}
// Flush any packets currently in the BPF device's buffer
if err := syscall.FlushBpf(fd); err != nil {
return 0, err
}
return buflen, nil
}
// setBPFDirection enables filtering traffic traveling in a specific direction
// using BPF, so that traffic sent by this package is not captured when reading
// using this package.
func setBPFDirection(fd int, direction int) error {
_, _, err := syscall.Syscall(
syscall.SYS_IOCTL,
uintptr(fd),
// Even though BIOCSDIRECTION is preferred on FreeBSD, BIOCSSEESENT continues
// to work, and is required for other BSD platforms
syscall.BIOCSSEESENT,
uintptr(unsafe.Pointer(&direction)),
)
if err != 0 {
return syscall.Errno(err)
}
return nil
}
// assembleBpfInsn assembles a slice of bpf.RawInstructions to the format required by
// package syscall.
func assembleBpfInsn(filter []bpf.RawInstruction) []syscall.BpfInsn {
// Copy each bpf.RawInstruction into syscall.BpfInsn. If needed,
// the structures have the same memory layout and could probably be
// unsafely cast to each other for speed.
insns := make([]syscall.BpfInsn, 0, len(filter))
for _, ins := range filter {
insns = append(insns, syscall.BpfInsn{
Code: ins.Op,
Jt: ins.Jt,
Jf: ins.Jf,
K: ins.K,
})
}
return insns
}
// baseInterfaceFilter creates a base BPF filter which filters traffic based
// on its EtherType and returns up to "mtu" bytes of data for processing.
func baseInterfaceFilter(proto uint16, mtu int) []bpf.Instruction {
return append(
// Filter traffic based on EtherType
baseFilter(proto),
// Accept the packet bytes up to the interface's MTU
bpf.RetConstant{
Val: uint32(mtu),
},
)
}
// baseFilter creates a base BPF filter which filters traffic based on its
// EtherType. baseFilter can be prepended to other filters to handle common
// filtering tasks.
func baseFilter(proto uint16) []bpf.Instruction {
// Offset | Length | Comment
// -------------------------
// 00 | 06 | Ethernet destination MAC address
// 06 | 06 | Ethernet source MAC address
// 12 | 02 | Ethernet EtherType
const (
etherTypeOffset = 12
etherTypeLength = 2
)
return []bpf.Instruction{
// Load EtherType value from Ethernet header
bpf.LoadAbsolute{
Off: etherTypeOffset,
Size: etherTypeLength,
},
// If EtherType is equal to the protocol we are using, jump to instructions
// added outside of this function.
bpf.JumpIf{
Cond: bpf.JumpEqual,
Val: uint32(proto),
SkipTrue: 1,
},
// EtherType does not match our protocol
bpf.RetConstant{
Val: 0,
},
}
}
+340
View File
@@ -0,0 +1,340 @@
// +build linux
package raw
import (
"net"
"os"
"sync"
"sync/atomic"
"time"
"unsafe"
"golang.org/x/net/bpf"
"golang.org/x/sys/unix"
)
var (
// Must implement net.PacketConn at compile-time.
_ net.PacketConn = &packetConn{}
)
// packetConn is the Linux-specific implementation of net.PacketConn for this
// package.
type packetConn struct {
ifi *net.Interface
s socket
pbe uint16
// Should timeouts be set at all?
noTimeouts bool
// Should stats be accumulated instead of reset on each call?
noCumulativeStats bool
// Internal storage for cumulative stats.
stats Stats
// Timeouts set via Set{Read,}Deadline, guarded by mutex.
timeoutMu sync.RWMutex
rtimeout time.Time
}
// socket is an interface which enables swapping out socket syscalls for
// testing.
type socket interface {
Bind(unix.Sockaddr) error
Close() error
FD() int
GetSockopt(level, name int, v unsafe.Pointer, l uintptr) error
Recvfrom([]byte, int) (int, unix.Sockaddr, error)
Sendto([]byte, int, unix.Sockaddr) error
SetSockopt(level, name int, v unsafe.Pointer, l uint32) error
SetTimeout(time.Duration) error
}
// listenPacket creates a net.PacketConn which can be used to send and receive
// data at the device driver level.
func listenPacket(ifi *net.Interface, proto uint16, cfg Config) (*packetConn, error) {
// Convert proto to big endian.
pbe := htons(proto)
// Enabling overriding the socket type via config.
typ := unix.SOCK_RAW
if cfg.LinuxSockDGRAM {
typ = unix.SOCK_DGRAM
}
// Open a packet socket using specified socket and protocol types.
sock, err := unix.Socket(unix.AF_PACKET, typ, int(pbe))
if err != nil {
return nil, err
}
// Wrap raw socket in socket interface.
pc, err := newPacketConn(ifi, &sysSocket{fd: sock}, pbe)
if err != nil {
return nil, err
}
pc.noTimeouts = cfg.NoTimeouts
pc.noCumulativeStats = cfg.NoCumulativeStats
return pc, nil
}
// newPacketConn creates a net.PacketConn using the specified network
// interface, wrapped socket and big endian protocol number.
//
// It is the entry point for tests in this package.
func newPacketConn(ifi *net.Interface, s socket, pbe uint16) (*packetConn, error) {
// Bind the packet socket to the interface specified by ifi
// packet(7):
// Only the sll_protocol and the sll_ifindex address fields are used for
// purposes of binding.
err := s.Bind(&unix.SockaddrLinklayer{
Protocol: pbe,
Ifindex: ifi.Index,
})
if err != nil {
return nil, err
}
return &packetConn{
ifi: ifi,
s: s,
pbe: pbe,
}, nil
}
// ReadFrom implements the net.PacketConn.ReadFrom method.
func (p *packetConn) ReadFrom(b []byte) (int, net.Addr, error) {
p.timeoutMu.Lock()
deadline := p.rtimeout
p.timeoutMu.Unlock()
var (
// Information returned by unix.Recvfrom.
n int
addr unix.Sockaddr
err error
// Timeout for a single loop iteration.
timeout = readTimeout
)
for {
if !deadline.IsZero() {
timeout = deadline.Sub(time.Now())
if timeout > readTimeout {
timeout = readTimeout
}
}
// Set a timeout for this iteration if configured to do so.
if !p.noTimeouts {
if err := p.s.SetTimeout(timeout); err != nil {
return 0, nil, err
}
}
// Attempt to receive on socket
// The recvfrom sycall will NOT be interrupted by closing of the socket
n, addr, err = p.s.Recvfrom(b, 0)
switch err {
case nil:
// Got data, break this loop shortly.
case unix.EAGAIN:
// Hit a timeout, keep looping.
continue
default:
// Return on any other error.
return n, nil, err
}
// Got data, exit the loop.
break
}
// Retrieve hardware address and other information from addr.
sa, ok := addr.(*unix.SockaddrLinklayer)
if !ok || sa.Halen < 6 {
return n, nil, unix.EINVAL
}
// Use length specified to convert byte array into a hardware address slice.
mac := make(net.HardwareAddr, sa.Halen)
copy(mac, sa.Addr[:])
// packet(7):
// sll_hatype and sll_pkttype are set on received packets for your
// information.
// TODO(mdlayher): determine if similar fields exist and are useful on
// non-Linux platforms
return n, &Addr{
HardwareAddr: mac,
}, nil
}
// WriteTo implements the net.PacketConn.WriteTo method.
func (p *packetConn) WriteTo(b []byte, addr net.Addr) (int, error) {
// Ensure correct Addr type.
a, ok := addr.(*Addr)
if !ok || a.HardwareAddr == nil || len(a.HardwareAddr) < 6 {
return 0, unix.EINVAL
}
// Convert hardware address back to byte array form.
var baddr [8]byte
copy(baddr[:], a.HardwareAddr)
// Send message on socket to the specified hardware address from addr
// packet(7):
// When you send packets it is enough to specify sll_family, sll_addr,
// sll_halen, sll_ifindex, and sll_protocol. The other fields should
// be 0.
// In this case, sll_family is taken care of automatically by unix.
err := p.s.Sendto(b, 0, &unix.SockaddrLinklayer{
Ifindex: p.ifi.Index,
Halen: uint8(len(a.HardwareAddr)),
Addr: baddr,
Protocol: p.pbe,
})
return len(b), err
}
// Close closes the connection.
func (p *packetConn) Close() error {
return p.s.Close()
}
// LocalAddr returns the local network address.
func (p *packetConn) LocalAddr() net.Addr {
return &Addr{
HardwareAddr: p.ifi.HardwareAddr,
}
}
// SetDeadline implements the net.PacketConn.SetDeadline method.
func (p *packetConn) SetDeadline(t time.Time) error {
return p.SetReadDeadline(t)
}
// SetReadDeadline implements the net.PacketConn.SetReadDeadline method.
func (p *packetConn) SetReadDeadline(t time.Time) error {
p.timeoutMu.Lock()
p.rtimeout = t
p.timeoutMu.Unlock()
return nil
}
// SetWriteDeadline implements the net.PacketConn.SetWriteDeadline method.
func (p *packetConn) SetWriteDeadline(t time.Time) error {
return nil
}
// SetBPF attaches an assembled BPF program to a raw net.PacketConn.
func (p *packetConn) SetBPF(filter []bpf.RawInstruction) error {
prog := unix.SockFprog{
Len: uint16(len(filter)),
Filter: (*unix.SockFilter)(unsafe.Pointer(&filter[0])),
}
err := p.s.SetSockopt(
unix.SOL_SOCKET,
unix.SO_ATTACH_FILTER,
unsafe.Pointer(&prog),
uint32(unsafe.Sizeof(prog)),
)
if err != nil {
return os.NewSyscallError("setsockopt", err)
}
return nil
}
// SetPromiscuous enables or disables promiscuous mode on the interface, allowing it
// to receive traffic that is not addressed to the interface.
func (p *packetConn) SetPromiscuous(b bool) error {
mreq := unix.PacketMreq{
Ifindex: int32(p.ifi.Index),
Type: unix.PACKET_MR_PROMISC,
}
membership := unix.PACKET_ADD_MEMBERSHIP
if !b {
membership = unix.PACKET_DROP_MEMBERSHIP
}
return p.s.SetSockopt(unix.SOL_PACKET, membership, unsafe.Pointer(&mreq), unix.SizeofPacketMreq)
}
// Stats retrieves statistics from the Conn.
func (p *packetConn) Stats() (*Stats, error) {
var s unix.TpacketStats
if err := p.s.GetSockopt(unix.SOL_PACKET, unix.PACKET_STATISTICS, unsafe.Pointer(&s), unsafe.Sizeof(s)); err != nil {
return nil, err
}
return p.handleStats(s), nil
}
// handleStats handles creation of Stats structures from raw packet socket stats.
func (p *packetConn) handleStats(s unix.TpacketStats) *Stats {
// Does the caller want instantaneous stats as provided by Linux? If so,
// return the structure directly.
if p.noCumulativeStats {
return &Stats{
Packets: uint64(s.Packets),
Drops: uint64(s.Drops),
}
}
// The caller wants cumulative stats. Add stats with the internal stats
// structure and return a copy of the resulting stats.
packets := atomic.AddUint64(&p.stats.Packets, uint64(s.Packets))
drops := atomic.AddUint64(&p.stats.Drops, uint64(s.Drops))
return &Stats{
Packets: packets,
Drops: drops,
}
}
// sysSocket is the default socket implementation. It makes use of
// Linux-specific system calls to handle raw socket functionality.
type sysSocket struct {
fd int
}
// Method implementations simply invoke the syscall of the same name, but pass
// the file descriptor stored in the sysSocket as the socket to use.
func (s *sysSocket) Bind(sa unix.Sockaddr) error { return unix.Bind(s.fd, sa) }
func (s *sysSocket) Close() error { return unix.Close(s.fd) }
func (s *sysSocket) FD() int { return s.fd }
func (s *sysSocket) GetSockopt(level, name int, v unsafe.Pointer, l uintptr) error {
_, _, err := unix.Syscall6(unix.SYS_GETSOCKOPT, uintptr(s.fd), uintptr(level), uintptr(name), uintptr(v), uintptr(unsafe.Pointer(&l)), 0)
if err != 0 {
return unix.Errno(err)
}
return nil
}
func (s *sysSocket) Recvfrom(p []byte, flags int) (int, unix.Sockaddr, error) {
return unix.Recvfrom(s.fd, p, flags)
}
func (s *sysSocket) Sendto(p []byte, flags int, to unix.Sockaddr) error {
return unix.Sendto(s.fd, p, flags, to)
}
func (s *sysSocket) SetSockopt(level, name int, v unsafe.Pointer, l uint32) error {
_, _, err := unix.Syscall6(unix.SYS_SETSOCKOPT, uintptr(s.fd), uintptr(level), uintptr(name), uintptr(v), uintptr(l), 0)
if err != 0 {
return unix.Errno(err)
}
return nil
}
func (s *sysSocket) SetTimeout(timeout time.Duration) error {
tv, err := newTimeval(timeout)
if err != nil {
return err
}
return unix.SetsockoptTimeval(s.fd, unix.SOL_SOCKET, unix.SO_RCVTIMEO, tv)
}
+73
View File
@@ -0,0 +1,73 @@
// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd
package raw
import (
"net"
"time"
"golang.org/x/net/bpf"
)
var (
// Must implement net.PacketConn at compile-time.
_ net.PacketConn = &packetConn{}
)
// packetConn is the generic implementation of net.PacketConn for this package.
type packetConn struct{}
// listenPacket is not currently implemented on this platform.
func listenPacket(ifi *net.Interface, proto uint16, cfg Config) (*packetConn, error) {
return nil, ErrNotImplemented
}
// ReadFrom is not currently implemented on this platform.
func (p *packetConn) ReadFrom(b []byte) (int, net.Addr, error) {
return 0, nil, ErrNotImplemented
}
// WriteTo is not currently implemented on this platform.
func (p *packetConn) WriteTo(b []byte, addr net.Addr) (int, error) {
return 0, ErrNotImplemented
}
// Close is not currently implemented on this platform.
func (p *packetConn) Close() error {
return ErrNotImplemented
}
// LocalAddr is not currently implemented on this platform.
func (p *packetConn) LocalAddr() net.Addr {
return nil
}
// SetDeadline is not currently implemented on this platform.
func (p *packetConn) SetDeadline(t time.Time) error {
return ErrNotImplemented
}
// SetReadDeadline is not currently implemented on this platform.
func (p *packetConn) SetReadDeadline(t time.Time) error {
return ErrNotImplemented
}
// SetWriteDeadline is not currently implemented on this platform.
func (p *packetConn) SetWriteDeadline(t time.Time) error {
return ErrNotImplemented
}
// SetBPF is not currently implemented on this platform.
func (p *packetConn) SetBPF(filter []bpf.RawInstruction) error {
return ErrNotImplemented
}
// SetPromisc is not currently implemented on this platform.
func (p *packetConn) SetPromiscuous(b bool) error {
return ErrNotImplemented
}
// Stats is not currently implemented on this platform.
func (p *packetConn) Stats() (*Stats, error) {
return nil, ErrNotImplemented
}
+21
View File
@@ -0,0 +1,21 @@
// +build !darwin,!arm,!windows,!mipsle,!mips,!386
package raw
import (
"time"
"golang.org/x/sys/unix"
)
// newTimeval transforms a duration into a unix.Timeval struct.
// An error is returned in case of zero time value.
func newTimeval(timeout time.Duration) (*unix.Timeval, error) {
if timeout < time.Microsecond {
return nil, &timeoutError{}
}
return &unix.Timeval{
Sec: int64(timeout / time.Second),
Usec: int64(timeout % time.Second / time.Microsecond),
}, nil
}
+21
View File
@@ -0,0 +1,21 @@
// +build arm mipsle mips 386
package raw
import (
"time"
"golang.org/x/sys/unix"
)
// newTimeval transforms a duration into a unix.Timeval struct.
// An error is returned in case of zero time value.
func newTimeval(timeout time.Duration) (*unix.Timeval, error) {
if timeout < time.Microsecond {
return nil, &timeoutError{}
}
return &unix.Timeval{
Sec: int32(timeout / time.Second),
Usec: int32(timeout % time.Second / time.Microsecond),
}, nil
}
+20
View File
@@ -0,0 +1,20 @@
// +build darwin
package raw
import (
"syscall"
"time"
)
// newTimeval transforms a duration into a syscall.Timeval struct.
// An error is returned in case of zero time value.
func newTimeval(timeout time.Duration) (*syscall.Timeval, error) {
if timeout < time.Microsecond {
return nil, &timeoutError{}
}
return &syscall.Timeval{
Sec: int64(timeout / time.Second),
Usec: int32(timeout % time.Second / time.Microsecond),
}, nil
}