gobgp icon indicating copy to clipboard operation
gobgp copied to clipboard

panic: runtime error: invalid memory address or nil pointer dereference

Open sunyone opened this issue 3 years ago • 1 comments

gobgp n 192.168.2.1 adj-in -a ls panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x70 pc=0xa5ad4e]

goroutine 1 [running]: main.makeShowRouteArgs(0xc00029cb00, 0xc000082220?, {0xc0001217e0?, 0x8?, 0x203000?}, 0x1, 0x0, 0x0, 0x1) /home/runner/work/gobgp/gobgp/cmd/gobgp/neighbor.go:611 +0x90e main.showRoute({0xc0003b6700, 0x63, 0xc0000ae000?}, 0x1, 0xbc?, 0x0, 0x1) /home/runner/work/gobgp/gobgp/cmd/gobgp/neighbor.go:621 +0x9aa main.showNeighborRib({0xc0ca76, 0x6}, {0xc000036490, 0xb}, {0xc000207210, 0x0, 0x1}) /home/runner/work/gobgp/gobgp/cmd/gobgp/neighbor.go:989 +0xc12 main.newNeighborCmd.func1(0xc000230a00?, {0xc000207210?, 0x1?, 0x1?}) /home/runner/work/gobgp/gobgp/cmd/gobgp/neighbor.go:1386 +0x21a github.com/spf13/cobra.(*Command).execute(0xc000230a00, {0xc0002071e0, 0x1, 0x1}) /home/runner/go/pkg/mod/github.com/spf13/[email protected]/command.go:860 +0x663 github.com/spf13/cobra.(*Command).ExecuteC(0xc000230280) /home/runner/go/pkg/mod/github.com/spf13/[email protected]/command.go:974 +0x3b4 github.com/spf13/cobra.(*Command).Execute(...) /home/runner/go/pkg/mod/github.com/spf13/[email protected]/command.go:902 main.newNeighborCmd.func6(0xc000234500?, {0xc0000add00?, 0x4?, 0x4?}) /home/runner/work/gobgp/gobgp/cmd/gobgp/neighbor.go:1475 +0xff github.com/spf13/cobra.(*Command).execute(0xc000234500, {0xc0000adcc0, 0x4, 0x4}) /home/runner/go/pkg/mod/github.com/spf13/[email protected]/command.go:860 +0x663 github.com/spf13/cobra.(*Command).ExecuteC(0xc00021b180) /home/runner/go/pkg/mod/github.com/spf13/[email protected]/command.go:974 +0x3b4 github.com/spf13/cobra.(*Command).Execute(...) /home/runner/go/pkg/mod/github.com/spf13/[email protected]/command.go:902 main.main() /home/runner/work/gobgp/gobgp/cmd/gobgp/main.go:32 +0xc5

sunyone avatar Nov 07 '22 14:11 sunyone


package main

import (
	"context"
	"fmt"
	"net"
	"strings"

	"github.com/osrg/gobgp/v3/pkg/api"
	"github.com/osrg/gobgp/v3/pkg/packet/bgp"
	"github.com/spf13/cobra"
	"google.golang.org/grpc"
)

// Address family mapping
var afiSafiMap = map[string]bgp.RouteFamily{
	"ipv4":        bgp.RF_IPv4_UC,
	"ipv6":        bgp.RF_IPv6_UC,
	"ls":          bgp.RF_LS,
	"vpnv4":       bgp.RF_IPv4_VPN,
	"vpnv6":       bgp.RF_IPv6_VPN,
	"evpn":        bgp.RF_EVPN,
	"opaque":      bgp.RF_OPAQUE,
	"flow":        bgp.RF_FS_IPv4_UC,
	"flow-vpn":    bgp.RF_FS_VPNv4_UC,
	"rtfilter":    bgp.RF_RTFILTER,
	"mpls":        bgp.RF_IPv4_MPLS,
}

