github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/sys/unix/lsf_linux.go (about)

     1  // Copyright 2011 The Go Authors.  All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Linux socket filter
     6  
     7  package unix
     8  
     9  import (
    10  	"syscall"
    11  	"unsafe"
    12  )
    13  
    14  func LsfStmt(code, k int) *SockFilter {
    15  	return &SockFilter{Code: uint16(code), K: uint32(k)}
    16  }
    17  
    18  func LsfJump(code, k, jt, jf int) *SockFilter {
    19  	return &SockFilter{Code: uint16(code), Jt: uint8(jt), Jf: uint8(jf), K: uint32(k)}
    20  }
    21  
    22  func LsfSocket(ifindex, proto int) (int, error) {
    23  	var lsall SockaddrLinklayer
    24  	s, e := Socket(AF_PACKET, SOCK_RAW, proto)
    25  	if e != nil {
    26  		return 0, e
    27  	}
    28  	p := (*[2]byte)(unsafe.Pointer(&lsall.Protocol))
    29  	p[0] = byte(proto >> 8)
    30  	p[1] = byte(proto)
    31  	lsall.Ifindex = ifindex
    32  	e = Bind(s, &lsall)
    33  	if e != nil {
    34  		Close(s)
    35  		return 0, e
    36  	}
    37  	return s, nil
    38  }
    39  
    40  type iflags struct {
    41  	name  [IFNAMSIZ]byte
    42  	flags uint16
    43  }
    44  
    45  func SetLsfPromisc(name string, m bool) error {
    46  	s, e := Socket(AF_INET, SOCK_DGRAM, 0)
    47  	if e != nil {
    48  		return e
    49  	}
    50  	defer Close(s)
    51  	var ifl iflags
    52  	copy(ifl.name[:], []byte(name))
    53  	_, _, ep := Syscall(SYS_IOCTL, uintptr(s), SIOCGIFFLAGS, uintptr(unsafe.Pointer(&ifl)))
    54  	if ep != 0 {
    55  		return syscall.Errno(ep)
    56  	}
    57  	if m {
    58  		ifl.flags |= uint16(IFF_PROMISC)
    59  	} else {
    60  		ifl.flags &= ^uint16(IFF_PROMISC)
    61  	}
    62  	_, _, ep = Syscall(SYS_IOCTL, uintptr(s), SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifl)))
    63  	if ep != 0 {
    64  		return syscall.Errno(ep)
    65  	}
    66  	return nil
    67  }
    68  
    69  func AttachLsf(fd int, i []SockFilter) error {
    70  	var p SockFprog
    71  	p.Len = uint16(len(i))
    72  	p.Filter = (*SockFilter)(unsafe.Pointer(&i[0]))
    73  	return setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, unsafe.Pointer(&p), unsafe.Sizeof(p))
    74  }
    75  
    76  func DetachLsf(fd int) error {
    77  	var dummy int
    78  	return setsockopt(fd, SOL_SOCKET, SO_DETACH_FILTER, unsafe.Pointer(&dummy), unsafe.Sizeof(dummy))
    79  }