google / gopacket

Provides packet processing capabilities for Go
BSD 3-Clause "New" or "Revised" License
6.35k stars 1.13k forks source link

routing.go: panic: runtime error: index out of range [-1] #795

Open Jipan-Yang opened 4 years ago

Jipan-Yang commented 4 years ago

panic if no route available:

$ go run ./test.go 
panic: runtime error: index out of range [-1]

goroutine 1 [running]:
github.com/google/gopacket/routing.(*router).RouteWithSrc(0xc00011c120, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xc000118220, 0x10, 0x10, ...)
    /home/jipan/go/src/github.com/google/gopacket/routing/routing.go:109 +0x6c0
github.com/google/gopacket/routing.(*router).Route(0xc00011c120, 0xc000118220, 0x10, 0x10, 0x4646cd, 0x4c99c0, 0xc000100470, 0xc00004cee8, 0x4ab6f2, 0x4ebc3a, ...)
    /home/jipan/go/src/github.com/google/gopacket/routing/routing.go:91 +0x86
main.main()
    /home/jipan/go/src/test/test.go:17 +0x131
exit status 2
$ ip -6 route show
::1 dev lo proto kernel metric 256 pref medium
fe80::/64 dev wlp3s0 proto kernel metric 256 pref medium
fe80::/64 dev wlp3s0 proto kernel metric 600 pref medium

Testing code:

package main

import (
    "fmt"
    "log"
    "net"

    "github.com/google/gopacket/routing"
)

func main() {
    ip := net.IP{0x20, 0x01, 0x48, 0x60, 0x00, 0x20, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0x68}
    router, err := routing.New()
    if err != nil {
        log.Fatal("routing error:", err)
    }
    iface, gw, src, err := router.Route(ip)
    if err != nil {
        log.Fatal("route error:", err)
        return
    }

    fmt.Printf("  iface: %+v\n  gw: %v\n  src: %v\n", iface, gw, src)
}

It works if route exists:

$ ip -6 route show
::1 dev lo proto kernel metric 256 pref medium
2607:fb90:9c3e:1a8f::/64 dev wlp3s0 proto ra metric 600 pref medium
fe80::/64 dev wlp3s0 proto kernel metric 256 pref medium
fe80::/64 dev wlp3s0 proto kernel metric 600 pref medium
default via fe80::8a9:77cc:b8fe:4b37 dev wlp3s0 proto ra metric 600 pref medium
$ go run ./test.go 
  iface: &{Index:3 MTU:1500 Name:wlp3s0 HardwareAddr:d4:6a:6a:df:90:d7 Flags:up|broadcast|multicast}
  gw: fe80::8a9:77cc:b8fe:4b37
  src: 2607:fb90:9c3e:1a8f:70c1:e8e6:5f32:fcdf
sivachandran commented 4 years ago

Commit f815f794877125111ea338dbac64c8201ee2f84f fixes this issue