bpf_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright 2016 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. package ipv4_test
  5. import (
  6. "net"
  7. "runtime"
  8. "testing"
  9. "time"
  10. "golang.org/x/net/bpf"
  11. "golang.org/x/net/ipv4"
  12. )
  13. func TestBPF(t *testing.T) {
  14. if runtime.GOOS != "linux" {
  15. t.Skipf("not supported on %s", runtime.GOOS)
  16. }
  17. l, err := net.ListenPacket("udp4", "127.0.0.1:0")
  18. if err != nil {
  19. t.Fatal(err)
  20. }
  21. defer l.Close()
  22. p := ipv4.NewPacketConn(l)
  23. // This filter accepts UDP packets whose first payload byte is
  24. // even.
  25. prog, err := bpf.Assemble([]bpf.Instruction{
  26. // Load the first byte of the payload (skipping UDP header).
  27. bpf.LoadAbsolute{Off: 8, Size: 1},
  28. // Select LSB of the byte.
  29. bpf.ALUOpConstant{Op: bpf.ALUOpAnd, Val: 1},
  30. // Byte is even?
  31. bpf.JumpIf{Cond: bpf.JumpEqual, Val: 0, SkipFalse: 1},
  32. // Accept.
  33. bpf.RetConstant{Val: 4096},
  34. // Ignore.
  35. bpf.RetConstant{Val: 0},
  36. })
  37. if err != nil {
  38. t.Fatalf("compiling BPF: %s", err)
  39. }
  40. if err = p.SetBPF(prog); err != nil {
  41. t.Fatalf("attaching filter to Conn: %s", err)
  42. }
  43. s, err := net.Dial("udp4", l.LocalAddr().String())
  44. if err != nil {
  45. t.Fatal(err)
  46. }
  47. defer s.Close()
  48. go func() {
  49. for i := byte(0); i < 10; i++ {
  50. s.Write([]byte{i})
  51. }
  52. }()
  53. l.SetDeadline(time.Now().Add(2 * time.Second))
  54. seen := make([]bool, 5)
  55. for {
  56. var b [512]byte
  57. n, _, err := l.ReadFrom(b[:])
  58. if err != nil {
  59. t.Fatalf("reading from listener: %s", err)
  60. }
  61. if n != 1 {
  62. t.Fatalf("unexpected packet length, want 1, got %d", n)
  63. }
  64. if b[0] >= 10 {
  65. t.Fatalf("unexpected byte, want 0-9, got %d", b[0])
  66. }
  67. if b[0]%2 != 0 {
  68. t.Fatalf("got odd byte %d, wanted only even bytes", b[0])
  69. }
  70. seen[b[0]/2] = true
  71. seenAll := true
  72. for _, v := range seen {
  73. if !v {
  74. seenAll = false
  75. break
  76. }
  77. }
  78. if seenAll {
  79. break
  80. }
  81. }
  82. }