From 58b754a7d344bcb56ffdb5060807bc5d3d74fb10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A3=8E=E6=89=87=E6=BB=91=E7=BF=94=E7=BF=BC?= Date: Tue, 22 Jul 2025 11:11:40 +0000 Subject: [PATCH] Remove wireguard inbound --- infra/conf/wireguard.go | 3 - infra/conf/xray.go | 4 +- proxy/wireguard/client.go | 5 - proxy/wireguard/config.go | 5 - proxy/wireguard/server.go | 194 ---------------------------- proxy/wireguard/server_test.go | 52 -------- proxy/wireguard/wireguard.go | 42 +----- testing/scenarios/wireguard_test.go | 43 +----- 8 files changed, 5 insertions(+), 343 deletions(-) delete mode 100644 proxy/wireguard/server.go delete mode 100644 proxy/wireguard/server_test.go diff --git a/infra/conf/wireguard.go b/infra/conf/wireguard.go index 34ce7215..70eca4f8 100644 --- a/infra/conf/wireguard.go +++ b/infra/conf/wireguard.go @@ -49,8 +49,6 @@ func (c *WireGuardPeerConfig) Build() (proto.Message, error) { } type WireGuardConfig struct { - IsClient bool `json:""` - NoKernelTun bool `json:"noKernelTun"` SecretKey string `json:"secretKey"` Address []string `json:"address"` @@ -117,7 +115,6 @@ func (c *WireGuardConfig) Build() (proto.Message, error) { return nil, errors.New("unsupported domain strategy: ", c.DomainStrategy) } - config.IsClient = c.IsClient config.NoKernelTun = c.NoKernelTun return config, nil diff --git a/infra/conf/xray.go b/infra/conf/xray.go index f1d9fb08..c7d9d4f0 100644 --- a/infra/conf/xray.go +++ b/infra/conf/xray.go @@ -29,7 +29,7 @@ var ( "vless": func() interface{} { return new(VLessInboundConfig) }, "vmess": func() interface{} { return new(VMessInboundConfig) }, "trojan": func() interface{} { return new(TrojanServerConfig) }, - "wireguard": func() interface{} { return &WireGuardConfig{IsClient: false} }, + "wireguard": func() interface{} { return new(WireGuardConfig) }, }, "protocol", "settings") outboundConfigLoader = NewJSONConfigLoader(ConfigCreatorCache{ @@ -43,7 +43,7 @@ var ( "vmess": func() interface{} { return new(VMessOutboundConfig) }, "trojan": func() interface{} { return new(TrojanClientConfig) }, "dns": func() interface{} { return new(DNSOutboundConfig) }, - "wireguard": func() interface{} { return &WireGuardConfig{IsClient: true} }, + "wireguard": func() interface{} { return new(WireGuardConfig) }, }, "protocol", "settings") ctllog = log.New(os.Stderr, "xctl> ", 0) diff --git a/proxy/wireguard/client.go b/proxy/wireguard/client.go index 345581c7..0c98d2a0 100644 --- a/proxy/wireguard/client.go +++ b/proxy/wireguard/client.go @@ -273,11 +273,6 @@ func (h *Handler) createIPCRequest() string { request.WriteString(fmt.Sprintf("private_key=%s\n", h.conf.SecretKey)) - if !h.conf.IsClient { - // placeholder, we'll handle actual port listening on Xray - request.WriteString("listen_port=1337\n") - } - for _, peer := range h.conf.Peers { if peer.PublicKey != "" { request.WriteString(fmt.Sprintf("public_key=%s\n", peer.PublicKey)) diff --git a/proxy/wireguard/config.go b/proxy/wireguard/config.go index cbaa670b..a1c9fa2f 100644 --- a/proxy/wireguard/config.go +++ b/proxy/wireguard/config.go @@ -31,11 +31,6 @@ func (c *DeviceConfig) fallbackIP6() bool { } func (c *DeviceConfig) createTun() tunCreator { - if !c.IsClient { - // See tun_linux.go createKernelTun() - errors.LogWarning(context.Background(), "Using gVisor TUN. WG inbound doesn't support kernel TUN yet.") - return createGVisorTun - } if c.NoKernelTun { errors.LogWarning(context.Background(), "Using gVisor TUN. NoKernelTun is set to true.") return createGVisorTun diff --git a/proxy/wireguard/server.go b/proxy/wireguard/server.go deleted file mode 100644 index bdf27568..00000000 --- a/proxy/wireguard/server.go +++ /dev/null @@ -1,194 +0,0 @@ -package wireguard - -import ( - "context" - goerrors "errors" - "io" - - "github.com/xtls/xray-core/common" - "github.com/xtls/xray-core/common/buf" - "github.com/xtls/xray-core/common/errors" - "github.com/xtls/xray-core/common/log" - "github.com/xtls/xray-core/common/net" - "github.com/xtls/xray-core/common/session" - "github.com/xtls/xray-core/common/signal" - "github.com/xtls/xray-core/common/task" - "github.com/xtls/xray-core/core" - "github.com/xtls/xray-core/features/dns" - "github.com/xtls/xray-core/features/policy" - "github.com/xtls/xray-core/features/routing" - "github.com/xtls/xray-core/transport/internet/stat" -) - -var nullDestination = net.TCPDestination(net.AnyIP, 0) - -type Server struct { - bindServer *netBindServer - - info routingInfo - policyManager policy.Manager -} - -type routingInfo struct { - ctx context.Context - dispatcher routing.Dispatcher - inboundTag *session.Inbound - outboundTag *session.Outbound - contentTag *session.Content -} - -func NewServer(ctx context.Context, conf *DeviceConfig) (*Server, error) { - v := core.MustFromContext(ctx) - - endpoints, hasIPv4, hasIPv6, err := parseEndpoints(conf) - if err != nil { - return nil, err - } - - server := &Server{ - bindServer: &netBindServer{ - netBind: netBind{ - dns: v.GetFeature(dns.ClientType()).(dns.Client), - dnsOption: dns.IPOption{ - IPv4Enable: hasIPv4, - IPv6Enable: hasIPv6, - }, - }, - }, - policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager), - } - - tun, err := conf.createTun()(endpoints, int(conf.Mtu), server.forwardConnection) - if err != nil { - return nil, err - } - - if err = tun.BuildDevice(createIPCRequest(conf), server.bindServer); err != nil { - _ = tun.Close() - return nil, err - } - - return server, nil -} - -// Network implements proxy.Inbound. -func (*Server) Network() []net.Network { - return []net.Network{net.Network_UDP} -} - -// Process implements proxy.Inbound. -func (s *Server) Process(ctx context.Context, network net.Network, conn stat.Connection, dispatcher routing.Dispatcher) error { - inbound := session.InboundFromContext(ctx) - inbound.Name = "wireguard" - inbound.CanSpliceCopy = 3 - outbounds := session.OutboundsFromContext(ctx) - ob := outbounds[len(outbounds)-1] - - s.info = routingInfo{ - ctx: core.ToBackgroundDetachedContext(ctx), - dispatcher: dispatcher, - inboundTag: session.InboundFromContext(ctx), - outboundTag: ob, - contentTag: session.ContentFromContext(ctx), - } - - ep, err := s.bindServer.ParseEndpoint(conn.RemoteAddr().String()) - if err != nil { - return err - } - - nep := ep.(*netEndpoint) - nep.conn = conn - - reader := buf.NewPacketReader(conn) - for { - mpayload, err := reader.ReadMultiBuffer() - if err != nil { - return err - } - - for _, payload := range mpayload { - v, ok := <-s.bindServer.readQueue - if !ok { - return nil - } - i, err := payload.Read(v.buff) - - v.bytes = i - v.endpoint = nep - v.err = err - v.waiter.Done() - if err != nil && goerrors.Is(err, io.EOF) { - nep.conn = nil - return nil - } - } - } -} - -func (s *Server) forwardConnection(dest net.Destination, conn net.Conn) { - if s.info.dispatcher == nil { - errors.LogError(s.info.ctx, "unexpected: dispatcher == nil") - return - } - defer conn.Close() - - ctx, cancel := context.WithCancel(core.ToBackgroundDetachedContext(s.info.ctx)) - plcy := s.policyManager.ForLevel(0) - timer := signal.CancelAfterInactivity(ctx, cancel, plcy.Timeouts.ConnectionIdle) - - ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{ - From: nullDestination, - To: dest, - Status: log.AccessAccepted, - Reason: "", - }) - - if s.info.inboundTag != nil { - ctx = session.ContextWithInbound(ctx, s.info.inboundTag) - } - - // what's this? - // Session information should not be shared between different connections - // why reuse them in server level? This will cause incorrect destoverride and unexpected routing behavior. - // Disable it temporarily. Maybe s.info should be removed. - - // if s.info.outboundTag != nil { - // ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{s.info.outboundTag}) - // } - // if s.info.contentTag != nil { - // ctx = session.ContextWithContent(ctx, s.info.contentTag) - // } - - link, err := s.info.dispatcher.Dispatch(ctx, dest) - if err != nil { - errors.LogErrorInner(s.info.ctx, err, "dispatch connection") - } - defer cancel() - - requestDone := func() error { - defer timer.SetTimeout(plcy.Timeouts.DownlinkOnly) - if err := buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer)); err != nil { - return errors.New("failed to transport all TCP request").Base(err) - } - - return nil - } - - responseDone := func() error { - defer timer.SetTimeout(plcy.Timeouts.UplinkOnly) - if err := buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer)); err != nil { - return errors.New("failed to transport all TCP response").Base(err) - } - - return nil - } - - requestDonePost := task.OnSuccess(requestDone, task.Close(link.Writer)) - if err := task.Run(ctx, requestDonePost, responseDone); err != nil { - common.Interrupt(link.Reader) - common.Interrupt(link.Writer) - errors.LogDebugInner(s.info.ctx, err, "connection ends") - return - } -} diff --git a/proxy/wireguard/server_test.go b/proxy/wireguard/server_test.go deleted file mode 100644 index 057b508e..00000000 --- a/proxy/wireguard/server_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package wireguard_test - -import ( - "context" - "github.com/stretchr/testify/assert" - "runtime/debug" - "testing" - - "github.com/xtls/xray-core/core" - "github.com/xtls/xray-core/proxy/wireguard" -) - -// TestWireGuardServerInitializationError verifies that an error during TUN initialization -// (triggered by an empty SecretKey) in the WireGuard server does not cause a panic and returns an error instead. -func TestWireGuardServerInitializationError(t *testing.T) { - // Create a minimal core instance with default features - config := &core.Config{} - instance, err := core.New(config) - if err != nil { - t.Fatalf("Failed to create core instance: %v", err) - } - // Set the Xray instance in the context - ctx := context.WithValue(context.Background(), core.XrayKey(1), instance) - - // Define the server configuration with an empty SecretKey to trigger error - conf := &wireguard.DeviceConfig{ - IsClient: false, - Endpoint: []string{"10.0.0.1/32"}, - Mtu: 1420, - SecretKey: "", // Empty SecretKey to trigger error - Peers: []*wireguard.PeerConfig{ - { - PublicKey: "some_public_key", - AllowedIps: []string{"10.0.0.2/32"}, - }, - }, - } - - // Use defer to catch any panic and fail the test explicitly - defer func() { - if r := recover(); r != nil { - t.Errorf("TUN initialization panicked: %v", r) - debug.PrintStack() - } - }() - - // Attempt to initialize the WireGuard server - _, err = wireguard.NewServer(ctx, conf) - - // Check that an error is returned - assert.ErrorContains(t, err, "failed to set private_key: hex string does not fit the slice") -} diff --git a/proxy/wireguard/wireguard.go b/proxy/wireguard/wireguard.go index 0d75ee00..60699711 100644 --- a/proxy/wireguard/wireguard.go +++ b/proxy/wireguard/wireguard.go @@ -30,11 +30,7 @@ var wgLogger = &device.Logger{ func init() { common.Must(common.RegisterConfig((*DeviceConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { deviceConfig := config.(*DeviceConfig) - if deviceConfig.IsClient { - return New(ctx, deviceConfig) - } else { - return NewServer(ctx, deviceConfig) - } + return New(ctx, deviceConfig) })) } @@ -72,39 +68,3 @@ func parseEndpoints(conf *DeviceConfig) ([]netip.Addr, bool, bool, error) { return endpoints, hasIPv4, hasIPv6, nil } - -// serialize the config into an IPC request -func createIPCRequest(conf *DeviceConfig) string { - var request strings.Builder - - request.WriteString(fmt.Sprintf("private_key=%s\n", conf.SecretKey)) - - if !conf.IsClient { - // placeholder, we'll handle actual port listening on Xray - request.WriteString("listen_port=1337\n") - } - - for _, peer := range conf.Peers { - if peer.PublicKey != "" { - request.WriteString(fmt.Sprintf("public_key=%s\n", peer.PublicKey)) - } - - if peer.PreSharedKey != "" { - request.WriteString(fmt.Sprintf("preshared_key=%s\n", peer.PreSharedKey)) - } - - if peer.Endpoint != "" { - request.WriteString(fmt.Sprintf("endpoint=%s\n", peer.Endpoint)) - } - - for _, ip := range peer.AllowedIps { - request.WriteString(fmt.Sprintf("allowed_ip=%s\n", ip)) - } - - if peer.KeepAlive != 0 { - request.WriteString(fmt.Sprintf("persistent_keepalive_interval=%d\n", peer.KeepAlive)) - } - } - - return request.String()[:request.Len()] -} diff --git a/testing/scenarios/wireguard_test.go b/testing/scenarios/wireguard_test.go index deaee114..eba41292 100644 --- a/testing/scenarios/wireguard_test.go +++ b/testing/scenarios/wireguard_test.go @@ -13,10 +13,8 @@ import ( core "github.com/xtls/xray-core/core" "github.com/xtls/xray-core/infra/conf" "github.com/xtls/xray-core/proxy/dokodemo" - "github.com/xtls/xray-core/proxy/freedom" "github.com/xtls/xray-core/proxy/wireguard" "github.com/xtls/xray-core/testing/servers/tcp" - "github.com/xtls/xray-core/testing/servers/udp" //"golang.org/x/sync/errgroup" ) @@ -28,45 +26,9 @@ func TestWireguard(t *testing.T) { common.Must(err) defer tcpServer.Close() - serverPrivate, _ := conf.ParseWireGuardKey("EGs4lTSJPmgELx6YiJAmPR2meWi6bY+e9rTdCipSj10=") - serverPublic, _ := conf.ParseWireGuardKey("osAMIyil18HeZXGGBDC9KpZoM+L2iGyXWVSYivuM9B0=") clientPrivate, _ := conf.ParseWireGuardKey("CPQSpgxgdQRZa5SUbT3HLv+mmDVHLW5YR/rQlzum/2I=") clientPublic, _ := conf.ParseWireGuardKey("MmLJ5iHFVVBp7VsB0hxfpQ0wEzAbT2KQnpQpj0+RtBw=") - serverPort := udp.PickPort() - serverConfig := &core.Config{ - App: []*serial.TypedMessage{ - serial.ToTypedMessage(&log.Config{ - ErrorLogLevel: clog.Severity_Debug, - ErrorLogType: log.LogType_Console, - }), - }, - Inbound: []*core.InboundHandlerConfig{ - { - ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{ - PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(serverPort)}}, - Listen: net.NewIPOrDomain(net.LocalHostIP), - }), - ProxySettings: serial.ToTypedMessage(&wireguard.DeviceConfig{ - IsClient: false, - NoKernelTun: false, - Endpoint: []string{"10.0.0.1"}, - Mtu: 1420, - SecretKey: serverPrivate, - Peers: []*wireguard.PeerConfig{{ - PublicKey: serverPublic, - AllowedIps: []string{"0.0.0.0/0", "::0/0"}, - }}, - }), - }, - }, - Outbound: []*core.OutboundHandlerConfig{ - { - ProxySettings: serial.ToTypedMessage(&freedom.Config{}), - }, - }, - } - clientPort := tcp.PickPort() clientConfig := &core.Config{ App: []*serial.TypedMessage{ @@ -91,13 +53,12 @@ func TestWireguard(t *testing.T) { Outbound: []*core.OutboundHandlerConfig{ { ProxySettings: serial.ToTypedMessage(&wireguard.DeviceConfig{ - IsClient: true, NoKernelTun: false, Endpoint: []string{"10.0.0.2"}, Mtu: 1420, SecretKey: clientPrivate, Peers: []*wireguard.PeerConfig{{ - Endpoint: "127.0.0.1:" + serverPort.String(), + Endpoint: "127.0.0.1:12777", PublicKey: clientPublic, AllowedIps: []string{"0.0.0.0/0", "::0/0"}, }}, @@ -106,7 +67,7 @@ func TestWireguard(t *testing.T) { }, } - servers, err := InitializeServerConfigs(serverConfig, clientConfig) + servers, err := InitializeServerConfigs(clientConfig) common.Must(err) defer CloseAllServers(servers)