setting.go 36 KB

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