// makeShowRouteArgs constructs arguments for showing routes
func makeShowRouteArgs(client api.GobgpApiClient, neighborAddr string, args []string, tableType api.TableType, reverse bool, format string, summary bool) (*api.ListPathRequest, error) {
	if client == nil {
		return nil, fmt.Errorf("nil gRPC client")
	}

	// Parse address family
	afiSafi := bgp.RF_IPv4_UC // Default
	if len(args) > 0 {
		var ok bool
		afiSafi, ok = afiSafiMap[strings.ToLower(args[0])]
		if !ok {
			return nil, fmt.Errorf("invalid address family: %s", args[0])
		}
	}

	// Validate neighbor address
	if neighborAddr != "" {
		if net.ParseIP(neighborAddr) == nil {
			return nil, fmt.Errorf("invalid neighbor address: %s", neighborAddr)
		}
	}

	// Construct ListPathRequest
	req := &api.ListPathRequest{
		TableType: tableType,
		Family: &api.Family{
			Afi:  uint32(afiSafi.Afi()),
			Safi: uint32(afiSafi.Safi()),
		},
		Reverse:  reverse,
		Summary:  summary,
		Prefixes: nil,
	}

	if neighborAddr != "" {
		req.Name = neighborAddr
	}

	return req, nil
}

// showRoute displays routes for a neighbor
func showRoute(cmd *cobra.Command, args []string, tableType api.TableType, reverse bool, format string, summary bool) error {
	// Initialize gRPC client
	conn, err := grpc.Dial("127.0.0.1:50051", grpc.WithInsecure())
	if err != nil {
		return fmt.Errorf("failed to connect to GoBGP server: %v", err)
	}
	defer conn.Close()

	client := api.NewGobgpApiClient(conn)
	if client == nil {
		return fmt.Errorf("failed to create gRPC client")
	}

	// Get neighbor address from args or flags
	neighborAddr := ""
	if len(args) > 0 && net.ParseIP(args[0]) != nil {
		neighborAddr = args[0]
		args = args[1:]
	}

	// Build request
	req, err := makeShowRouteArgs(client, neighborAddr, args, tableType, reverse, format, summary)
	if err != nil {
		return fmt.Errorf("failed to build route request: %v", err)
	}

	// Query routes
	ctx := context.Background()
	stream, err := client.ListPath(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to list paths: %v", err)
	}

	// Process response
	for {
		resp, err := stream.Recv()
		if err != nil {
			if err.Error() == "EOF" {
				break
			}
			return fmt.Errorf("error receiving paths: %v", err)
		}
		if resp.Destination == nil {
			continue
		}

		// Print paths (simplified for brevity)
		for _, path := range resp.Destination.Paths {
			fmt.Printf("Path: %s\n", path.String())
		}
	}

	return nil
}

// showNeighborRib displays the neighbor's RIB
func showNeighborRib(name, neighborAddr string, args []string) error {
	tableType := api.TableType_ADJ_IN // For adj-in
	reverse, _ := cmdFlags.Bool("reverse")
	summary, _ := cmdFlags.Bool("summary")
	format := "" // Add format handling if needed
	return showRoute(nil, append([]string{neighborAddr}, args...), tableType, reverse, format, summary)
}

// Cobra command setup (simplified)
func newNeighborCmd() *cobra.Command {
	neighborCmd := &cobra.Command{
		Use: "neighbor",
	}
	neighborCmd.AddCommand(&cobra.Command{
		Use: "adj-in [neighbor] [-a <afi-safi>]",
		Run: func(cmd *cobra.Command, args []string) {
			neighborAddr := ""
			afiSafi := "ls" // Default for this example
			if len(args) > 0 {
				neighborAddr = args[0]
				args = args[1:]
			}
			if a, _ := cmd.Flags().GetString("afi-safi"); a != "" {
				afiSafi = a
			}
			if err := showNeighborRib("adj-in", neighborAddr, []string{afiSafi}); err != nil {
				fmt.Printf("Error: %v\n", err)
			}
		},
	})
	return neighborCmd
}

func main() {
	rootCmd := &cobra.Command{Use: "gobgp"}
	rootCmd.AddCommand(newNeighborCmd())
	if err := rootCmd.Execute(); err != nil {
		fmt.Printf("Error: %v\n", err)
	}
}

// Placeholder for cmdFlags (replace with actual flag handling)
var cmdFlags = &cobra.Command{
	Flags: func() *cobra.FlagSet {
		fs := &cobra.FlagSet{}
		fs.String("afi-safi", "", "Address family")
		fs.Bool("reverse", false, "Reverse order")
		fs.Bool("summary", false, "Show summary")
		return fs
	}(),
}

ljluestc avatar Jun 01 '25 02:06 ljluestc