feat(xray): browse geosite/geoip categories from routing rules (#6165)

* feat(xray): browse geosite/geoip categories from routing rules

Routing rules made you type category names from memory: nothing showed which
categories a database actually contains, what is inside one, or whether a
name resolves at all — a typo only surfaced when Xray refused the config.

The panel now reads Xray's .dat databases itself and exposes them over four
endpoints: databases in the asset folder, a database's categories, one page
of a category's rules, and validation of the tokens already in a rule. The
reader walks the protobuf wire format directly rather than decoding into Go
structs, because a 10 MB geosite.dat holds well over a million domains and
materialising them costs ~284 MB where streaming costs ~19 MB. Only the
category index is cached, entry pages are scanned on demand, and scans are
serialised, so twenty concurrent requests peak at 87 MB instead of 1 GB.
A database's type is decided by its contents, not its file name, since
custom .dat files are named freely.

In the rule form, the source-IP, IP and domain fields gain a database button
opening the browser: search over categories, a preview of what a category
holds, and a multi-select that merges into the field. Plain domains, CIDRs
and categories the panel does not know are left untouched; categories already
present come back ticked, and unticking one removes it from the rule.

* fix(xray): read geo databases through os.Root and match codes verbatim

CodeQL flagged the database read as a path built from a user-supplied value,
and it was right about the shape of it. The file name arrives in a request;
resolve() rejects traversal and stats the file through an os.Root, but the
read itself went through a joined path with os.ReadFile. That left the
symlink defence incomplete: the stat could pass while the read followed a
link planted — or swapped in — afterwards.

Reads now go through the same root, so a request-supplied name never becomes
a path this code resolves on its own, and the size limit is applied to the
opened file rather than to a separate stat of it.

Lookup no longer trims the category code either. It backs the routing-token
validator, and the core matches codes verbatim: "geosite: cn" will not start
Xray, so repairing that space here hid exactly the typo the validator exists
to report.

* fix(xray): address review findings on the geo category browser

Asset folder. The browser read config.GetBinFolderPath() unconditionally,
but the core honours a preset XRAY_LOCATION_ASSET and only falls back to the
bin folder (ensureXrayAssetLocation). On an install pointing at a shared
asset directory the panel listed an empty folder and reported perfectly
valid geosite:/geoip: tokens as missing — the validator warning about a
correct config. The directory is now resolved with the core's precedence.

Paging. Serving one page read and rescanned the whole database, so walking
category-ads-all re-read it per page. The index now records each category's
byte range and a page reads only that record through the os.Root handle,
with the current category's records held for the duration of a paging
session. Profiling that also showed the real cost was not the read but the
slice of payload pointers built per call — a category holds a hundred
thousand of them — so records are now walked with a callback instead.
Ten pages over category-ads-all: 239 MB allocated, now 4.3 MB.

Cached failures. Any error from reading a file was latched under the file's
size+mtime, so a transient ENOMEM or EMFILE marked a healthy database as
damaged until it changed on disk. Only deterministic failures are cached.

Wrong kind. A geoip: token typed into a domain field parsed as a plain
domain and was waved through, though the core cannot resolve it as one. It
is now reported, with its own reason and wording.

Frontend. The category filter fed the query key on every keystroke, so each
character triggered a request that re-scanned the database; it is debounced
now. GeoTokenInput accepts and forwards a ref, so React Hook Form can focus
these three fields on a validation error again. A failed validation shows
that it failed instead of rendering the same empty state as "no issues".

Also drops an unreachable branch in the token-count guard and corrects the
categories endpoint docs, where limit is unbounded by default.

---------

Co-authored-by: STRENCH0 <17428017+STRENCH0@users.noreply.github.com>
This commit is contained in:
Grigoriy
2026-08-15 18:12:59 +03:00
committed by GitHub
parent 7c8a9a6909
commit d7698ec7aa
43 changed files with 5433 additions and 6 deletions
+278
View File
@@ -0,0 +1,278 @@
package controller
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/netip"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/op/go-logging"
xraygeodata "github.com/xtls/xray-core/common/geodata"
"google.golang.org/protobuf/proto"
xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/mhsanaei/3x-ui/v3/internal/xray/geodata"
)
func newGeodataEngine(t *testing.T) *gin.Engine {
t.Helper()
xuilogger.InitLogger(logging.ERROR)
gin.SetMode(gin.TestMode)
dir := t.TempDir()
t.Setenv("XUI_BIN_FOLDER", dir)
writeGeositeDB(t, dir)
writeGeoipDB(t, dir)
engine := gin.New()
NewXraySettingController(engine.Group("/panel/api"))
return engine
}
func writeGeositeDB(t *testing.T, dir string) {
t.Helper()
data, err := proto.Marshal(&xraygeodata.GeoSiteList{Entry: []*xraygeodata.GeoSite{
{Code: "google", Domain: []*xraygeodata.Domain{
{Type: xraygeodata.Domain_Domain, Value: "google.com"},
{Type: xraygeodata.Domain_Full, Value: "ads.google.com", Attribute: []*xraygeodata.Domain_Attribute{
{Key: "ads", TypedValue: &xraygeodata.Domain_Attribute_BoolValue{BoolValue: true}},
}},
}},
{Code: "cn", Domain: []*xraygeodata.Domain{{Type: xraygeodata.Domain_Domain, Value: "baidu.com"}}},
}})
if err != nil {
t.Fatalf("marshal geosite: %v", err)
}
if err := os.WriteFile(filepath.Join(dir, "geosite.dat"), data, 0o644); err != nil {
t.Fatalf("write geosite.dat: %v", err)
}
}
func writeGeoipDB(t *testing.T, dir string) {
t.Helper()
prefix := netip.MustParsePrefix("10.0.0.0/8")
data, err := proto.Marshal(&xraygeodata.GeoIPList{Entry: []*xraygeodata.GeoIP{
{Code: "private", Cidr: []*xraygeodata.CIDR{{Ip: prefix.Addr().AsSlice(), Prefix: uint32(prefix.Bits())}}},
}})
if err != nil {
t.Fatalf("marshal geoip: %v", err)
}
if err := os.WriteFile(filepath.Join(dir, "geoip.dat"), data, 0o644); err != nil {
t.Fatalf("write geoip.dat: %v", err)
}
}
type geodataEnvelope struct {
Success bool `json:"success"`
Msg string `json:"msg"`
Obj json.RawMessage `json:"obj"`
}
func doGeodataGet(t *testing.T, engine *gin.Engine, path string) geodataEnvelope {
t.Helper()
return doGeodataReq(t, engine, httptest.NewRequest(http.MethodGet, path, nil))
}
func doGeodataPost(t *testing.T, engine *gin.Engine, path string, form url.Values) geodataEnvelope {
t.Helper()
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return doGeodataReq(t, engine, req)
}
func doGeodataReq(t *testing.T, engine *gin.Engine, req *http.Request) geodataEnvelope {
t.Helper()
w := httptest.NewRecorder()
engine.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("%s %s: status %d, body=%s", req.Method, req.URL, w.Code, w.Body.String())
}
var env geodataEnvelope
if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {
t.Fatalf("decode envelope: %v body=%s", err, w.Body.String())
}
return env
}
func TestGeodataFiles(t *testing.T) {
engine := newGeodataEngine(t)
env := doGeodataGet(t, engine, "/panel/api/xray/geodata/files")
if !env.Success {
t.Fatalf("files not successful: %s", env.Msg)
}
var files []geodata.GeoFile
if err := json.Unmarshal(env.Obj, &files); err != nil {
t.Fatalf("decode files: %v", err)
}
if len(files) != 2 {
t.Fatalf("files = %+v, want 2 entries", files)
}
byName := make(map[string]geodata.GeoFile, len(files))
for _, file := range files {
byName[file.Name] = file
}
if got := byName["geosite.dat"]; got.Kind != geodata.KindSite || got.Categories != 2 {
t.Errorf("geosite.dat = %+v, want kind site with 2 categories", got)
}
if got := byName["geoip.dat"]; got.Kind != geodata.KindIP || got.Categories != 1 {
t.Errorf("geoip.dat = %+v, want kind ip with 1 category", got)
}
}
func TestGeodataCategoriesAndEntries(t *testing.T) {
engine := newGeodataEngine(t)
env := doGeodataGet(t, engine, "/panel/api/xray/geodata/categories?file=geosite.dat&q=goo&limit=10")
var categories geodata.GeoCategoryPage
if err := json.Unmarshal(env.Obj, &categories); err != nil {
t.Fatalf("decode categories: %v", err)
}
if categories.Total != 1 || categories.Items[0].Code != "google" {
t.Fatalf("categories = %+v, want only google", categories)
}
env = doGeodataGet(t, engine, "/panel/api/xray/geodata/entries?file=geosite.dat&code=google&limit=1&offset=1")
var entries geodata.GeoEntryPage
if err := json.Unmarshal(env.Obj, &entries); err != nil {
t.Fatalf("decode entries: %v", err)
}
if entries.Total != 2 {
t.Errorf("entries total = %d, want 2", entries.Total)
}
if len(entries.Items) != 1 || entries.Items[0].Value != "ads.google.com" || entries.Items[0].Kind != "full" {
t.Errorf("entries items = %+v, want the second entry ads.google.com", entries.Items)
}
}
func TestGeodataRejectsBadRequests(t *testing.T) {
engine := newGeodataEngine(t)
tests := []struct {
name string
path string
}{
{name: "missing code", path: "/panel/api/xray/geodata/entries?file=geosite.dat"},
{name: "unknown category", path: "/panel/api/xray/geodata/entries?file=geosite.dat&code=nope"},
{name: "path traversal", path: "/panel/api/xray/geodata/categories?file=../../etc/passwd.dat"},
{name: "non dat file", path: "/panel/api/xray/geodata/categories?file=x-ui.db"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if env := doGeodataGet(t, engine, tt.path); env.Success {
t.Errorf("request succeeded, want failure: %s", env.Obj)
}
})
}
}
func TestGeodataValidate(t *testing.T) {
engine := newGeodataEngine(t)
tests := []struct {
name string
kind string
tokens string
wantTokens []string
wantReason string
}{
{name: "known categories pass", kind: "domain", tokens: "geosite:google,geosite:cn,google.com"},
{name: "attribute filter passes", kind: "domain", tokens: "geosite:google@ads"},
{
name: "attribute the category does not carry",
kind: "domain",
tokens: "geosite:google@typo",
wantTokens: []string{"geosite:google@typo"},
wantReason: "attributeMissing",
},
{
name: "empty attribute is a syntax error",
kind: "domain",
tokens: "geosite:google@",
wantTokens: []string{"geosite:google@"},
wantReason: "syntax",
},
{
name: "missing category",
kind: "domain",
tokens: "geosite:google,geosite:blabla",
wantTokens: []string{"geosite:blabla"},
wantReason: "categoryMissing",
},
{
name: "missing database",
kind: "domain",
tokens: "ext:absent.dat:corp",
wantTokens: []string{"ext:absent.dat:corp"},
wantReason: "fileMissing",
},
{
name: "a geoip token in a domain field is reported",
kind: "domain",
tokens: "geoip:cn",
wantTokens: []string{"geoip:cn"},
wantReason: "wrongKind",
},
{name: "plain cidr passes", kind: "ip", tokens: "10.0.0.0/8,geoip:private"},
{
name: "missing ip category",
kind: "ip",
tokens: "geoip:nowhere",
wantTokens: []string{"geoip:nowhere"},
wantReason: "categoryMissing",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
env := doGeodataPost(t, engine, "/panel/api/xray/geodata/validate", url.Values{
"kind": {tt.kind},
"tokens": {tt.tokens},
})
if !env.Success {
t.Fatalf("validate not successful: %s", env.Msg)
}
var issues []service.GeodataTokenIssue
if err := json.Unmarshal(env.Obj, &issues); err != nil {
t.Fatalf("decode issues: %v", err)
}
if len(issues) != len(tt.wantTokens) {
t.Fatalf("issues = %+v, want %d", issues, len(tt.wantTokens))
}
for i, wantToken := range tt.wantTokens {
if issues[i].Token != wantToken {
t.Errorf("issue %d token = %q, want %q", i, issues[i].Token, wantToken)
}
if issues[i].Reason != tt.wantReason {
t.Errorf("issue %d reason = %q, want %q", i, issues[i].Reason, tt.wantReason)
}
}
})
}
}
func TestGeodataFollowsXrayAssetLocation(t *testing.T) {
engine := newGeodataEngine(t)
shared := t.TempDir()
writeGeositeDB(t, shared)
t.Setenv("XRAY_LOCATION_ASSET", shared)
env := doGeodataGet(t, engine, "/panel/api/xray/geodata/files")
var files []geodata.GeoFile
if err := json.Unmarshal(env.Obj, &files); err != nil {
t.Fatalf("decode files: %v", err)
}
if len(files) != 1 || files[0].Name != "geosite.dat" {
t.Fatalf("files = %+v, want only the database from XRAY_LOCATION_ASSET", files)
}
if files[0].Categories != 2 {
t.Errorf("categories = %d, want 2 — the shared asset folder should be read", files[0].Categories)
}
}
+73
View File
@@ -26,6 +26,7 @@ type XraySettingController struct {
WarpService integration.WarpService
NordService integration.NordService
OutboundSubscriptionService service.OutboundSubscriptionService
GeodataService service.GeodataService
}
// NewXraySettingController creates a new XraySettingController and initializes its routes.
@@ -53,6 +54,11 @@ func (a *XraySettingController) initRouter(g *gin.RouterGroup) {
g.POST("/balancerOverride", a.balancerOverride)
g.POST("/routeTest", a.routeTest)
g.GET("/geodata/files", a.geodataFiles)
g.GET("/geodata/categories", a.geodataCategories)
g.GET("/geodata/entries", a.geodataEntries)
g.POST("/geodata/validate", a.geodataValidate)
// Outbound subscription (remote outbound lists)
g.GET("/outbound-subs", a.listOutboundSubs)
g.POST("/outbound-subs", a.createOutboundSub)
@@ -391,6 +397,73 @@ func (a *XraySettingController) routeTest(c *gin.Context) {
jsonObj(c, result, nil)
}
// maxGeodataTokens bounds one validation request; a routing rule listing more
// categories than this is not something the panel needs to answer for.
const maxGeodataTokens = 500
// geodataFiles lists the geo databases Xray resolves geosite:/geoip: tokens
// against, including ones that failed to parse.
func (a *XraySettingController) geodataFiles(c *gin.Context) {
files, err := a.GeodataService.Files()
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
jsonObj(c, files, nil)
}
// geodataCategories returns one page of a database's categories.
func (a *XraySettingController) geodataCategories(c *gin.Context) {
offset, limit := geodataPaging(c)
page, err := a.GeodataService.Categories(c.Query("file"), c.Query("q"), offset, limit)
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
jsonObj(c, page, nil)
}
// geodataEntries returns one page of the domains or CIDRs inside a category.
func (a *XraySettingController) geodataEntries(c *gin.Context) {
code := c.Query("code")
if code == "" {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("code is required"))
return
}
offset, limit := geodataPaging(c)
page, err := a.GeodataService.Entries(c.Query("file"), code, c.Query("q"), offset, limit)
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
jsonObj(c, page, nil)
}
// geodataValidate reports which routing tokens do not resolve against the
// databases on disk.
func (a *XraySettingController) geodataValidate(c *gin.Context) {
// Split with a bound rather than splitting first: a 10 MB body of commas
// would otherwise allocate millions of strings before the limit is checked.
tokens := strings.SplitN(c.PostForm("tokens"), ",", maxGeodataTokens+1)
if len(tokens) > maxGeodataTokens {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewErrorf("too many tokens: over %d", maxGeodataTokens))
return
}
jsonObj(c, a.GeodataService.Validate(c.PostForm("kind") == "ip", tokens), nil)
}
func geodataPaging(c *gin.Context) (int, int) {
offset, err := strconv.Atoi(c.Query("offset"))
if err != nil {
offset = 0
}
limit, err := strconv.Atoi(c.Query("limit"))
if err != nil {
limit = 0
}
return offset, limit
}
// --- Outbound Subscription handlers ---
func (a *XraySettingController) listOutboundSubs(c *gin.Context) {