From 922c839c13dce2b5cdc9d3ab1609cd278f92b35e Mon Sep 17 00:00:00 2001 From: jebbs Date: Mon, 10 Oct 2022 16:40:11 +0800 Subject: [PATCH] fix may pick nil outbound if fallback not set --- outbound/balancer.go | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/outbound/balancer.go b/outbound/balancer.go index 0b6e1d9b..2e8bdf8a 100644 --- a/outbound/balancer.go +++ b/outbound/balancer.go @@ -90,6 +90,16 @@ func (s *Balancer) NewPacketConnection(ctx context.Context, conn N.PacketConn, m // initialize inits the balancer func (s *Balancer) initialize() error { + // the fallback is required, in case that all outbounds are not available, + // we can pick it instead of returning nil to avoid panic. + if s.fallbackTag == "" { + return E.New("fallback not set") + } + outbound, loaded := s.router.Outbound(s.fallbackTag) + if !loaded { + return E.New("fallback outbound not found: ", s.fallbackTag) + } + s.fallback = outbound for i, tag := range s.tags { outbound, loaded := s.router.Outbound(tag) if !loaded { @@ -97,13 +107,6 @@ func (s *Balancer) initialize() error { } s.nodes = append(s.nodes, balancer.NewNode(outbound)) } - if s.fallbackTag != "" { - outbound, loaded := s.router.Outbound(s.fallbackTag) - if !loaded { - return E.New("fallback outbound not found: ", s.fallbackTag) - } - s.fallback = outbound - } return nil } @@ -129,7 +132,7 @@ func (s *Balancer) pick() adapter.Outbound { // not started count := len(s.nodes) if count == 0 { - // goes to fallbackTag + // goes to fallback return s.fallback } picked := s.nodes[rand.Intn(count)]