diff --git a/libv2ray_main.go b/libv2ray_main.go index 68af7eff..a31ac4ed 100644 --- a/libv2ray_main.go +++ b/libv2ray_main.go @@ -33,11 +33,12 @@ const ( // CoreController represents a controller for managing Xray core instance lifecycle type CoreController struct { - CallbackHandler CoreCallbackHandler - statsManager corestats.Manager - coreMutex sync.Mutex - coreInstance *core.Instance - IsRunning bool + CallbackHandler CoreCallbackHandler + statsManager corestats.Manager + coreMutex sync.Mutex + coreInstance *core.Instance + balancerFallbacks map[string]string + IsRunning bool } // CoreCallbackHandler defines interface for receiving callbacks and notifications from the core service @@ -157,6 +158,7 @@ func (x *CoreController) doShutdown() { } x.IsRunning = false x.statsManager = nil + x.balancerFallbacks = nil } // doStartLoop sets up and starts the Xray core @@ -180,6 +182,7 @@ func (x *CoreController) doStartLoop(configContent string) error { return fmt.Errorf("startup failed: %w", err) } + x.balancerFallbacks = configuredBalancerFallbacks(config) x.CallbackHandler.Startup() x.CallbackHandler.OnEmitStatus(0, "Started successfully, running") diff --git a/libv2ray_url_request_test.go b/libv2ray_url_request_test.go new file mode 100644 index 00000000..05b70cfb --- /dev/null +++ b/libv2ray_url_request_test.go @@ -0,0 +1,178 @@ +package libv2ray + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + core "github.com/xtls/xray-core/core" + coreserial "github.com/xtls/xray-core/infra/conf/serial" +) + +func TestApplyRequestHeaders(t *testing.T) { + req, err := http.NewRequest(http.MethodGet, "https://example.com", nil) + if err != nil { + t.Fatal(err) + } + + applyRequestHeaders(req, map[string]string{ + "host": "origin.example", + "X-Test": "value", + }) + + if req.Host != "origin.example" { + t.Fatalf("Host = %q, want %q", req.Host, "origin.example") + } + if got := req.Header.Get("Host"); got != "" { + t.Fatalf("Header[Host] = %q, want empty", got) + } + if got := req.Header.Get("X-Test"); got != "value" { + t.Fatalf("X-Test = %q, want %q", got, "value") + } +} + +func TestDownloadUrlToFileWithHeaders(t *testing.T) { + controller := testHTTPController(t) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/redirect" { + w.Header().Set("Profile-Title", "intermediate") + http.Redirect(w, r, "/subscription", http.StatusFound) + return + } + if r.Header.Get("X-Test") != "request" { + w.WriteHeader(http.StatusForbidden) + return + } + w.Header().Set("Subscription-Userinfo", "upload=1; download=2; total=100; expire=2000000000") + w.Header().Set("Profile-Title", "base64:dGVzdA==") + w.Header().Set("Support-Url", "https://example.com/support") + w.Header().Set("Profile-Web-Page-Url", "https://example.com/account") + w.Header().Add("X-Repeated", "first") + w.Header().Add("X-Repeated", "second") + _, _ = w.Write([]byte("subscription body")) + })) + defer server.Close() + path := filepath.Join(t.TempDir(), "subscription") + headersJSON, err := controller.DownloadUrlToFileWithHeaders(server.URL+"/redirect", "proxy", `{"X-Test":"request"}`, path, 1000) + if err != nil { + t.Fatal(err) + } + var headers http.Header + if err := json.Unmarshal([]byte(headersJSON), &headers); err != nil { + t.Fatal(err) + } + for name, want := range map[string]string{ + "Subscription-Userinfo": "upload=1; download=2; total=100; expire=2000000000", + "Profile-Title": "base64:dGVzdA==", + "Support-Url": "https://example.com/support", + "Profile-Web-Page-Url": "https://example.com/account", + } { + if got := headers.Get(name); got != want { + t.Errorf("%s = %q, want %q", name, got, want) + } + } + if got := headers.Values("X-Repeated"); len(got) != 2 || got[0] != "first" || got[1] != "second" { + t.Errorf("repeated headers = %v", got) + } + if body, err := os.ReadFile(path); err != nil || string(body) != "subscription body" { + t.Fatalf("body = %q, error = %v", body, err) + } + // The original API still downloads the same body without returning metadata. + if err := controller.DownloadUrlToFile(server.URL, "proxy", `{"X-Test":"request"}`, path, 1000); err != nil { + t.Fatal(err) + } +} + +func TestDownloadUrlToFileFailureDoesNotPublishHeadersOrBody(t *testing.T) { + controller := testHTTPController(t) + for _, status := range []int{http.StatusForbidden, http.StatusPartialContent, http.StatusOK} { + t.Run(http.StatusText(status), func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Profile-Title", "must not escape") + w.Header().Set("Content-Length", "100") + w.WriteHeader(status) + _, _ = w.Write([]byte("truncated")) + })) + defer server.Close() + directory := t.TempDir() + path := filepath.Join(directory, "subscription") + if err := os.WriteFile(path, []byte("original"), 0600); err != nil { + t.Fatal(err) + } + headers, err := controller.DownloadUrlToFileWithHeaders(server.URL, "proxy", "", path, 1000) + if err == nil || headers != "" { + t.Fatalf("headers = %q, error = %v", headers, err) + } + if body, err := os.ReadFile(path); err != nil || string(body) != "original" { + t.Fatalf("previous body = %q, error = %v", body, err) + } + files, err := os.ReadDir(directory) + if err != nil || len(files) != 1 { + t.Fatalf("temporary files leaked: %v, error = %v", files, err) + } + }) + } +} + +func TestAppRequestsUseConfiguredBalancerFallback(t *testing.T) { + controller := testHTTPControllerWithConfig(t, `{ + "log":{"loglevel":"none"}, + "outbounds":[ + {"protocol":"blackhole","tag":"blocked"}, + {"protocol":"blackhole","tag":"member"}, + {"protocol":"freedom","tag":"group-fallback"} + ], + "observatory":{"subjectSelector":["unobserved"]}, + "routing":{"balancers":[ + {"tag":"group","selector":["member"],"strategy":{"type":"leastPing"},"fallbackTag":"group-fallback"}, + {"tag":"without-fallback","selector":["member"],"strategy":{"type":"leastPing"}} + ]} + }`) + if target, err := controller.GetBalancerPrincipleTarget("group"); err != nil || target != "" { + t.Fatalf("expected no observed target, got %q, error = %v", target, err) + } + tag, err := controller.GetBalancerOutbound("group") + if err != nil || tag != "group-fallback" { + t.Fatalf("resolved outbound = %q, error = %v", tag, err) + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("through the fallback")) + })) + defer server.Close() + if body, err := controller.GetUrlContent(server.URL, tag); err != nil || body != "through the fallback" { + t.Fatalf("body = %q, error = %v", body, err) + } + for _, group := range []string{"without-fallback", "unknown"} { + if tag, err := controller.GetBalancerOutbound(group); err == nil || tag != "" { + t.Errorf("unexpected outbound %q for %s, error = %v", tag, group, err) + } + } +} + +func testHTTPController(t *testing.T) *CoreController { + t.Helper() + // A blocked default outbound makes successful downloads prove that the + // requested outbound is selected, including after an HTTP redirect. + return testHTTPControllerWithConfig(t, `{"log":{"loglevel":"none"},"outbounds":[{"protocol":"blackhole","tag":"blocked"},{"protocol":"freedom","tag":"proxy"}]}`) +} + +func testHTTPControllerWithConfig(t *testing.T, content string) *CoreController { + t.Helper() + config, err := coreserial.LoadJSONConfig(strings.NewReader(content)) + if err != nil { + t.Fatal(err) + } + inst, err := core.New(config) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = inst.Close() }) + if err := inst.Start(); err != nil { + t.Fatal(err) + } + return &CoreController{coreInstance: inst, IsRunning: true, balancerFallbacks: configuredBalancerFallbacks(config)} +} diff --git a/libv2ray_utils.go b/libv2ray_utils.go index 342e516f..6de7dde8 100644 --- a/libv2ray_utils.go +++ b/libv2ray_utils.go @@ -2,18 +2,25 @@ package libv2ray import ( "context" + "encoding/json" "errors" "fmt" "io" "net" "net/http" + "os" + "path/filepath" "strconv" "strings" "time" + corerouter "github.com/xtls/xray-core/app/router" corenet "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/serial" + coresession "github.com/xtls/xray-core/common/session" core "github.com/xtls/xray-core/core" + coreoutbound "github.com/xtls/xray-core/features/outbound" + corerouting "github.com/xtls/xray-core/features/routing" corestats "github.com/xtls/xray-core/features/stats" coreserial "github.com/xtls/xray-core/infra/conf/serial" ) @@ -62,6 +69,233 @@ func (x *CoreController) MeasureDelay(url string) (int64, error) { return measureInstDelay(ctx, x.coreInstance, url) } +// GetBalancerPrincipleTarget returns the strategy's current first-choice +// outbound. An empty result means the observatory has not produced a viable +// target yet or the running profile has no compatible balancer. +func (x *CoreController) GetBalancerPrincipleTarget(balancerTag string) (string, error) { + x.coreMutex.Lock() + defer x.coreMutex.Unlock() + + if !x.IsRunning || x.coreInstance == nil { + return "", nil + } + return firstBalancerPrincipleTarget(x.coreInstance, balancerTag) +} + +func firstBalancerPrincipleTarget(inst *core.Instance, balancerTag string) (string, error) { + if balancerTag == "" { + return "", nil + } + if inst == nil { + return "", errors.New("core instance is nil") + } + principle, ok := inst.GetFeature(corerouting.RouterType()).(corerouting.BalancerPrincipleTarget) + if !ok { + return "", errors.New("router does not expose balancer principle targets") + } + targets, err := principle.GetPrincipleTarget(balancerTag) + if err != nil { + return "", err + } + for _, target := range targets { + if target != "" { + return target, nil + } + } + return "", nil +} + +// GetBalancerOutbound resolves an explicit app-request outbound, honoring an active +// override and the configured group fallback when the strategy has no target. +func (x *CoreController) GetBalancerOutbound(balancerTag string) (string, error) { + x.coreMutex.Lock() + defer x.coreMutex.Unlock() + + inst := x.coreInstance + if !x.IsRunning || inst == nil { + return "", errors.New("core is not running") + } + if router, ok := inst.GetFeature(corerouting.RouterType()).(corerouting.BalancerOverrider); ok { + target, err := router.GetOverrideTarget(balancerTag) + if err == nil && target != "" { + return target, nil + } + } + target, err := firstBalancerPrincipleTarget(inst, balancerTag) + if err == nil && target != "" { + return target, nil + } + fallback := x.balancerFallbacks[balancerTag] + if fallback != "" { + manager, ok := inst.GetFeature(coreoutbound.ManagerType()).(coreoutbound.Manager) + if ok && manager.GetHandler(fallback) != nil { + return fallback, nil + } + } + if err != nil { + return "", err + } + return "", fmt.Errorf("balancer %q has no usable outbound", balancerTag) +} + +func configuredBalancerFallbacks(config *core.Config) map[string]string { + fallbacks := make(map[string]string) + for _, app := range config.App { + if app.Type != "xray.app.router.Config" { + continue + } + // LoadJSONConfig has already decoded and validated the router configuration. + instance, err := app.GetInstance() + router, ok := instance.(*corerouter.Config) + if err != nil || !ok { + continue + } + for _, balancer := range router.GetBalancingRule() { + if fallback := balancer.GetFallbackTag(); fallback != "" { + fallbacks[balancer.GetTag()] = fallback + } + } + } + return fallbacks +} + +// GetUrlContent retrieves a URL through the requested outbound of the current core instance. +func (x *CoreController) GetUrlContent(url string, outboundTag string) (string, error) { + resp, err := x.getURL(url, outboundTag, "", 5*time.Second) + if err != nil { + return "", err + } + defer resp.Body.Close() + + content, err := io.ReadAll(resp.Body) + if err != nil { + return "", fmt.Errorf("failed to read response body: %w", err) + } + return string(content), nil +} + +// DownloadUrlToFile downloads a URL through the requested outbound of the +// current core instance. Headers are supplied as a JSON object. +func (x *CoreController) DownloadUrlToFile(url string, outboundTag string, headersJSON string, filePath string, timeoutMillis int64) error { + _, err := x.DownloadUrlToFileWithHeaders(url, outboundTag, headersJSON, filePath, timeoutMillis) + return err +} + +// DownloadUrlToFileWithHeaders downloads a URL and returns the final response +// headers as a JSON object of string arrays, only after the file is complete. +// It uses the same outbound routing and transactional file replacement as DownloadUrlToFile. +func (x *CoreController) DownloadUrlToFileWithHeaders(url string, outboundTag string, headersJSON string, filePath string, timeoutMillis int64) (string, error) { + if filePath == "" { + return "", errors.New("file path is empty") + } + timeout := time.Duration(timeoutMillis) * time.Millisecond + if timeout <= 0 { + timeout = 15 * time.Second + } + + resp, err := x.getURL(url, outboundTag, headersJSON, timeout) + if err != nil { + return "", err + } + defer resp.Body.Close() + + responseHeaders, err := json.Marshal(resp.Header) + if err != nil { + return "", fmt.Errorf("failed to encode response headers: %w", err) + } + + file, err := os.CreateTemp(filepath.Dir(filePath), "."+filepath.Base(filePath)+".*") + if err != nil { + return "", fmt.Errorf("failed to create temporary file: %w", err) + } + temporaryPath := file.Name() + closed := false + defer func() { + if !closed { + _ = file.Close() + } + _ = os.Remove(temporaryPath) + }() + + written, err := io.Copy(file, resp.Body) + if err != nil { + return "", fmt.Errorf("failed to write response body: %w", err) + } + if resp.ContentLength >= 0 && written != resp.ContentLength { + return "", fmt.Errorf("response length mismatch: expected %d bytes, got %d", resp.ContentLength, written) + } + if err = file.Close(); err != nil { + return "", fmt.Errorf("failed to close temporary file: %w", err) + } + closed = true + if err = os.Rename(temporaryPath, filePath); err != nil { + return "", fmt.Errorf("failed to replace destination file: %w", err) + } + return string(responseHeaders), nil +} + +func (x *CoreController) getURL(url string, outboundTag string, headersJSON string, timeout time.Duration) (*http.Response, error) { + x.coreMutex.Lock() + inst := x.coreInstance + running := x.IsRunning + x.coreMutex.Unlock() + + if !running || inst == nil { + return nil, errors.New("core is not running") + } + if outboundTag == "" { + return nil, errors.New("outbound tag is empty") + } + + tr := &http.Transport{ + TLSHandshakeTimeout: 5 * time.Second, + DisableKeepAlives: true, + DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { + dest, err := corenet.ParseDestination(fmt.Sprintf("%s:%s", network, addr)) + if err != nil { + return nil, err + } + ctx = coresession.SetForcedOutboundTagToContext(ctx, outboundTag) + return core.Dial(ctx, inst, dest) + }, + } + req, err := http.NewRequest(http.MethodGet, url, nil) + if err != nil { + return nil, fmt.Errorf("failed to create request: %w", err) + } + if headersJSON != "" { + headers := make(map[string]string) + if err := json.Unmarshal([]byte(headersJSON), &headers); err != nil { + return nil, fmt.Errorf("failed to parse request headers: %w", err) + } + applyRequestHeaders(req, headers) + } + + resp, err := (&http.Client{Transport: tr, Timeout: timeout}).Do(req) + if err != nil { + return nil, err + } + + if resp.StatusCode < http.StatusOK || + resp.StatusCode >= http.StatusMultipleChoices || + resp.StatusCode == http.StatusPartialContent { + resp.Body.Close() + return nil, fmt.Errorf("invalid status: %s", resp.Status) + } + + return resp, nil +} + +func applyRequestHeaders(req *http.Request, headers map[string]string) { + for key, value := range headers { + if strings.EqualFold(key, "Host") { + req.Host = value + continue + } + req.Header.Set(key, value) + } +} + // MeasureOutboundDelay measures the outbound delay for a given configuration and URL func MeasureOutboundDelay(ConfigureFileContent string, url string) (int64, error) { config, err := coreserial.LoadJSONConfig(strings.NewReader(ConfigureFileContent))