setting.go 34 KB

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