interfaces_linux_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright (c) 2020 Tailscale Inc & 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 interfaces
  5. import (
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "testing"
  11. )
  12. // test the specific /proc/net/route path as found on Google Cloud Run instances
  13. func TestGoogleCloudRunDefaultRouteInterface(t *testing.T) {
  14. dir := t.TempDir()
  15. savedProcNetRoutePath := procNetRoutePath
  16. defer func() { procNetRoutePath = savedProcNetRoutePath }()
  17. procNetRoutePath = filepath.Join(dir, "CloudRun")
  18. buf := []byte("Iface\tDestination\tGateway\tFlags\tRefCnt\tUse\tMetric\tMask\tMTU\tWindow\tIRTT\n" +
  19. "eth0\t8008FEA9\t00000000\t0001\t0\t0\t0\t01FFFFFF\t0\t0\t0\n" +
  20. "eth1\t00000000\t00000000\t0001\t0\t0\t0\t00000000\t0\t0\t0\n")
  21. err := ioutil.WriteFile(procNetRoutePath, buf, 0644)
  22. if err != nil {
  23. t.Fatal(err)
  24. }
  25. got, err := DefaultRouteInterface()
  26. if err != nil {
  27. t.Fatal(err)
  28. }
  29. if got != "eth1" {
  30. t.Fatalf("got %s, want eth1", got)
  31. }
  32. }
  33. // we read chunks of /proc/net/route at a time, test that files longer than the chunk
  34. // size can be handled.
  35. func TestExtremelyLongProcNetRoute(t *testing.T) {
  36. dir := t.TempDir()
  37. savedProcNetRoutePath := procNetRoutePath
  38. defer func() { procNetRoutePath = savedProcNetRoutePath }()
  39. procNetRoutePath = filepath.Join(dir, "VeryLong")
  40. f, err := os.Create(procNetRoutePath)
  41. if err != nil {
  42. t.Fatal(err)
  43. }
  44. _, err = f.Write([]byte("Iface\tDestination\tGateway\tFlags\tRefCnt\tUse\tMetric\tMask\tMTU\tWindow\tIRTT\n"))
  45. if err != nil {
  46. t.Fatal(err)
  47. }
  48. for n := 0; n <= 1000; n++ {
  49. line := fmt.Sprintf("eth%d\t8008FEA9\t00000000\t0001\t0\t0\t0\t01FFFFFF\t0\t0\t0\n", n)
  50. _, err := f.Write([]byte(line))
  51. if err != nil {
  52. t.Fatal(err)
  53. }
  54. }
  55. _, err = f.Write([]byte("tokenring1\t00000000\t00000000\t0001\t0\t0\t0\t00000000\t0\t0\t0\n"))
  56. if err != nil {
  57. t.Fatal(err)
  58. }
  59. got, err := DefaultRouteInterface()
  60. if err != nil {
  61. t.Fatal(err)
  62. }
  63. if got != "tokenring1" {
  64. t.Fatalf("got %q, want tokenring1", got)
  65. }
  66. }
  67. func BenchmarkDefaultRouteInterface(b *testing.B) {
  68. b.ReportAllocs()
  69. for i := 0; i < b.N; i++ {
  70. if _, err := DefaultRouteInterface(); err != nil {
  71. b.Fatal(err)
  72. }
  73. }
  74. }