From 84e5933d9dff3b9d117ce0d7342d6c976465307a Mon Sep 17 00:00:00 2001 From: Hiddify Date: Sat, 16 Mar 2024 22:14:08 +0100 Subject: [PATCH] better vpn service handler --- config/admin_service_commander.go | 23 +++++++++++++++++++---- v2/tunnel_service.go | 26 +++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/config/admin_service_commander.go b/config/admin_service_commander.go index c5ced53..00fada8 100644 --- a/config/admin_service_commander.go +++ b/config/admin_service_commander.go @@ -4,6 +4,7 @@ import ( context "context" "fmt" "log" + "net" "os" "path/filepath" "runtime" @@ -65,17 +66,30 @@ func startTunnelRequestWithFailover(opt ConfigOptions, installService bool) { } } - +func isPortInUse(port string) bool { + listener, err := net.Listen("tcp", "127.0.0.1:"+port) + if err != nil { + return true // Port is in use + } + defer listener.Close() + return false // Port is available +} func startTunnelRequest(opt ConfigOptions, installService bool) (bool, error) { + if !isPortInUse("18020") { + if installService { + return runTunnelService(opt) + } + return false, fmt.Errorf("service is not running") + } conn, err := grpc.Dial("127.0.0.1:18020", grpc.WithInsecure()) if err != nil { log.Printf("did not connect: %v", err) } defer conn.Close() c := pb.NewTunnelServiceClient(conn) - ctx, cancel := context.WithTimeout(context.Background(), time.Second*1) + ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) defer cancel() - _, err = c.Start(ctx, &pb.TunnelStartRequest{ + res, err := c.Start(ctx, &pb.TunnelStartRequest{ Ipv6: opt.IPv6Mode == option.DomainStrategy(dns.DomainStrategyUseIPv4), ServerPort: int32(opt.InboundOptions.MixedPort), StrictRoute: opt.InboundOptions.StrictRoute, @@ -83,9 +97,10 @@ func startTunnelRequest(opt ConfigOptions, installService bool) (bool, error) { Stack: opt.InboundOptions.TUNStack, }) if err != nil { - log.Printf("could not greet: %v", err) + log.Printf("could not greet: %+v %+v", res, err) if installService { + ExitTunnelService() return runTunnelService(opt) } return false, err diff --git a/v2/tunnel_service.go b/v2/tunnel_service.go index 92507fd..14f6f3c 100644 --- a/v2/tunnel_service.go +++ b/v2/tunnel_service.go @@ -60,8 +60,32 @@ func makeTunnelConfig(Ipv6 bool, ServerPort int32, StrictRoute bool, EndpointInd "server": "127.0.0.1", "server_port": ` + fmt.Sprintf("%d", ServerPort) + `, "version": "5" + }, + { + "type": "direct", + "tag": "direct-out" } - ] + ], + "route": { + "rules": [ + { + "process_name":"Hiddify.exe", + "outbound": "direct-out" + }, + { + "process_name":"Hiddify", + "outbound": "direct-out" + }, + { + "process_name":"HiddifyCli", + "outbound": "direct-out" + }, + { + "process_name":"HiddifyCli.exe", + "outbound": "direct-out" + } + ] + } }` return base