diff --git a/adapter/endpoint.go b/adapter/endpoint.go index 63d7ce9d..81d94030 100644 --- a/adapter/endpoint.go +++ b/adapter/endpoint.go @@ -12,6 +12,7 @@ type Endpoint interface { Type() string Tag() string Outbound + IsEndpoint() } type EndpointRegistry interface { diff --git a/adapter/endpoint/adapter.go b/adapter/endpoint/adapter.go index c75e4d83..e5c33f43 100644 --- a/adapter/endpoint/adapter.go +++ b/adapter/endpoint/adapter.go @@ -41,3 +41,6 @@ func (a *Adapter) Network() []string { func (a *Adapter) Dependencies() []string { return a.dependencies } + +func (a *Adapter) IsEndpoint() { +} diff --git a/adapter/outbound/manager.go b/adapter/outbound/manager.go index fd616363..d2713a59 100644 --- a/adapter/outbound/manager.go +++ b/adapter/outbound/manager.go @@ -3,6 +3,7 @@ package outbound import ( "context" "os" + "slices" "strings" "sync" @@ -62,16 +63,26 @@ func (m *Manager) Start(stage adapter.StartStage, scope *adapter.Scope) error { } outbounds := m.outbounds m.access.Unlock() - if stage == adapter.StartStateStart { - return m.startOutbounds(scope, append(outbounds, common.Map(m.endpoint.Endpoints(), func(it adapter.Endpoint) adapter.Outbound { return it })...)) + sortedOutbounds, err := sortOutbounds(slices.Concat(outbounds, common.Map(m.endpoint.Endpoints(), func(it adapter.Endpoint) adapter.Outbound { return it }))) + if err != nil { + return err } - for _, outbound := range outbounds { + for _, outbound := range sortedOutbounds { + if endpoint, isEndpoint := outbound.(adapter.Endpoint); isEndpoint { + if stage == adapter.StartStateStart { + err = m.endpoint.StartEndpoint(endpoint) + if err != nil { + return err + } + } + continue + } lifecycle, isLifecycle := outbound.(adapter.Lifecycle) if !isLifecycle { continue } name := "outbound/" + outbound.Type() + "[" + outbound.Tag() + "]" - err := scope.Start(name, lifecycle, stage) + err = scope.Start(name, lifecycle, stage) if err != nil { return err } @@ -79,54 +90,40 @@ func (m *Manager) Start(stage adapter.StartStage, scope *adapter.Scope) error { return nil } -func (m *Manager) startOutbounds(scope *adapter.Scope, outbounds []adapter.Outbound) error { - started := make(map[string]bool) +func sortOutbounds(outbounds []adapter.Outbound) ([]adapter.Outbound, error) { + sortedOutbounds := make([]adapter.Outbound, 0, len(outbounds)) + sorted := make(map[string]bool) for { canContinue := false - startOne: - for _, outboundToStart := range outbounds { - outboundTag := outboundToStart.Tag() - if started[outboundTag] { + sortOne: + for _, outboundToSort := range outbounds { + outboundTag := outboundToSort.Tag() + if sorted[outboundTag] { continue } - dependencies := outboundToStart.Dependencies() + dependencies := outboundToSort.Dependencies() for _, dependency := range dependencies { - if !started[dependency] { - continue startOne + if !sorted[dependency] { + continue sortOne } } - started[outboundTag] = true + sorted[outboundTag] = true canContinue = true - if endpoint, isEndpoint := outboundToStart.(adapter.Endpoint); isEndpoint { - err := m.endpoint.StartEndpoint(endpoint) - if err != nil { - return err - } - continue - } - lifecycle, isLifecycle := outboundToStart.(adapter.Lifecycle) - if !isLifecycle { - continue - } - name := "outbound/" + outboundToStart.Type() + "[" + outboundTag + "]" - err := scope.Start(name, lifecycle, adapter.StartStateStart) - if err != nil { - return err - } + sortedOutbounds = append(sortedOutbounds, outboundToSort) } - if len(started) == len(outbounds) { + if len(sorted) == len(outbounds) { break } if canContinue { continue } currentOutbound := common.Find(outbounds, func(it adapter.Outbound) bool { - return !started[it.Tag()] + return !sorted[it.Tag()] }) var lintOutbound func(oTree []string, oCurrent adapter.Outbound) error lintOutbound = func(oTree []string, oCurrent adapter.Outbound) error { problemOutboundTag := common.Find(oCurrent.Dependencies(), func(it string) bool { - return !started[it] + return !sorted[it] }) if common.Contains(oTree, problemOutboundTag) { return E.New("circular outbound dependency: ", strings.Join(oTree, " -> "), " -> ", problemOutboundTag) @@ -139,9 +136,9 @@ func (m *Manager) startOutbounds(scope *adapter.Scope, outbounds []adapter.Outbo } return lintOutbound(append(oTree, problemOutboundTag), problemOutbound) } - return lintOutbound([]string{currentOutbound.Tag()}, currentOutbound) + return nil, lintOutbound([]string{currentOutbound.Tag()}, currentOutbound) } - return nil + return sortedOutbounds, nil } func (m *Manager) Outbounds() []adapter.Outbound { diff --git a/dns/transport_manager.go b/dns/transport_manager.go index f1a69ecf..dda6d5a1 100644 --- a/dns/transport_manager.go +++ b/dns/transport_manager.go @@ -60,12 +60,13 @@ func (m *TransportManager) Start(stage adapter.StartStage, scope *adapter.Scope) } transports := m.transports m.access.Unlock() - if stage == adapter.StartStateStart { - return m.startTransports(scope, transports) + sortedTransports, err := m.sortTransports(transports) + if err != nil { + return err } - for _, transport := range transports { + for _, transport := range sortedTransports { name := "dns/" + transport.Type() + "[" + transport.Tag() + "]" - err := scope.Start(name, transport, stage) + err = scope.Start(name, transport, stage) if err != nil { return err } @@ -73,43 +74,40 @@ func (m *TransportManager) Start(stage adapter.StartStage, scope *adapter.Scope) return nil } -func (m *TransportManager) startTransports(scope *adapter.Scope, transports []adapter.DNSTransport) error { - started := make(map[string]bool) +func (m *TransportManager) sortTransports(transports []adapter.DNSTransport) ([]adapter.DNSTransport, error) { + sortedTransports := make([]adapter.DNSTransport, 0, len(transports)) + sorted := make(map[string]bool) for { canContinue := false - startOne: - for _, transportToStart := range transports { - transportTag := transportToStart.Tag() - if started[transportTag] { + sortOne: + for _, transportToSort := range transports { + transportTag := transportToSort.Tag() + if sorted[transportTag] { continue } - dependencies := transportToStart.Dependencies() + dependencies := transportToSort.Dependencies() for _, dependency := range dependencies { - if !started[dependency] { - continue startOne + if !sorted[dependency] { + continue sortOne } } - started[transportTag] = true + sorted[transportTag] = true canContinue = true - name := "dns/" + transportToStart.Type() + "[" + transportTag + "]" - err := scope.Start(name, transportToStart, adapter.StartStateStart) - if err != nil { - return err - } + sortedTransports = append(sortedTransports, transportToSort) } - if len(started) == len(transports) { + if len(sorted) == len(transports) { break } if canContinue { continue } currentTransport := common.Find(transports, func(it adapter.DNSTransport) bool { - return !started[it.Tag()] + return !sorted[it.Tag()] }) var lintTransport func(oTree []string, oCurrent adapter.DNSTransport) error lintTransport = func(oTree []string, oCurrent adapter.DNSTransport) error { problemTransportTag := common.Find(oCurrent.Dependencies(), func(it string) bool { - return !started[it] + return !sorted[it] }) if common.Contains(oTree, problemTransportTag) { return E.New("circular server dependency: ", strings.Join(oTree, " -> "), " -> ", problemTransportTag) @@ -122,9 +120,9 @@ func (m *TransportManager) startTransports(scope *adapter.Scope, transports []ad } return lintTransport(append(oTree, problemTransportTag), problemTransport) } - return lintTransport([]string{currentTransport.Tag()}, currentTransport) + return nil, lintTransport([]string{currentTransport.Tag()}, currentTransport) } - return nil + return sortedTransports, nil } func (m *TransportManager) Transports() []adapter.DNSTransport { diff --git a/protocol/openconnect/client.go b/protocol/openconnect/client.go index 2bb9a3d7..e2c61bc1 100644 --- a/protocol/openconnect/client.go +++ b/protocol/openconnect/client.go @@ -478,10 +478,10 @@ func (e *Endpoint) readLoop(ctx context.Context) { err = e.device.WriteInboundBuffers(packetBuffers) buf.ReleaseMulti(packetBuffers) if err != nil { - err = E.Cause(err, "write packet to device") - e.logger.Error(err) - e.setTerminalError(err) - return + if E.IsCanceled(err) || ctx.Err() != nil { + return + } + e.logger.Debug(E.Cause(err, "write packet to device")) } } } diff --git a/protocol/openvpn/client.go b/protocol/openvpn/client.go index a0e585e0..98f8f274 100644 --- a/protocol/openvpn/client.go +++ b/protocol/openvpn/client.go @@ -654,10 +654,10 @@ func (c *ClientEndpoint) readLoop(ctx context.Context) { err = c.device.WriteInboundBuffers(packetBuffers) buf.ReleaseMulti(packetBuffers) if err != nil { - err = E.Cause(err, "write packet to device") - c.logger.Error(err) - c.setTerminalError(err) - return + if E.IsCanceled(err) || ctx.Err() != nil { + return + } + c.logger.Debug(E.Cause(err, "write packet to device")) } } } diff --git a/protocol/openvpn/server.go b/protocol/openvpn/server.go index 269b7a9e..984b4234 100644 --- a/protocol/openvpn/server.go +++ b/protocol/openvpn/server.go @@ -627,8 +627,10 @@ func (s *ServerEndpoint) readLoop(ctx context.Context) { err = s.device.WriteInboundBuffers(packetBuffers) buf.ReleaseMulti(packetBuffers) if err != nil { - s.logger.Error(E.Cause(err, "write packet to device")) - return + if E.IsCanceled(err) || ctx.Err() != nil { + return + } + s.logger.Debug(E.Cause(err, "write packet to device")) } } } diff --git a/protocol/wireguard/endpoint.go b/protocol/wireguard/endpoint.go index 4d51968e..c31a2b06 100644 --- a/protocol/wireguard/endpoint.go +++ b/protocol/wireguard/endpoint.go @@ -202,7 +202,7 @@ func (w *Endpoint) DetachReturn(returnPath tun.Return) error { func (w *Endpoint) JudgeFlow(network uint8, source netip.AddrPort, destination netip.AddrPort, firstPacket []byte) tun.FlowVerdict { for _, localPrefix := range w.localAddresses { - if localPrefix.Contains(destination.Addr()) { + if destination.Addr() == localPrefix.Addr() { return tun.FlowVerdict{Action: tun.ActionAccept} } } @@ -235,7 +235,7 @@ func (w *Endpoint) NewConnectionEx(ctx context.Context, conn net.Conn, source M. metadata.InboundType = w.Type() metadata.Source = source for _, localPrefix := range w.localAddresses { - if localPrefix.Contains(destination.Addr) { + if destination.Addr == localPrefix.Addr() { metadata.OriginDestination = destination if destination.Addr.Is4() { destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1}) @@ -258,7 +258,7 @@ func (w *Endpoint) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, metadata.Source = source metadata.Destination = destination for _, localPrefix := range w.localAddresses { - if localPrefix.Contains(destination.Addr) { + if destination.Addr == localPrefix.Addr() { metadata.OriginDestination = destination if destination.Addr.Is4() { metadata.Destination.Addr = netip.AddrFrom4([4]uint8{127, 0, 0, 1}) diff --git a/transport/openconnect/device_system.go b/transport/openconnect/device_system.go index abca06d7..fca3fe34 100644 --- a/transport/openconnect/device_system.go +++ b/transport/openconnect/device_system.go @@ -29,13 +29,15 @@ const ( type systemDevice struct { baseDevice - stateAccess sync.RWMutex - options DeviceOptions - dialer N.Dialer - device tun.Tun - inet4Address netip.Addr - inet6Address netip.Addr - closed bool + stateAccess sync.RWMutex + options DeviceOptions + dialer N.Dialer + device tun.Tun + readLoopDone chan struct{} + reconfiguring bool + inet4Address netip.Addr + inet6Address netip.Addr + closed bool } func newSystemDevice(options DeviceOptions) (*systemDevice, error) { @@ -87,7 +89,13 @@ func (d *systemDevice) startLocked() error { } d.device = tunInterface d.options.Logger.Info("started at ", d.options.Name) - go d.readLoop(tunInterface, int(d.options.MTU)) + readLoopDone := make(chan struct{}) + d.readLoopDone = readLoopDone + mtu := int(d.options.MTU) + go func() { + d.readLoop(tunInterface, mtu) + close(readLoopDone) + }() return nil } @@ -239,8 +247,15 @@ func (d *systemDevice) UpdateConfiguration(configuration Configuration) error { } if !slices.Equal(previousConfiguration.Addresses, configuration.Addresses) || previousMTU != updatedMTU { - d.device.Close() + oldDevice := d.device + readLoopDone := d.readLoopDone d.device = nil + d.reconfiguring = true + d.stateAccess.Unlock() + oldDevice.Close() + <-readLoopDone + d.stateAccess.Lock() + d.reconfiguring = false return d.startLocked() } return nil @@ -253,8 +268,12 @@ func (d *systemDevice) WriteInboundBuffers(packetBuffers []*buf.Buffer) error { func (d *systemDevice) writeBuffers(packetBuffers []*buf.Buffer) error { d.stateAccess.RLock() tunInterface := d.device + reconfiguring := d.reconfiguring d.stateAccess.RUnlock() if tunInterface == nil { + if reconfiguring { + return nil + } return E.New("system device is not ready") } linuxTUN, isLinuxTUN := tunInterface.(tun.LinuxTUN) @@ -296,8 +315,12 @@ func (d *systemDevice) writeBuffers(packetBuffers []*buf.Buffer) error { func (d *systemDevice) writePacket(packet []byte) error { d.stateAccess.RLock() tunInterface := d.device + reconfiguring := d.reconfiguring d.stateAccess.RUnlock() if tunInterface == nil { + if reconfiguring { + return nil + } return E.New("system device is not ready") } if tun.PacketOffset == 0 { diff --git a/transport/openvpn/device_system.go b/transport/openvpn/device_system.go index 93421ee3..7557b164 100644 --- a/transport/openvpn/device_system.go +++ b/transport/openvpn/device_system.go @@ -29,13 +29,15 @@ const ( type systemDevice struct { baseDevice - stateAccess sync.RWMutex - options DeviceOptions - dialer N.Dialer - device tun.Tun - inet4Address netip.Addr - inet6Address netip.Addr - closed bool + stateAccess sync.RWMutex + options DeviceOptions + dialer N.Dialer + device tun.Tun + readLoopDone chan struct{} + reconfiguring bool + inet4Address netip.Addr + inet6Address netip.Addr + closed bool } func newSystemDevice(options DeviceOptions) (*systemDevice, error) { @@ -87,7 +89,13 @@ func (d *systemDevice) startLocked() error { } d.device = tunInterface d.options.Logger.Info("started at ", d.options.Name) - go d.readLoop(tunInterface, int(d.options.MTU)) + readLoopDone := make(chan struct{}) + d.readLoopDone = readLoopDone + mtu := int(d.options.MTU) + go func() { + d.readLoop(tunInterface, mtu) + close(readLoopDone) + }() return nil } @@ -254,8 +262,15 @@ func (d *systemDevice) UpdateConfiguration(configuration Configuration) error { } if !slices.Equal(previousConfiguration.Address, configuration.Address) || previousMTU != updatedMTU { - d.device.Close() + oldDevice := d.device + readLoopDone := d.readLoopDone d.device = nil + d.reconfiguring = true + d.stateAccess.Unlock() + oldDevice.Close() + <-readLoopDone + d.stateAccess.Lock() + d.reconfiguring = false return d.startLocked() } return nil @@ -274,8 +289,12 @@ func (d *systemDevice) WriteInboundBuffers(packetBuffers []*buf.Buffer) error { func (d *systemDevice) writeBuffers(packetBuffers []*buf.Buffer) error { d.stateAccess.RLock() tunInterface := d.device + reconfiguring := d.reconfiguring d.stateAccess.RUnlock() if tunInterface == nil { + if reconfiguring { + return nil + } return E.New("system device is not ready") } linuxTUN, isLinuxTUN := tunInterface.(tun.LinuxTUN) @@ -317,8 +336,12 @@ func (d *systemDevice) writeBuffers(packetBuffers []*buf.Buffer) error { func (d *systemDevice) writePacket(packet []byte) error { d.stateAccess.RLock() tunInterface := d.device + reconfiguring := d.reconfiguring d.stateAccess.RUnlock() if tunInterface == nil { + if reconfiguring { + return nil + } return E.New("system device is not ready") } if tun.PacketOffset == 0 { diff --git a/transport/wireguard/device_system_stack.go b/transport/wireguard/device_system_stack.go index ae92235b..0eac9077 100644 --- a/transport/wireguard/device_system_stack.go +++ b/transport/wireguard/device_system_stack.go @@ -170,7 +170,7 @@ func (w *systemStackDevice) writeStack(packet []byte) bool { destination = netip.AddrFrom16(header.IPv6(packet).DestinationAddress().As16()) } for _, prefix := range w.options.Address { - if prefix.Contains(destination) { + if destination == prefix.Addr() { return false } }