1
0

setting.go 34 KB

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