1
0

setting.go 34 KB

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