better vpn service handler

This commit is contained in:
Hiddify
2024-03-16 22:14:08 +01:00
parent 3e48086e67
commit 84e5933d9d
2 changed files with 44 additions and 5 deletions

View File

@@ -4,6 +4,7 @@ import (
context "context" context "context"
"fmt" "fmt"
"log" "log"
"net"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "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) { 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()) conn, err := grpc.Dial("127.0.0.1:18020", grpc.WithInsecure())
if err != nil { if err != nil {
log.Printf("did not connect: %v", err) log.Printf("did not connect: %v", err)
} }
defer conn.Close() defer conn.Close()
c := pb.NewTunnelServiceClient(conn) c := pb.NewTunnelServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*1) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel() defer cancel()
_, err = c.Start(ctx, &pb.TunnelStartRequest{ res, err := c.Start(ctx, &pb.TunnelStartRequest{
Ipv6: opt.IPv6Mode == option.DomainStrategy(dns.DomainStrategyUseIPv4), Ipv6: opt.IPv6Mode == option.DomainStrategy(dns.DomainStrategyUseIPv4),
ServerPort: int32(opt.InboundOptions.MixedPort), ServerPort: int32(opt.InboundOptions.MixedPort),
StrictRoute: opt.InboundOptions.StrictRoute, StrictRoute: opt.InboundOptions.StrictRoute,
@@ -83,9 +97,10 @@ func startTunnelRequest(opt ConfigOptions, installService bool) (bool, error) {
Stack: opt.InboundOptions.TUNStack, Stack: opt.InboundOptions.TUNStack,
}) })
if err != nil { if err != nil {
log.Printf("could not greet: %v", err) log.Printf("could not greet: %+v %+v", res, err)
if installService { if installService {
ExitTunnelService()
return runTunnelService(opt) return runTunnelService(opt)
} }
return false, err return false, err

View File

@@ -60,8 +60,32 @@ func makeTunnelConfig(Ipv6 bool, ServerPort int32, StrictRoute bool, EndpointInd
"server": "127.0.0.1", "server": "127.0.0.1",
"server_port": ` + fmt.Sprintf("%d", ServerPort) + `, "server_port": ` + fmt.Sprintf("%d", ServerPort) + `,
"version": "5" "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 return base