setting.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. package service
  2. import (
  3. _ "embed"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "os"
  10. "reflect"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/google/uuid"
  15. "github.com/mhsanaei/3x-ui/v3/internal/database"
  16. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  17. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  18. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  19. "github.com/mhsanaei/3x-ui/v3/internal/util/netproxy"
  20. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  21. "github.com/mhsanaei/3x-ui/v3/internal/util/reflect_util"
  22. "github.com/mhsanaei/3x-ui/v3/internal/web/entity"
  23. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  24. )
  25. //go:embed config.json
  26. var xrayTemplateConfig string
  27. var defaultValueMap = map[string]string{
  28. "xrayTemplateConfig": xrayTemplateConfig,
  29. "webListen": "",
  30. "webDomain": "",
  31. "webPort": "2053",
  32. "webCertFile": "",
  33. "webKeyFile": "",
  34. "secret": random.Seq(32),
  35. "panelGuid": uuid.NewString(),
  36. "apiToken": "",
  37. // Node mTLS material (opt-in). All default empty: the CA + master client
  38. // cert are minted lazily on first use, and the node-side trust CA is pasted
  39. // in by the operator. Kept out of entity.AllSetting so private keys never
  40. // reach the settings UI/export.
  41. "nodeMtlsCaCertPem": "",
  42. "nodeMtlsCaKeyPem": "",
  43. "nodeMtlsClientCertPem": "",
  44. "nodeMtlsClientKeyPem": "",
  45. "nodeMtlsClientCAPem": "",
  46. "webBasePath": normalizeBasePath(getEnv("XUI_INIT_WEB_BASE_PATH", "/")),
  47. "sessionMaxAge": "360",
  48. "trustedProxyCIDRs": "127.0.0.1/32,::1/128",
  49. "pageSize": "25",
  50. "expireDiff": "0",
  51. "trafficDiff": "0",
  52. "remarkTemplate": "{{INBOUND}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D",
  53. "timeLocation": "Local",
  54. "tgBotEnable": "false",
  55. "tgBotToken": "",
  56. "tgBotProxy": "",
  57. "tgBotAPIServer": "",
  58. "tgBotChatId": "",
  59. "tgRunTime": "@daily",
  60. "tgBotBackup": "false",
  61. "tgCpu": "80",
  62. "tgLang": "en-US",
  63. "twoFactorEnable": "false",
  64. "twoFactorToken": "",
  65. "subEnable": "true",
  66. "subJsonEnable": "false",
  67. "subTitle": "",
  68. "subSupportUrl": "",
  69. "subProfileUrl": "",
  70. "subAnnounce": "",
  71. "subEnableRouting": "false",
  72. "subRoutingRules": "",
  73. "subHideSettings": "false",
  74. "subListen": "",
  75. "subPort": "2096",
  76. "subPath": "/sub/",
  77. "subDomain": "",
  78. "subCertFile": "",
  79. "subKeyFile": "",
  80. "subUpdates": "12",
  81. "subEncrypt": "true",
  82. "subURI": "",
  83. "subJsonPath": "/json/",
  84. "subJsonURI": "",
  85. "subClashEnable": "false",
  86. "subClashPath": "/clash/",
  87. "subClashURI": "",
  88. "subClashEnableRouting": "false",
  89. "subClashRules": "",
  90. "subJsonMux": "",
  91. "subJsonRules": "",
  92. "subJsonFinalMask": "",
  93. "subThemeDir": "",
  94. "datepicker": "gregorian",
  95. "warp": "",
  96. "warpUpdateInterval": "0",
  97. "nord": "",
  98. "externalTrafficInformEnable": "false",
  99. "externalTrafficInformURI": "",
  100. "restartXrayOnClientDisable": "true",
  101. "xrayOutboundTestUrl": "https://www.google.com/generate_204",
  102. "panelOutbound": "",
  103. // LDAP defaults
  104. "ldapEnable": "false",
  105. "ldapHost": "",
  106. "ldapPort": "389",
  107. "ldapUseTLS": "false",
  108. "ldapBindDN": "",
  109. "ldapPassword": "",
  110. "ldapBaseDN": "",
  111. "ldapUserFilter": "(objectClass=person)",
  112. "ldapUserAttr": "mail",
  113. "ldapVlessField": "vless_enabled",
  114. "ldapSyncCron": "@every 1m",
  115. "ldapFlagField": "",
  116. "ldapTruthyValues": "true,1,yes,on",
  117. "ldapInvertFlag": "false",
  118. "ldapInboundTags": "",
  119. "ldapAutoCreate": "false",
  120. "ldapAutoDelete": "false",
  121. "ldapDefaultTotalGB": "0",
  122. "ldapDefaultExpiryDays": "0",
  123. "ldapDefaultLimitIP": "0",
  124. // Event bus — per-subscriber event filtering (empty = all disabled)
  125. "tgEnabledEvents": "login.attempt,cpu.high",
  126. "smtpEnabledEvents": "login.attempt,cpu.high",
  127. "smtpCpu": "80",
  128. // Email (SMTP) notifications
  129. "smtpEnable": "false",
  130. "smtpHost": "",
  131. "smtpPort": "587",
  132. "smtpUsername": "",
  133. "smtpPassword": "",
  134. "smtpTo": "",
  135. "smtpEncryptionType": "starttls", // no, starttls, tls
  136. }
  137. // SettingService provides business logic for application settings management.
  138. // It handles configuration storage, retrieval, and validation for all system settings.
  139. type SettingService struct{}
  140. func (s *SettingService) GetDefaultJSONConfig() (any, error) {
  141. var jsonData any
  142. err := json.Unmarshal([]byte(xrayTemplateConfig), &jsonData)
  143. if err != nil {
  144. return nil, err
  145. }
  146. return jsonData, nil
  147. }
  148. func (s *SettingService) GetAllSetting() (*entity.AllSetting, error) {
  149. db := database.GetDB()
  150. settings := make([]*model.Setting, 0)
  151. err := db.Model(model.Setting{}).Not("key = ?", "xrayTemplateConfig").Find(&settings).Error
  152. if err != nil {
  153. return nil, err
  154. }
  155. allSetting := &entity.AllSetting{}
  156. t := reflect.TypeFor[entity.AllSetting]()
  157. v := reflect.ValueOf(allSetting).Elem()
  158. fields := reflect_util.GetFields(t)
  159. setSetting := func(key, value string) (err error) {
  160. defer func() {
  161. panicErr := recover()
  162. if panicErr != nil {
  163. err = errors.New(fmt.Sprint(panicErr))
  164. }
  165. }()
  166. var found bool
  167. var field reflect.StructField
  168. for _, f := range fields {
  169. if f.Tag.Get("json") == key {
  170. field = f
  171. found = true
  172. break
  173. }
  174. }
  175. if !found {
  176. // Some settings are automatically generated, no need to return to the front end to modify the user
  177. return nil
  178. }
  179. fieldV := v.FieldByName(field.Name)
  180. switch t := fieldV.Interface().(type) {
  181. case int:
  182. n, err := strconv.ParseInt(effectiveSettingValue(key, value), 10, 64)
  183. if err != nil {
  184. return err
  185. }
  186. fieldV.SetInt(n)
  187. case string:
  188. fieldV.SetString(value)
  189. case bool:
  190. fieldV.SetBool(effectiveSettingValue(key, value) == "true")
  191. default:
  192. return common.NewErrorf("unknown field %v type %v", key, t)
  193. }
  194. return
  195. }
  196. keyMap := map[string]bool{}
  197. for _, setting := range settings {
  198. err := setSetting(setting.Key, setting.Value)
  199. if err != nil {
  200. return nil, err
  201. }
  202. keyMap[setting.Key] = true
  203. }
  204. for key, value := range defaultValueMap {
  205. if keyMap[key] {
  206. continue
  207. }
  208. err := setSetting(key, value)
  209. if err != nil {
  210. return nil, err
  211. }
  212. }
  213. return allSetting, nil
  214. }
  215. func (s *SettingService) GetAllSettingView() (*entity.AllSettingView, error) {
  216. allSetting, err := s.GetAllSetting()
  217. if err != nil {
  218. return nil, err
  219. }
  220. view := &entity.AllSettingView{AllSetting: *allSetting}
  221. view.HasTgBotToken = secretConfigured(allSetting.TgBotToken)
  222. view.HasTwoFactorToken = secretConfigured(allSetting.TwoFactorToken)
  223. view.HasLdapPassword = secretConfigured(allSetting.LdapPassword)
  224. view.HasWarpSecret = secretConfigured(mustString(s.GetWarp()))
  225. view.HasNordSecret = secretConfigured(mustString(s.GetNord()))
  226. view.HasSmtpPassword = secretConfigured(allSetting.SmtpPassword)
  227. var apiTokenCount int64
  228. if err := database.GetDB().Model(model.ApiToken{}).Where("enabled = ?", true).Count(&apiTokenCount).Error; err == nil {
  229. view.HasApiToken = apiTokenCount > 0
  230. }
  231. view.TgBotToken = ""
  232. view.TwoFactorToken = ""
  233. view.LdapPassword = ""
  234. view.SmtpPassword = ""
  235. return view, nil
  236. }
  237. func secretConfigured(value string) bool {
  238. return strings.TrimSpace(value) != ""
  239. }
  240. func mustString(value string, _ error) string {
  241. return value
  242. }
  243. func getEnv(key, fallback string) string {
  244. val, ok := os.LookupEnv(key)
  245. if !ok {
  246. return fallback
  247. }
  248. val = strings.TrimSpace(val)
  249. if val == "" {
  250. return fallback
  251. }
  252. return val
  253. }
  254. func (s *SettingService) ResetSettings() error {
  255. db := database.GetDB()
  256. err := db.Where("1 = 1").Delete(model.Setting{}).Error
  257. if err != nil {
  258. return err
  259. }
  260. return db.Model(model.User{}).
  261. Where("1 = 1").Error
  262. }
  263. func (s *SettingService) getSetting(key string) (*model.Setting, error) {
  264. db := database.GetDB()
  265. setting := &model.Setting{}
  266. err := db.Model(model.Setting{}).Where("key = ?", key).First(setting).Error
  267. if err != nil {
  268. return nil, err
  269. }
  270. return setting, nil
  271. }
  272. func (s *SettingService) saveSetting(key string, value string) error {
  273. setting, err := s.getSetting(key)
  274. db := database.GetDB()
  275. if database.IsNotFound(err) {
  276. return db.Create(&model.Setting{
  277. Key: key,
  278. Value: value,
  279. }).Error
  280. } else if err != nil {
  281. return err
  282. }
  283. setting.Key = key
  284. setting.Value = value
  285. return db.Save(setting).Error
  286. }
  287. func (s *SettingService) getString(key string) (string, error) {
  288. setting, err := s.getSetting(key)
  289. if database.IsNotFound(err) {
  290. value, ok := defaultValueMap[key]
  291. if !ok {
  292. return "", common.NewErrorf("key <%v> not in defaultValueMap", key)
  293. }
  294. return value, nil
  295. } else if err != nil {
  296. return "", err
  297. }
  298. return setting.Value, nil
  299. }
  300. func (s *SettingService) setString(key string, value string) error {
  301. return s.saveSetting(key, value)
  302. }
  303. func effectiveSettingValue(key, stored string) string {
  304. if stored == "" {
  305. if def, ok := defaultValueMap[key]; ok {
  306. return def
  307. }
  308. }
  309. return stored
  310. }
  311. func (s *SettingService) getBool(key string) (bool, error) {
  312. str, err := s.getString(key)
  313. if err != nil {
  314. return false, err
  315. }
  316. return strconv.ParseBool(effectiveSettingValue(key, str))
  317. }
  318. func (s *SettingService) setBool(key string, value bool) error {
  319. return s.setString(key, strconv.FormatBool(value))
  320. }
  321. func (s *SettingService) getInt(key string) (int, error) {
  322. str, err := s.getString(key)
  323. if err != nil {
  324. return 0, err
  325. }
  326. return strconv.Atoi(effectiveSettingValue(key, str))
  327. }
  328. func (s *SettingService) setInt(key string, value int) error {
  329. return s.setString(key, strconv.Itoa(value))
  330. }
  331. func (s *SettingService) GetWarpLastUpdate() (int64, error) {
  332. val, err := s.getString("warpLastUpdate")
  333. if err != nil || val == "" {
  334. return 0, err
  335. }
  336. return strconv.ParseInt(val, 10, 64)
  337. }
  338. func (s *SettingService) SetWarpLastUpdate(val int64) error {
  339. return s.saveSetting("warpLastUpdate", strconv.FormatInt(val, 10))
  340. }
  341. func (s *SettingService) SetWarpUpdateInterval(val int) error {
  342. return s.setInt("warpUpdateInterval", val)
  343. }
  344. func (s *SettingService) GetXrayConfigTemplate() (string, error) {
  345. return s.getString("xrayTemplateConfig")
  346. }
  347. func (s *SettingService) GetXrayOutboundTestUrl() (string, error) {
  348. return s.getString("xrayOutboundTestUrl")
  349. }
  350. func (s *SettingService) SetXrayOutboundTestUrl(url string) error {
  351. clean, err := SanitizeHTTPURL(url)
  352. if err != nil {
  353. return err
  354. }
  355. return s.setString("xrayOutboundTestUrl", clean)
  356. }
  357. func (s *SettingService) GetListen() (string, error) {
  358. return s.getString("webListen")
  359. }
  360. func (s *SettingService) SetListen(ip string) error {
  361. return s.setString("webListen", ip)
  362. }
  363. func (s *SettingService) GetWebDomain() (string, error) {
  364. return s.getString("webDomain")
  365. }
  366. func (s *SettingService) GetTgBotToken() (string, error) {
  367. return s.getString("tgBotToken")
  368. }
  369. func (s *SettingService) SetTgBotToken(token string) error {
  370. return s.setString("tgBotToken", token)
  371. }
  372. func (s *SettingService) GetTgBotProxy() (string, error) {
  373. return s.getString("tgBotProxy")
  374. }
  375. func (s *SettingService) SetTgBotProxy(token string) error {
  376. return s.setString("tgBotProxy", token)
  377. }
  378. // GetPanelOutbound returns the Xray outbound tag the panel's own outbound
  379. // requests (version checks, Telegram, subscription fetches) are routed through.
  380. func (s *SettingService) GetPanelOutbound() (string, error) {
  381. return s.getString("panelOutbound")
  382. }
  383. func (s *SettingService) SetPanelOutbound(tag string) error {
  384. return s.setString("panelOutbound", tag)
  385. }
  386. // PanelEgressProxyURL resolves the loopback SOCKS bridge that the generated
  387. // config exposes when a panel outbound is configured (see injectPanelEgress).
  388. // It returns "" — meaning a direct connection — when the feature is off or
  389. // the bridge is not present in the running core yet.
  390. func (s *SettingService) PanelEgressProxyURL() string {
  391. tag, err := s.GetPanelOutbound()
  392. if err != nil || tag == "" {
  393. return ""
  394. }
  395. proc := XrayProcess()
  396. if proc == nil || !proc.IsRunning() {
  397. logger.Warning("panel outbound [", tag, "] is set but Xray is not running, using a direct connection")
  398. return ""
  399. }
  400. cfg := proc.GetConfig()
  401. if cfg == nil {
  402. return ""
  403. }
  404. for i := range cfg.InboundConfigs {
  405. if cfg.InboundConfigs[i].Tag == PanelEgressInboundTag {
  406. return fmt.Sprintf("socks5://127.0.0.1:%d", cfg.InboundConfigs[i].Port)
  407. }
  408. }
  409. logger.Warning("panel outbound [", tag, "] is set but the egress bridge is not in the running config, using a direct connection")
  410. return ""
  411. }
  412. func (s *SettingService) NodeEgressProxyURL(nodeID int) string {
  413. tag := NodeEgressInboundTag(nodeID)
  414. proc := XrayProcess()
  415. if proc == nil || !proc.IsRunning() {
  416. logger.Warning("node outbound [", tag, "] is set but Xray is not running, using a direct connection")
  417. return ""
  418. }
  419. cfg := proc.GetConfig()
  420. if cfg == nil {
  421. return ""
  422. }
  423. for i := range cfg.InboundConfigs {
  424. if cfg.InboundConfigs[i].Tag == tag {
  425. return fmt.Sprintf("socks5://127.0.0.1:%d", cfg.InboundConfigs[i].Port)
  426. }
  427. }
  428. logger.Warning("node outbound [", tag, "] is set but the egress bridge is not in the running config, using a direct connection")
  429. return ""
  430. }
  431. // NewProxiedHTTPClient returns an HTTP client that routes the panel's own
  432. // outbound requests through the configured panel outbound (via the loopback
  433. // SOCKS bridge in the running Xray). When the feature is off or the bridge
  434. // is unavailable it falls back to a direct client.
  435. func (s *SettingService) NewProxiedHTTPClient(timeout time.Duration) *http.Client {
  436. proxyUrl := s.PanelEgressProxyURL()
  437. client, err := netproxy.NewHTTPClient(proxyUrl, timeout)
  438. if err != nil {
  439. logger.Warningf("Invalid panel egress proxy %q, using direct connection: %v", proxyUrl, err)
  440. return &http.Client{Timeout: timeout}
  441. }
  442. return client
  443. }
  444. func (s *SettingService) GetTgBotAPIServer() (string, error) {
  445. return s.getString("tgBotAPIServer")
  446. }
  447. func (s *SettingService) SetTgBotAPIServer(token string) error {
  448. return s.setString("tgBotAPIServer", token)
  449. }
  450. func (s *SettingService) GetTgBotChatId() (string, error) {
  451. return s.getString("tgBotChatId")
  452. }
  453. func (s *SettingService) SetTgBotChatId(chatIds string) error {
  454. return s.setString("tgBotChatId", chatIds)
  455. }
  456. func (s *SettingService) GetTgbotEnabled() (bool, error) {
  457. return s.getBool("tgBotEnable")
  458. }
  459. func (s *SettingService) SetTgbotEnabled(value bool) error {
  460. return s.setBool("tgBotEnable", value)
  461. }
  462. func (s *SettingService) GetTgbotRuntime() (string, error) {
  463. return s.getString("tgRunTime")
  464. }
  465. func (s *SettingService) SetTgbotRuntime(time string) error {
  466. return s.setString("tgRunTime", time)
  467. }
  468. func (s *SettingService) GetTgBotBackup() (bool, error) {
  469. return s.getBool("tgBotBackup")
  470. }
  471. func (s *SettingService) GetTgCpu() (int, error) {
  472. return s.getInt("tgCpu")
  473. }
  474. func (s *SettingService) GetTgLang() (string, error) {
  475. return s.getString("tgLang")
  476. }
  477. func (s *SettingService) GetTwoFactorEnable() (bool, error) {
  478. return s.getBool("twoFactorEnable")
  479. }
  480. func (s *SettingService) SetTwoFactorEnable(value bool) error {
  481. return s.setBool("twoFactorEnable", value)
  482. }
  483. func (s *SettingService) GetTwoFactorToken() (string, error) {
  484. return s.getString("twoFactorToken")
  485. }
  486. func (s *SettingService) SetTwoFactorToken(value string) error {
  487. return s.setString("twoFactorToken", value)
  488. }
  489. func (s *SettingService) GetPort() (int, error) {
  490. return s.getInt("webPort")
  491. }
  492. func (s *SettingService) SetPort(port int) error {
  493. return s.setInt("webPort", port)
  494. }
  495. func (s *SettingService) SetCertFile(webCertFile string) error {
  496. return s.setString("webCertFile", webCertFile)
  497. }
  498. func (s *SettingService) GetCertFile() (string, error) {
  499. return s.getString("webCertFile")
  500. }
  501. func (s *SettingService) SetKeyFile(webKeyFile string) error {
  502. return s.setString("webKeyFile", webKeyFile)
  503. }
  504. func (s *SettingService) GetKeyFile() (string, error) {
  505. return s.getString("webKeyFile")
  506. }
  507. func (s *SettingService) GetExpireDiff() (int, error) {
  508. return s.getInt("expireDiff")
  509. }
  510. func (s *SettingService) GetTrafficDiff() (int, error) {
  511. return s.getInt("trafficDiff")
  512. }
  513. func (s *SettingService) GetSessionMaxAge() (int, error) {
  514. return s.getInt("sessionMaxAge")
  515. }
  516. func (s *SettingService) GetTrustedProxyCIDRs() (string, error) {
  517. return s.getString("trustedProxyCIDRs")
  518. }
  519. func (s *SettingService) GetRemarkTemplate() (string, error) {
  520. return s.getString("remarkTemplate")
  521. }
  522. func (s *SettingService) GetSecret() ([]byte, error) {
  523. secret, err := s.getString("secret")
  524. if secret == defaultValueMap["secret"] {
  525. err := s.saveSetting("secret", secret)
  526. if err != nil {
  527. logger.Warning("save secret failed:", err)
  528. }
  529. }
  530. return []byte(secret), err
  531. }
  532. // GetPanelGuid returns this panel's stable self-identifier, persisting a
  533. // freshly generated UUID on first read. It is the globally stable node
  534. // identity used to attribute online clients and inbounds to the physical
  535. // node that hosts them across a chain of nodes (#4983), where per-panel
  536. // autoincrement node ids are meaningless one hop away.
  537. func (s *SettingService) GetPanelGuid() (string, error) {
  538. guid, err := s.getString("panelGuid")
  539. if err != nil {
  540. return "", err
  541. }
  542. if guid == defaultValueMap["panelGuid"] {
  543. if saveErr := s.saveSetting("panelGuid", guid); saveErr != nil {
  544. logger.Warning("save panelGuid failed:", saveErr)
  545. }
  546. }
  547. return guid, nil
  548. }
  549. func (s *SettingService) SetBasePath(basePath string) error {
  550. if !strings.HasPrefix(basePath, "/") {
  551. basePath = "/" + basePath
  552. }
  553. if !strings.HasSuffix(basePath, "/") {
  554. basePath += "/"
  555. }
  556. return s.setString("webBasePath", basePath)
  557. }
  558. func (s *SettingService) GetBasePath() (string, error) {
  559. basePath, err := s.getString("webBasePath")
  560. if err != nil {
  561. return "", err
  562. }
  563. return normalizeBasePath(basePath), nil
  564. }
  565. func (s *SettingService) GetTimeLocation() (*time.Location, error) {
  566. l, err := s.getString("timeLocation")
  567. if err != nil {
  568. return nil, err
  569. }
  570. location, err := time.LoadLocation(l)
  571. if err != nil {
  572. defaultLocation := defaultValueMap["timeLocation"]
  573. logger.Errorf("location <%v> not exist, using default location: %v", l, defaultLocation)
  574. location, err = time.LoadLocation(defaultLocation)
  575. if err != nil {
  576. logger.Errorf("failed to load default location, using UTC: %v", err)
  577. return time.UTC, nil
  578. }
  579. return location, nil
  580. }
  581. return location, nil
  582. }
  583. func (s *SettingService) GetSubEnable() (bool, error) {
  584. return s.getBool("subEnable")
  585. }
  586. func (s *SettingService) GetSubJsonEnable() (bool, error) {
  587. return s.getBool("subJsonEnable")
  588. }
  589. func (s *SettingService) GetSubTitle() (string, error) {
  590. return s.getString("subTitle")
  591. }
  592. func (s *SettingService) GetSubSupportUrl() (string, error) {
  593. return s.getString("subSupportUrl")
  594. }
  595. func (s *SettingService) GetSubProfileUrl() (string, error) {
  596. return s.getString("subProfileUrl")
  597. }
  598. func (s *SettingService) GetSubAnnounce() (string, error) {
  599. return s.getString("subAnnounce")
  600. }
  601. func (s *SettingService) GetSubEnableRouting() (bool, error) {
  602. return s.getBool("subEnableRouting")
  603. }
  604. func (s *SettingService) GetSubRoutingRules() (string, error) {
  605. return s.getString("subRoutingRules")
  606. }
  607. func (s *SettingService) GetSubHideSettings() (bool, error) {
  608. return s.getBool("subHideSettings")
  609. }
  610. func (s *SettingService) GetSubListen() (string, error) {
  611. return s.getString("subListen")
  612. }
  613. func (s *SettingService) GetSubPort() (int, error) {
  614. return s.getInt("subPort")
  615. }
  616. func (s *SettingService) GetSubPath() (string, error) {
  617. return s.getString("subPath")
  618. }
  619. func (s *SettingService) GetSubJsonPath() (string, error) {
  620. return s.getString("subJsonPath")
  621. }
  622. func (s *SettingService) GetSubDomain() (string, error) {
  623. return s.getString("subDomain")
  624. }
  625. func (s *SettingService) SetSubCertFile(subCertFile string) error {
  626. return s.setString("subCertFile", subCertFile)
  627. }
  628. func (s *SettingService) GetSubCertFile() (string, error) {
  629. return s.getString("subCertFile")
  630. }
  631. func (s *SettingService) SetSubKeyFile(subKeyFile string) error {
  632. return s.setString("subKeyFile", subKeyFile)
  633. }
  634. func (s *SettingService) GetSubKeyFile() (string, error) {
  635. return s.getString("subKeyFile")
  636. }
  637. func (s *SettingService) GetSubUpdates() (string, error) {
  638. return s.getString("subUpdates")
  639. }
  640. func (s *SettingService) GetSubEncrypt() (bool, error) {
  641. return s.getBool("subEncrypt")
  642. }
  643. func (s *SettingService) GetPageSize() (int, error) {
  644. return s.getInt("pageSize")
  645. }
  646. func (s *SettingService) GetSubURI() (string, error) {
  647. return s.getString("subURI")
  648. }
  649. func (s *SettingService) GetSubJsonURI() (string, error) {
  650. return s.getString("subJsonURI")
  651. }
  652. func (s *SettingService) GetSubClashEnable() (bool, error) {
  653. return s.getBool("subClashEnable")
  654. }
  655. func (s *SettingService) GetSubClashPath() (string, error) {
  656. return s.getString("subClashPath")
  657. }
  658. func (s *SettingService) GetSubClashURI() (string, error) {
  659. return s.getString("subClashURI")
  660. }
  661. func (s *SettingService) GetSubClashEnableRouting() (bool, error) {
  662. return s.getBool("subClashEnableRouting")
  663. }
  664. func (s *SettingService) GetSubClashRules() (string, error) {
  665. return s.getString("subClashRules")
  666. }
  667. func (s *SettingService) GetSubJsonMux() (string, error) {
  668. return s.getString("subJsonMux")
  669. }
  670. func (s *SettingService) GetSubJsonRules() (string, error) {
  671. return s.getString("subJsonRules")
  672. }
  673. func (s *SettingService) GetSubJsonFinalMask() (string, error) {
  674. return s.getString("subJsonFinalMask")
  675. }
  676. func (s *SettingService) GetSubThemeDir() (string, error) {
  677. return s.getString("subThemeDir")
  678. }
  679. func (s *SettingService) GetDatepicker() (string, error) {
  680. return s.getString("datepicker")
  681. }
  682. func (s *SettingService) GetWarp() (string, error) {
  683. return s.getString("warp")
  684. }
  685. func (s *SettingService) SetWarp(data string) error {
  686. return s.setString("warp", data)
  687. }
  688. func (s *SettingService) GetNord() (string, error) {
  689. return s.getString("nord")
  690. }
  691. func (s *SettingService) SetNord(data string) error {
  692. return s.setString("nord", data)
  693. }
  694. func (s *SettingService) GetExternalTrafficInformEnable() (bool, error) {
  695. return s.getBool("externalTrafficInformEnable")
  696. }
  697. func (s *SettingService) SetExternalTrafficInformEnable(value bool) error {
  698. return s.setBool("externalTrafficInformEnable", value)
  699. }
  700. func (s *SettingService) GetExternalTrafficInformURI() (string, error) {
  701. return s.getString("externalTrafficInformURI")
  702. }
  703. func (s *SettingService) SetExternalTrafficInformURI(InformURI string) error {
  704. return s.setString("externalTrafficInformURI", InformURI)
  705. }
  706. func (s *SettingService) GetRestartXrayOnClientDisable() (bool, error) {
  707. return s.getBool("restartXrayOnClientDisable")
  708. }
  709. func (s *SettingService) SetRestartXrayOnClientDisable(value bool) error {
  710. return s.setBool("restartXrayOnClientDisable", value)
  711. }
  712. // GetIpLimitEnable reports whether the IP-limit feature is available. Always
  713. // true since the panel enforces limits via the core's online-stats API; on an
  714. // older core the job falls back to access-log parsing and warns there when the
  715. // log is missing, so the UI no longer hides the field behind that condition.
  716. func (s *SettingService) GetIpLimitEnable() (bool, error) {
  717. return true, nil
  718. }
  719. // GetAccessLogEnable reports whether an Xray access log is configured. Used by
  720. // the UI for features that genuinely read the log file (the xray log viewer) —
  721. // distinct from IP limiting, which works without it.
  722. func (s *SettingService) GetAccessLogEnable() (bool, error) {
  723. accessLogPath, err := xray.GetAccessLogPath()
  724. if err != nil {
  725. return false, err
  726. }
  727. return (accessLogPath != "none" && accessLogPath != ""), nil
  728. }
  729. // GetLdapEnable returns whether LDAP is enabled.
  730. func (s *SettingService) GetLdapEnable() (bool, error) {
  731. return s.getBool("ldapEnable")
  732. }
  733. func (s *SettingService) GetLdapHost() (string, error) {
  734. return s.getString("ldapHost")
  735. }
  736. func (s *SettingService) GetLdapPort() (int, error) {
  737. return s.getInt("ldapPort")
  738. }
  739. func (s *SettingService) GetLdapUseTLS() (bool, error) {
  740. return s.getBool("ldapUseTLS")
  741. }
  742. func (s *SettingService) GetLdapBindDN() (string, error) {
  743. return s.getString("ldapBindDN")
  744. }
  745. func (s *SettingService) GetLdapPassword() (string, error) {
  746. return s.getString("ldapPassword")
  747. }
  748. func (s *SettingService) GetLdapBaseDN() (string, error) {
  749. return s.getString("ldapBaseDN")
  750. }
  751. func (s *SettingService) GetLdapUserFilter() (string, error) {
  752. return s.getString("ldapUserFilter")
  753. }
  754. func (s *SettingService) GetLdapUserAttr() (string, error) {
  755. return s.getString("ldapUserAttr")
  756. }
  757. func (s *SettingService) GetLdapVlessField() (string, error) {
  758. return s.getString("ldapVlessField")
  759. }
  760. func (s *SettingService) GetLdapSyncCron() (string, error) {
  761. return s.getString("ldapSyncCron")
  762. }
  763. func (s *SettingService) GetLdapFlagField() (string, error) {
  764. return s.getString("ldapFlagField")
  765. }
  766. func (s *SettingService) GetLdapTruthyValues() (string, error) {
  767. return s.getString("ldapTruthyValues")
  768. }
  769. func (s *SettingService) GetLdapInvertFlag() (bool, error) {
  770. return s.getBool("ldapInvertFlag")
  771. }
  772. func (s *SettingService) GetLdapInboundTags() (string, error) {
  773. return s.getString("ldapInboundTags")
  774. }
  775. func (s *SettingService) GetLdapAutoCreate() (bool, error) {
  776. return s.getBool("ldapAutoCreate")
  777. }
  778. func (s *SettingService) GetLdapAutoDelete() (bool, error) {
  779. return s.getBool("ldapAutoDelete")
  780. }
  781. func (s *SettingService) GetLdapDefaultTotalGB() (int, error) {
  782. return s.getInt("ldapDefaultTotalGB")
  783. }
  784. func (s *SettingService) GetLdapDefaultExpiryDays() (int, error) {
  785. return s.getInt("ldapDefaultExpiryDays")
  786. }
  787. func (s *SettingService) GetLdapDefaultLimitIP() (int, error) {
  788. return s.getInt("ldapDefaultLimitIP")
  789. }
  790. // Event bus — per-subscriber event filtering
  791. func (s *SettingService) GetTgEnabledEvents() (string, error) {
  792. return s.getString("tgEnabledEvents")
  793. }
  794. func (s *SettingService) SetTgEnabledEvents(events string) error {
  795. return s.setString("tgEnabledEvents", events)
  796. }
  797. func (s *SettingService) GetSmtpEnabledEvents() (string, error) {
  798. return s.getString("smtpEnabledEvents")
  799. }
  800. func (s *SettingService) SetSmtpEnabledEvents(events string) error {
  801. return s.setString("smtpEnabledEvents", events)
  802. }
  803. // Email (SMTP) settings
  804. func (s *SettingService) GetSmtpEnable() (bool, error) {
  805. return s.getBool("smtpEnable")
  806. }
  807. func (s *SettingService) SetSmtpEnable(value bool) error {
  808. return s.setBool("smtpEnable", value)
  809. }
  810. func (s *SettingService) GetSmtpHost() (string, error) {
  811. return s.getString("smtpHost")
  812. }
  813. func (s *SettingService) SetSmtpHost(value string) error {
  814. return s.setString("smtpHost", value)
  815. }
  816. func (s *SettingService) GetSmtpPort() (int, error) {
  817. return s.getInt("smtpPort")
  818. }
  819. func (s *SettingService) SetSmtpPort(value int) error {
  820. return s.setInt("smtpPort", value)
  821. }
  822. func (s *SettingService) GetSmtpUsername() (string, error) {
  823. return s.getString("smtpUsername")
  824. }
  825. func (s *SettingService) SetSmtpUsername(value string) error {
  826. return s.setString("smtpUsername", value)
  827. }
  828. func (s *SettingService) GetSmtpPassword() (string, error) {
  829. return s.getString("smtpPassword")
  830. }
  831. func (s *SettingService) SetSmtpPassword(value string) error {
  832. return s.setString("smtpPassword", value)
  833. }
  834. func (s *SettingService) GetSmtpTo() (string, error) {
  835. return s.getString("smtpTo")
  836. }
  837. func (s *SettingService) SetSmtpTo(value string) error {
  838. return s.setString("smtpTo", value)
  839. }
  840. func (s *SettingService) GetSmtpEncryptionType() (string, error) {
  841. return s.getString("smtpEncryptionType")
  842. }
  843. func (s *SettingService) SetSmtpEncryptionType(value string) error {
  844. return s.setString("smtpEncryptionType", value)
  845. }
  846. func (s *SettingService) GetSmtpCpu() (int, error) {
  847. return s.getInt("smtpCpu")
  848. }
  849. func (s *SettingService) SetSmtpCpu(value int) error {
  850. return s.setInt("smtpCpu", value)
  851. }
  852. func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting) error {
  853. if err := s.preserveRedactedSecrets(allSetting); err != nil {
  854. return err
  855. }
  856. if err := validateSettingsURLs(allSetting); err != nil {
  857. return err
  858. }
  859. if err := allSetting.CheckValid(); err != nil {
  860. return err
  861. }
  862. v := reflect.ValueOf(allSetting).Elem()
  863. t := reflect.TypeFor[entity.AllSetting]()
  864. fields := reflect_util.GetFields(t)
  865. errs := make([]error, 0)
  866. for _, field := range fields {
  867. key := field.Tag.Get("json")
  868. fieldV := v.FieldByName(field.Name)
  869. value := fmt.Sprint(fieldV.Interface())
  870. err := s.saveSetting(key, value)
  871. if err != nil {
  872. errs = append(errs, err)
  873. }
  874. }
  875. return common.Combine(errs...)
  876. }
  877. func (s *SettingService) preserveRedactedSecrets(allSetting *entity.AllSetting) error {
  878. if strings.TrimSpace(allSetting.TgBotToken) == "" {
  879. value, err := s.GetTgBotToken()
  880. if err != nil {
  881. return err
  882. }
  883. allSetting.TgBotToken = value
  884. }
  885. if strings.TrimSpace(allSetting.LdapPassword) == "" {
  886. value, err := s.GetLdapPassword()
  887. if err != nil {
  888. return err
  889. }
  890. allSetting.LdapPassword = value
  891. }
  892. if allSetting.TwoFactorEnable && strings.TrimSpace(allSetting.TwoFactorToken) == "" {
  893. value, err := s.GetTwoFactorToken()
  894. if err != nil {
  895. return err
  896. }
  897. allSetting.TwoFactorToken = value
  898. }
  899. if strings.TrimSpace(allSetting.SmtpPassword) == "" {
  900. value, err := s.GetSmtpPassword()
  901. if err != nil {
  902. return err
  903. }
  904. allSetting.SmtpPassword = value
  905. }
  906. return nil
  907. }
  908. func validateSettingsURLs(allSetting *entity.AllSetting) error {
  909. if allSetting.ExternalTrafficInformURI != "" {
  910. u, err := SanitizeHTTPURL(allSetting.ExternalTrafficInformURI)
  911. if err != nil {
  912. return common.NewError("external traffic inform URI is invalid:", err)
  913. }
  914. allSetting.ExternalTrafficInformURI = u
  915. }
  916. if allSetting.TgBotAPIServer != "" {
  917. u, err := SanitizeHTTPURL(allSetting.TgBotAPIServer)
  918. if err != nil {
  919. return common.NewError("telegram API server URL is invalid:", err)
  920. }
  921. allSetting.TgBotAPIServer = u
  922. }
  923. return nil
  924. }
  925. func (s *SettingService) UpdateSecret(key string, value string) error {
  926. switch key {
  927. case "tgBotToken", "ldapPassword", "twoFactorToken":
  928. return s.saveSetting(key, strings.TrimSpace(value))
  929. default:
  930. return common.NewError("secret key is not replaceable:", key)
  931. }
  932. }
  933. func (s *SettingService) GetDefaultXrayConfig() (any, error) {
  934. var jsonData any
  935. err := json.Unmarshal([]byte(xrayTemplateConfig), &jsonData)
  936. if err != nil {
  937. return nil, err
  938. }
  939. return jsonData, nil
  940. }
  941. func extractHostname(host string) string {
  942. h, _, err := net.SplitHostPort(host)
  943. // Err is not nil means host does not contain port
  944. if err != nil {
  945. h = host
  946. }
  947. ip := net.ParseIP(h)
  948. // If it's not an IP, return as is
  949. if ip == nil {
  950. return h
  951. }
  952. // If it's an IPv4, return as is
  953. if ip.To4() != nil {
  954. return h
  955. }
  956. // IPv6 needs bracketing
  957. return "[" + h + "]"
  958. }
  959. // BuildSubURIBase is shared by GetDefaultSettings (the panel's Client
  960. // Information page) and the subscription page so both render subscription
  961. // URLs identically.
  962. func (s *SettingService) BuildSubURIBase(host string) string {
  963. subPort, _ := s.GetSubPort()
  964. subDomain, _ := s.GetSubDomain()
  965. subKeyFile, _ := s.GetSubKeyFile()
  966. subCertFile, _ := s.GetSubCertFile()
  967. subTLS := subKeyFile != "" && subCertFile != ""
  968. if subDomain == "" {
  969. subDomain = extractHostname(host)
  970. }
  971. scheme := "http"
  972. if subTLS {
  973. scheme = "https"
  974. }
  975. if (subPort == 443 && subTLS) || (subPort == 80 && !subTLS) {
  976. return scheme + "://" + subDomain
  977. }
  978. return fmt.Sprintf("%s://%s:%d", scheme, subDomain, subPort)
  979. }
  980. func (s *SettingService) GetDefaultSettings(host string) (any, error) {
  981. type settingFunc func() (any, error)
  982. settings := map[string]settingFunc{
  983. "expireDiff": func() (any, error) { return s.GetExpireDiff() },
  984. "trafficDiff": func() (any, error) { return s.GetTrafficDiff() },
  985. "pageSize": func() (any, error) { return s.GetPageSize() },
  986. "defaultCert": func() (any, error) { return s.GetCertFile() },
  987. "defaultKey": func() (any, error) { return s.GetKeyFile() },
  988. "tgBotEnable": func() (any, error) { return s.GetTgbotEnabled() },
  989. "subThemeDir": func() (any, error) { return s.GetSubThemeDir() },
  990. "subEnable": func() (any, error) { return s.GetSubEnable() },
  991. "subJsonEnable": func() (any, error) { return s.GetSubJsonEnable() },
  992. "subClashEnable": func() (any, error) { return s.GetSubClashEnable() },
  993. "subTitle": func() (any, error) { return s.GetSubTitle() },
  994. "subURI": func() (any, error) { return s.GetSubURI() },
  995. "subJsonURI": func() (any, error) { return s.GetSubJsonURI() },
  996. "subClashURI": func() (any, error) { return s.GetSubClashURI() },
  997. "datepicker": func() (any, error) { return s.GetDatepicker() },
  998. "ipLimitEnable": func() (any, error) { return s.GetIpLimitEnable() },
  999. "accessLogEnable": func() (any, error) { return s.GetAccessLogEnable() },
  1000. "webDomain": func() (any, error) { return s.GetWebDomain() },
  1001. "subDomain": func() (any, error) { return s.GetSubDomain() },
  1002. }
  1003. result := make(map[string]any)
  1004. for key, fn := range settings {
  1005. value, err := fn()
  1006. if err != nil {
  1007. return "", err
  1008. }
  1009. result[key] = value
  1010. }
  1011. subEnable := result["subEnable"].(bool)
  1012. subJsonEnable := false
  1013. if v, ok := result["subJsonEnable"]; ok {
  1014. if b, ok2 := v.(bool); ok2 {
  1015. subJsonEnable = b
  1016. }
  1017. }
  1018. subClashEnable := false
  1019. if v, ok := result["subClashEnable"]; ok {
  1020. if b, ok2 := v.(bool); ok2 {
  1021. subClashEnable = b
  1022. }
  1023. }
  1024. if (subEnable && result["subURI"].(string) == "") || (subJsonEnable && result["subJsonURI"].(string) == "") || (subClashEnable && result["subClashURI"].(string) == "") {
  1025. subURI := s.BuildSubURIBase(host)
  1026. subTitle, _ := s.GetSubTitle()
  1027. subPath, _ := s.GetSubPath()
  1028. subJsonPath, _ := s.GetSubJsonPath()
  1029. subClashPath, _ := s.GetSubClashPath()
  1030. if subEnable && result["subURI"].(string) == "" {
  1031. result["subURI"] = subURI + subPath
  1032. }
  1033. if result["subTitle"].(string) == "" {
  1034. result["subTitle"] = subTitle
  1035. }
  1036. if subJsonEnable && result["subJsonURI"].(string) == "" {
  1037. result["subJsonURI"] = subURI + subJsonPath
  1038. }
  1039. if subClashEnable && result["subClashURI"].(string) == "" {
  1040. result["subClashURI"] = subURI + subClashPath
  1041. }
  1042. }
  1043. return result, nil
  1044. }