lsf_linux.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. // Linux socket filter
  5. package unix
  6. import (
  7. "syscall"
  8. "unsafe"
  9. )
  10. func LsfStmt(code, k int) *SockFilter {
  11. return &SockFilter{Code: uint16(code), K: uint32(k)}
  12. }
  13. func LsfJump(code, k, jt, jf int) *SockFilter {
  14. return &SockFilter{Code: uint16(code), Jt: uint8(jt), Jf: uint8(jf), K: uint32(k)}
  15. }
  16. func LsfSocket(ifindex, proto int) (int, error) {
  17. var lsall SockaddrLinklayer
  18. s, e := Socket(AF_PACKET, SOCK_RAW, proto)
  19. if e != nil {
  20. return 0, e
  21. }
  22. p := (*[2]byte)(unsafe.Pointer(&lsall.Protocol))
  23. p[0] = byte(proto >> 8)
  24. p[1] = byte(proto)
  25. lsall.Ifindex = ifindex
  26. e = Bind(s, &lsall)
  27. if e != nil {
  28. Close(s)
  29. return 0, e
  30. }
  31. return s, nil
  32. }
  33. type iflags struct {
  34. name [IFNAMSIZ]byte
  35. flags uint16
  36. }
  37. func SetLsfPromisc(name string, m bool) error {
  38. s, e := Socket(AF_INET, SOCK_DGRAM, 0)
  39. if e != nil {
  40. return e
  41. }
  42. defer Close(s)
  43. var ifl iflags
  44. copy(ifl.name[:], []byte(name))
  45. _, _, ep := Syscall(SYS_IOCTL, uintptr(s), SIOCGIFFLAGS, uintptr(unsafe.Pointer(&ifl)))
  46. if ep != 0 {
  47. return syscall.Errno(ep)
  48. }
  49. if m {
  50. ifl.flags |= uint16(IFF_PROMISC)
  51. } else {
  52. ifl.flags &= ^uint16(IFF_PROMISC)
  53. }
  54. _, _, ep = Syscall(SYS_IOCTL, uintptr(s), SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifl)))
  55. if ep != 0 {
  56. return syscall.Errno(ep)
  57. }
  58. return nil
  59. }
  60. func AttachLsf(fd int, i []SockFilter) error {
  61. var p SockFprog
  62. p.Len = uint16(len(i))
  63. p.Filter = (*SockFilter)(unsafe.Pointer(&i[0]))
  64. return setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, unsafe.Pointer(&p), unsafe.Sizeof(p))
  65. }
  66. func DetachLsf(fd int) error {
  67. var dummy int
  68. return setsockopt(fd, SOL_SOCKET, SO_DETACH_FILTER, unsafe.Pointer(&dummy), unsafe.Sizeof(dummy))
  69. }