setting.go 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. package service
  2. import (
  3. _ "embed"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "reflect"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/mhsanaei/3x-ui/v3/database"
  14. "github.com/mhsanaei/3x-ui/v3/database/model"
  15. "github.com/mhsanaei/3x-ui/v3/logger"
  16. "github.com/mhsanaei/3x-ui/v3/util/common"
  17. "github.com/mhsanaei/3x-ui/v3/util/netproxy"
  18. "github.com/mhsanaei/3x-ui/v3/util/random"
  19. "github.com/mhsanaei/3x-ui/v3/util/reflect_util"
  20. "github.com/mhsanaei/3x-ui/v3/web/entity"
  21. "github.com/mhsanaei/3x-ui/v3/xray"
  22. )
  23. //go:embed config.json
  24. var xrayTemplateConfig string
  25. var defaultValueMap = map[string]string{
  26. "xrayTemplateConfig": xrayTemplateConfig,
  27. "webListen": "",
  28. "webDomain": "",
  29. "webPort": "2053",
  30. "webCertFile": "",
  31. "webKeyFile": "",
  32. "secret": random.Seq(32),
  33. "apiToken": "",
  34. "webBasePath": "/",
  35. "sessionMaxAge": "360",
  36. "trustedProxyCIDRs": "127.0.0.1/32,::1/128",
  37. "pageSize": "25",
  38. "expireDiff": "0",
  39. "trafficDiff": "0",
  40. "remarkModel": "-ieo",
  41. "timeLocation": "Local",
  42. "tgBotEnable": "false",
  43. "tgBotToken": "",
  44. "tgBotProxy": "",
  45. "tgBotAPIServer": "",
  46. "tgBotChatId": "",
  47. "tgRunTime": "@daily",
  48. "tgBotBackup": "false",
  49. "tgBotLoginNotify": "true",
  50. "tgCpu": "80",
  51. "tgLang": "en-US",
  52. "twoFactorEnable": "false",
  53. "twoFactorToken": "",
  54. "subEnable": "true",
  55. "subJsonEnable": "false",
  56. "subTitle": "",
  57. "subSupportUrl": "",
  58. "subProfileUrl": "",
  59. "subAnnounce": "",
  60. "subEnableRouting": "true",
  61. "subRoutingRules": "",
  62. "subListen": "",
  63. "subPort": "2096",
  64. "subPath": "/sub/",
  65. "subDomain": "",
  66. "subCertFile": "",
  67. "subKeyFile": "",
  68. "subUpdates": "12",
  69. "subEncrypt": "true",
  70. "subShowInfo": "true",
  71. "subEmailInRemark": "true",
  72. "subURI": "",
  73. "subJsonPath": "/json/",
  74. "subJsonURI": "",
  75. "subClashEnable": "true",
  76. "subClashPath": "/clash/",
  77. "subClashURI": "",
  78. "subJsonFragment": "",
  79. "subJsonNoises": "",
  80. "subJsonMux": "",
  81. "subJsonRules": "",
  82. "datepicker": "gregorian",
  83. "warp": "",
  84. "nord": "",
  85. "externalTrafficInformEnable": "false",
  86. "externalTrafficInformURI": "",
  87. "restartXrayOnClientDisable": "true",
  88. "xrayOutboundTestUrl": "https://www.google.com/generate_204",
  89. "panelProxy": "",
  90. // LDAP defaults
  91. "ldapEnable": "false",
  92. "ldapHost": "",
  93. "ldapPort": "389",
  94. "ldapUseTLS": "false",
  95. "ldapBindDN": "",
  96. "ldapPassword": "",
  97. "ldapBaseDN": "",
  98. "ldapUserFilter": "(objectClass=person)",
  99. "ldapUserAttr": "mail",
  100. "ldapVlessField": "vless_enabled",
  101. "ldapSyncCron": "@every 1m",
  102. "ldapFlagField": "",
  103. "ldapTruthyValues": "true,1,yes,on",
  104. "ldapInvertFlag": "false",
  105. "ldapInboundTags": "",
  106. "ldapAutoCreate": "false",
  107. "ldapAutoDelete": "false",
  108. "ldapDefaultTotalGB": "0",
  109. "ldapDefaultExpiryDays": "0",
  110. "ldapDefaultLimitIP": "0",
  111. }
  112. // SettingService provides business logic for application settings management.
  113. // It handles configuration storage, retrieval, and validation for all system settings.
  114. type SettingService struct{}
  115. func (s *SettingService) GetDefaultJSONConfig() (any, error) {
  116. var jsonData any
  117. err := json.Unmarshal([]byte(xrayTemplateConfig), &jsonData)
  118. if err != nil {
  119. return nil, err
  120. }
  121. return jsonData, nil
  122. }
  123. func (s *SettingService) GetAllSetting() (*entity.AllSetting, error) {
  124. db := database.GetDB()
  125. settings := make([]*model.Setting, 0)
  126. err := db.Model(model.Setting{}).Not("key = ?", "xrayTemplateConfig").Find(&settings).Error
  127. if err != nil {
  128. return nil, err
  129. }
  130. allSetting := &entity.AllSetting{}
  131. t := reflect.TypeFor[entity.AllSetting]()
  132. v := reflect.ValueOf(allSetting).Elem()
  133. fields := reflect_util.GetFields(t)
  134. setSetting := func(key, value string) (err error) {
  135. defer func() {
  136. panicErr := recover()
  137. if panicErr != nil {
  138. err = errors.New(fmt.Sprint(panicErr))
  139. }
  140. }()
  141. var found bool
  142. var field reflect.StructField
  143. for _, f := range fields {
  144. if f.Tag.Get("json") == key {
  145. field = f
  146. found = true
  147. break
  148. }
  149. }
  150. if !found {
  151. // Some settings are automatically generated, no need to return to the front end to modify the user
  152. return nil
  153. }
  154. fieldV := v.FieldByName(field.Name)
  155. switch t := fieldV.Interface().(type) {
  156. case int:
  157. n, err := strconv.ParseInt(effectiveSettingValue(key, value), 10, 64)
  158. if err != nil {
  159. return err
  160. }
  161. fieldV.SetInt(n)
  162. case string:
  163. fieldV.SetString(value)
  164. case bool:
  165. fieldV.SetBool(effectiveSettingValue(key, value) == "true")
  166. default:
  167. return common.NewErrorf("unknown field %v type %v", key, t)
  168. }
  169. return
  170. }
  171. keyMap := map[string]bool{}
  172. for _, setting := range settings {
  173. err := setSetting(setting.Key, setting.Value)
  174. if err != nil {
  175. return nil, err
  176. }
  177. keyMap[setting.Key] = true
  178. }
  179. for key, value := range defaultValueMap {
  180. if keyMap[key] {
  181. continue
  182. }
  183. err := setSetting(key, value)
  184. if err != nil {
  185. return nil, err
  186. }
  187. }
  188. return allSetting, nil
  189. }
  190. func (s *SettingService) GetAllSettingView() (*entity.AllSettingView, error) {
  191. allSetting, err := s.GetAllSetting()
  192. if err != nil {
  193. return nil, err
  194. }
  195. view := &entity.AllSettingView{AllSetting: *allSetting}
  196. view.HasTgBotToken = secretConfigured(allSetting.TgBotToken)
  197. view.HasTwoFactorToken = secretConfigured(allSetting.TwoFactorToken)
  198. view.HasLdapPassword = secretConfigured(allSetting.LdapPassword)
  199. view.HasWarpSecret = secretConfigured(mustString(s.GetWarp()))
  200. view.HasNordSecret = secretConfigured(mustString(s.GetNord()))
  201. var apiTokenCount int64
  202. if err := database.GetDB().Model(model.ApiToken{}).Where("enabled = ?", true).Count(&apiTokenCount).Error; err == nil {
  203. view.HasApiToken = apiTokenCount > 0
  204. }
  205. view.TgBotToken = ""
  206. view.TwoFactorToken = ""
  207. view.LdapPassword = ""
  208. return view, nil
  209. }
  210. func secretConfigured(value string) bool {
  211. return strings.TrimSpace(value) != ""
  212. }
  213. func mustString(value string, _ error) string {
  214. return value
  215. }
  216. func (s *SettingService) ResetSettings() error {
  217. db := database.GetDB()
  218. err := db.Where("1 = 1").Delete(model.Setting{}).Error
  219. if err != nil {
  220. return err
  221. }
  222. return db.Model(model.User{}).
  223. Where("1 = 1").Error
  224. }
  225. func (s *SettingService) getSetting(key string) (*model.Setting, error) {
  226. db := database.GetDB()
  227. setting := &model.Setting{}
  228. err := db.Model(model.Setting{}).Where("key = ?", key).First(setting).Error
  229. if err != nil {
  230. return nil, err
  231. }
  232. return setting, nil
  233. }
  234. func (s *SettingService) saveSetting(key string, value string) error {
  235. setting, err := s.getSetting(key)
  236. db := database.GetDB()
  237. if database.IsNotFound(err) {
  238. return db.Create(&model.Setting{
  239. Key: key,
  240. Value: value,
  241. }).Error
  242. } else if err != nil {
  243. return err
  244. }
  245. setting.Key = key
  246. setting.Value = value
  247. return db.Save(setting).Error
  248. }
  249. func (s *SettingService) getString(key string) (string, error) {
  250. setting, err := s.getSetting(key)
  251. if database.IsNotFound(err) {
  252. value, ok := defaultValueMap[key]
  253. if !ok {
  254. return "", common.NewErrorf("key <%v> not in defaultValueMap", key)
  255. }
  256. return value, nil
  257. } else if err != nil {
  258. return "", err
  259. }
  260. return setting.Value, nil
  261. }
  262. func (s *SettingService) setString(key string, value string) error {
  263. return s.saveSetting(key, value)
  264. }
  265. func effectiveSettingValue(key, stored string) string {
  266. if stored == "" {
  267. if def, ok := defaultValueMap[key]; ok {
  268. return def
  269. }
  270. }
  271. return stored
  272. }
  273. func (s *SettingService) getBool(key string) (bool, error) {
  274. str, err := s.getString(key)
  275. if err != nil {
  276. return false, err
  277. }
  278. return strconv.ParseBool(effectiveSettingValue(key, str))
  279. }
  280. func (s *SettingService) setBool(key string, value bool) error {
  281. return s.setString(key, strconv.FormatBool(value))
  282. }
  283. func (s *SettingService) getInt(key string) (int, error) {
  284. str, err := s.getString(key)
  285. if err != nil {
  286. return 0, err
  287. }
  288. return strconv.Atoi(effectiveSettingValue(key, str))
  289. }
  290. func (s *SettingService) setInt(key string, value int) error {
  291. return s.setString(key, strconv.Itoa(value))
  292. }
  293. func (s *SettingService) GetXrayConfigTemplate() (string, error) {
  294. return s.getString("xrayTemplateConfig")
  295. }
  296. func (s *SettingService) GetXrayOutboundTestUrl() (string, error) {
  297. return s.getString("xrayOutboundTestUrl")
  298. }
  299. func (s *SettingService) SetXrayOutboundTestUrl(url string) error {
  300. clean, err := SanitizeHTTPURL(url)
  301. if err != nil {
  302. return err
  303. }
  304. return s.setString("xrayOutboundTestUrl", clean)
  305. }
  306. func (s *SettingService) GetListen() (string, error) {
  307. return s.getString("webListen")
  308. }
  309. func (s *SettingService) SetListen(ip string) error {
  310. return s.setString("webListen", ip)
  311. }
  312. func (s *SettingService) GetWebDomain() (string, error) {
  313. return s.getString("webDomain")
  314. }
  315. func (s *SettingService) GetTgBotToken() (string, error) {
  316. return s.getString("tgBotToken")
  317. }
  318. func (s *SettingService) SetTgBotToken(token string) error {
  319. return s.setString("tgBotToken", token)
  320. }
  321. func (s *SettingService) GetTgBotProxy() (string, error) {
  322. return s.getString("tgBotProxy")
  323. }
  324. func (s *SettingService) SetTgBotProxy(token string) error {
  325. return s.setString("tgBotProxy", token)
  326. }
  327. func (s *SettingService) GetPanelProxy() (string, error) {
  328. return s.getString("panelProxy")
  329. }
  330. func (s *SettingService) SetPanelProxy(proxyUrl string) error {
  331. return s.setString("panelProxy", proxyUrl)
  332. }
  333. // NewProxiedHTTPClient returns an HTTP client that routes the panel's own
  334. // outbound requests through the configured panelProxy setting. An invalid or
  335. // missing proxy falls back to a direct client so existing behavior is preserved.
  336. func (s *SettingService) NewProxiedHTTPClient(timeout time.Duration) *http.Client {
  337. proxyUrl, err := s.GetPanelProxy()
  338. if err != nil {
  339. logger.Warning("Failed to read panel proxy setting:", err)
  340. proxyUrl = ""
  341. }
  342. client, err := netproxy.NewHTTPClient(proxyUrl, timeout)
  343. if err != nil {
  344. logger.Warningf("Invalid panel proxy %q, using direct connection: %v", proxyUrl, err)
  345. return &http.Client{Timeout: timeout}
  346. }
  347. return client
  348. }
  349. func (s *SettingService) GetTgBotAPIServer() (string, error) {
  350. return s.getString("tgBotAPIServer")
  351. }
  352. func (s *SettingService) SetTgBotAPIServer(token string) error {
  353. return s.setString("tgBotAPIServer", token)
  354. }
  355. func (s *SettingService) GetTgBotChatId() (string, error) {
  356. return s.getString("tgBotChatId")
  357. }
  358. func (s *SettingService) SetTgBotChatId(chatIds string) error {
  359. return s.setString("tgBotChatId", chatIds)
  360. }
  361. func (s *SettingService) GetTgbotEnabled() (bool, error) {
  362. return s.getBool("tgBotEnable")
  363. }
  364. func (s *SettingService) SetTgbotEnabled(value bool) error {
  365. return s.setBool("tgBotEnable", value)
  366. }
  367. func (s *SettingService) GetTgbotRuntime() (string, error) {
  368. return s.getString("tgRunTime")
  369. }
  370. func (s *SettingService) SetTgbotRuntime(time string) error {
  371. return s.setString("tgRunTime", time)
  372. }
  373. func (s *SettingService) GetTgBotBackup() (bool, error) {
  374. return s.getBool("tgBotBackup")
  375. }
  376. func (s *SettingService) GetTgBotLoginNotify() (bool, error) {
  377. return s.getBool("tgBotLoginNotify")
  378. }
  379. func (s *SettingService) GetTgCpu() (int, error) {
  380. return s.getInt("tgCpu")
  381. }
  382. func (s *SettingService) GetTgLang() (string, error) {
  383. return s.getString("tgLang")
  384. }
  385. func (s *SettingService) GetTwoFactorEnable() (bool, error) {
  386. return s.getBool("twoFactorEnable")
  387. }
  388. func (s *SettingService) SetTwoFactorEnable(value bool) error {
  389. return s.setBool("twoFactorEnable", value)
  390. }
  391. func (s *SettingService) GetTwoFactorToken() (string, error) {
  392. return s.getString("twoFactorToken")
  393. }
  394. func (s *SettingService) SetTwoFactorToken(value string) error {
  395. return s.setString("twoFactorToken", value)
  396. }
  397. func (s *SettingService) GetPort() (int, error) {
  398. return s.getInt("webPort")
  399. }
  400. func (s *SettingService) SetPort(port int) error {
  401. return s.setInt("webPort", port)
  402. }
  403. func (s *SettingService) SetCertFile(webCertFile string) error {
  404. return s.setString("webCertFile", webCertFile)
  405. }
  406. func (s *SettingService) GetCertFile() (string, error) {
  407. return s.getString("webCertFile")
  408. }
  409. func (s *SettingService) SetKeyFile(webKeyFile string) error {
  410. return s.setString("webKeyFile", webKeyFile)
  411. }
  412. func (s *SettingService) GetKeyFile() (string, error) {
  413. return s.getString("webKeyFile")
  414. }
  415. func (s *SettingService) GetExpireDiff() (int, error) {
  416. return s.getInt("expireDiff")
  417. }
  418. func (s *SettingService) GetTrafficDiff() (int, error) {
  419. return s.getInt("trafficDiff")
  420. }
  421. func (s *SettingService) GetSessionMaxAge() (int, error) {
  422. return s.getInt("sessionMaxAge")
  423. }
  424. func (s *SettingService) GetTrustedProxyCIDRs() (string, error) {
  425. return s.getString("trustedProxyCIDRs")
  426. }
  427. func (s *SettingService) GetRemarkModel() (string, error) {
  428. return s.getString("remarkModel")
  429. }
  430. func (s *SettingService) GetSecret() ([]byte, error) {
  431. secret, err := s.getString("secret")
  432. if secret == defaultValueMap["secret"] {
  433. err := s.saveSetting("secret", secret)
  434. if err != nil {
  435. logger.Warning("save secret failed:", err)
  436. }
  437. }
  438. return []byte(secret), err
  439. }
  440. func (s *SettingService) SetBasePath(basePath string) error {
  441. if !strings.HasPrefix(basePath, "/") {
  442. basePath = "/" + basePath
  443. }
  444. if !strings.HasSuffix(basePath, "/") {
  445. basePath += "/"
  446. }
  447. return s.setString("webBasePath", basePath)
  448. }
  449. func (s *SettingService) GetBasePath() (string, error) {
  450. basePath, err := s.getString("webBasePath")
  451. if err != nil {
  452. return "", err
  453. }
  454. if !strings.HasPrefix(basePath, "/") {
  455. basePath = "/" + basePath
  456. }
  457. if !strings.HasSuffix(basePath, "/") {
  458. basePath += "/"
  459. }
  460. return basePath, nil
  461. }
  462. func (s *SettingService) GetTimeLocation() (*time.Location, error) {
  463. l, err := s.getString("timeLocation")
  464. if err != nil {
  465. return nil, err
  466. }
  467. location, err := time.LoadLocation(l)
  468. if err != nil {
  469. defaultLocation := defaultValueMap["timeLocation"]
  470. logger.Errorf("location <%v> not exist, using default location: %v", l, defaultLocation)
  471. location, err = time.LoadLocation(defaultLocation)
  472. if err != nil {
  473. logger.Errorf("failed to load default location, using UTC: %v", err)
  474. return time.UTC, nil
  475. }
  476. return location, nil
  477. }
  478. return location, nil
  479. }
  480. func (s *SettingService) GetSubEnable() (bool, error) {
  481. return s.getBool("subEnable")
  482. }
  483. func (s *SettingService) GetSubJsonEnable() (bool, error) {
  484. return s.getBool("subJsonEnable")
  485. }
  486. func (s *SettingService) GetSubTitle() (string, error) {
  487. return s.getString("subTitle")
  488. }
  489. func (s *SettingService) GetSubSupportUrl() (string, error) {
  490. return s.getString("subSupportUrl")
  491. }
  492. func (s *SettingService) GetSubProfileUrl() (string, error) {
  493. return s.getString("subProfileUrl")
  494. }
  495. func (s *SettingService) GetSubAnnounce() (string, error) {
  496. return s.getString("subAnnounce")
  497. }
  498. func (s *SettingService) GetSubEnableRouting() (bool, error) {
  499. return s.getBool("subEnableRouting")
  500. }
  501. func (s *SettingService) GetSubRoutingRules() (string, error) {
  502. return s.getString("subRoutingRules")
  503. }
  504. func (s *SettingService) GetSubListen() (string, error) {
  505. return s.getString("subListen")
  506. }
  507. func (s *SettingService) GetSubPort() (int, error) {
  508. return s.getInt("subPort")
  509. }
  510. func (s *SettingService) GetSubPath() (string, error) {
  511. return s.getString("subPath")
  512. }
  513. func (s *SettingService) GetSubJsonPath() (string, error) {
  514. return s.getString("subJsonPath")
  515. }
  516. func (s *SettingService) GetSubDomain() (string, error) {
  517. return s.getString("subDomain")
  518. }
  519. func (s *SettingService) SetSubCertFile(subCertFile string) error {
  520. return s.setString("subCertFile", subCertFile)
  521. }
  522. func (s *SettingService) GetSubCertFile() (string, error) {
  523. return s.getString("subCertFile")
  524. }
  525. func (s *SettingService) SetSubKeyFile(subKeyFile string) error {
  526. return s.setString("subKeyFile", subKeyFile)
  527. }
  528. func (s *SettingService) GetSubKeyFile() (string, error) {
  529. return s.getString("subKeyFile")
  530. }
  531. func (s *SettingService) GetSubUpdates() (string, error) {
  532. return s.getString("subUpdates")
  533. }
  534. func (s *SettingService) GetSubEncrypt() (bool, error) {
  535. return s.getBool("subEncrypt")
  536. }
  537. func (s *SettingService) GetSubShowInfo() (bool, error) {
  538. return s.getBool("subShowInfo")
  539. }
  540. func (s *SettingService) GetSubEmailInRemark() (bool, error) {
  541. return s.getBool("subEmailInRemark")
  542. }
  543. func (s *SettingService) GetPageSize() (int, error) {
  544. return s.getInt("pageSize")
  545. }
  546. func (s *SettingService) GetSubURI() (string, error) {
  547. return s.getString("subURI")
  548. }
  549. func (s *SettingService) GetSubJsonURI() (string, error) {
  550. return s.getString("subJsonURI")
  551. }
  552. func (s *SettingService) GetSubClashEnable() (bool, error) {
  553. return s.getBool("subClashEnable")
  554. }
  555. func (s *SettingService) GetSubClashPath() (string, error) {
  556. return s.getString("subClashPath")
  557. }
  558. func (s *SettingService) GetSubClashURI() (string, error) {
  559. return s.getString("subClashURI")
  560. }
  561. func (s *SettingService) GetSubJsonFragment() (string, error) {
  562. return s.getString("subJsonFragment")
  563. }
  564. func (s *SettingService) GetSubJsonNoises() (string, error) {
  565. return s.getString("subJsonNoises")
  566. }
  567. func (s *SettingService) GetSubJsonMux() (string, error) {
  568. return s.getString("subJsonMux")
  569. }
  570. func (s *SettingService) GetSubJsonRules() (string, error) {
  571. return s.getString("subJsonRules")
  572. }
  573. func (s *SettingService) GetDatepicker() (string, error) {
  574. return s.getString("datepicker")
  575. }
  576. func (s *SettingService) GetWarp() (string, error) {
  577. return s.getString("warp")
  578. }
  579. func (s *SettingService) SetWarp(data string) error {
  580. return s.setString("warp", data)
  581. }
  582. func (s *SettingService) GetNord() (string, error) {
  583. return s.getString("nord")
  584. }
  585. func (s *SettingService) SetNord(data string) error {
  586. return s.setString("nord", data)
  587. }
  588. func (s *SettingService) GetExternalTrafficInformEnable() (bool, error) {
  589. return s.getBool("externalTrafficInformEnable")
  590. }
  591. func (s *SettingService) SetExternalTrafficInformEnable(value bool) error {
  592. return s.setBool("externalTrafficInformEnable", value)
  593. }
  594. func (s *SettingService) GetExternalTrafficInformURI() (string, error) {
  595. return s.getString("externalTrafficInformURI")
  596. }
  597. func (s *SettingService) SetExternalTrafficInformURI(InformURI string) error {
  598. return s.setString("externalTrafficInformURI", InformURI)
  599. }
  600. func (s *SettingService) GetRestartXrayOnClientDisable() (bool, error) {
  601. return s.getBool("restartXrayOnClientDisable")
  602. }
  603. func (s *SettingService) SetRestartXrayOnClientDisable(value bool) error {
  604. return s.setBool("restartXrayOnClientDisable", value)
  605. }
  606. func (s *SettingService) GetIpLimitEnable() (bool, error) {
  607. accessLogPath, err := xray.GetAccessLogPath()
  608. if err != nil {
  609. return false, err
  610. }
  611. return (accessLogPath != "none" && accessLogPath != ""), nil
  612. }
  613. // GetLdapEnable returns whether LDAP is enabled.
  614. func (s *SettingService) GetLdapEnable() (bool, error) {
  615. return s.getBool("ldapEnable")
  616. }
  617. func (s *SettingService) GetLdapHost() (string, error) {
  618. return s.getString("ldapHost")
  619. }
  620. func (s *SettingService) GetLdapPort() (int, error) {
  621. return s.getInt("ldapPort")
  622. }
  623. func (s *SettingService) GetLdapUseTLS() (bool, error) {
  624. return s.getBool("ldapUseTLS")
  625. }
  626. func (s *SettingService) GetLdapBindDN() (string, error) {
  627. return s.getString("ldapBindDN")
  628. }
  629. func (s *SettingService) GetLdapPassword() (string, error) {
  630. return s.getString("ldapPassword")
  631. }
  632. func (s *SettingService) GetLdapBaseDN() (string, error) {
  633. return s.getString("ldapBaseDN")
  634. }
  635. func (s *SettingService) GetLdapUserFilter() (string, error) {
  636. return s.getString("ldapUserFilter")
  637. }
  638. func (s *SettingService) GetLdapUserAttr() (string, error) {
  639. return s.getString("ldapUserAttr")
  640. }
  641. func (s *SettingService) GetLdapVlessField() (string, error) {
  642. return s.getString("ldapVlessField")
  643. }
  644. func (s *SettingService) GetLdapSyncCron() (string, error) {
  645. return s.getString("ldapSyncCron")
  646. }
  647. func (s *SettingService) GetLdapFlagField() (string, error) {
  648. return s.getString("ldapFlagField")
  649. }
  650. func (s *SettingService) GetLdapTruthyValues() (string, error) {
  651. return s.getString("ldapTruthyValues")
  652. }
  653. func (s *SettingService) GetLdapInvertFlag() (bool, error) {
  654. return s.getBool("ldapInvertFlag")
  655. }
  656. func (s *SettingService) GetLdapInboundTags() (string, error) {
  657. return s.getString("ldapInboundTags")
  658. }
  659. func (s *SettingService) GetLdapAutoCreate() (bool, error) {
  660. return s.getBool("ldapAutoCreate")
  661. }
  662. func (s *SettingService) GetLdapAutoDelete() (bool, error) {
  663. return s.getBool("ldapAutoDelete")
  664. }
  665. func (s *SettingService) GetLdapDefaultTotalGB() (int, error) {
  666. return s.getInt("ldapDefaultTotalGB")
  667. }
  668. func (s *SettingService) GetLdapDefaultExpiryDays() (int, error) {
  669. return s.getInt("ldapDefaultExpiryDays")
  670. }
  671. func (s *SettingService) GetLdapDefaultLimitIP() (int, error) {
  672. return s.getInt("ldapDefaultLimitIP")
  673. }
  674. func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting) error {
  675. if err := s.preserveRedactedSecrets(allSetting); err != nil {
  676. return err
  677. }
  678. if err := validateSettingsURLs(allSetting); err != nil {
  679. return err
  680. }
  681. if err := allSetting.CheckValid(); err != nil {
  682. return err
  683. }
  684. v := reflect.ValueOf(allSetting).Elem()
  685. t := reflect.TypeFor[entity.AllSetting]()
  686. fields := reflect_util.GetFields(t)
  687. errs := make([]error, 0)
  688. for _, field := range fields {
  689. key := field.Tag.Get("json")
  690. fieldV := v.FieldByName(field.Name)
  691. value := fmt.Sprint(fieldV.Interface())
  692. err := s.saveSetting(key, value)
  693. if err != nil {
  694. errs = append(errs, err)
  695. }
  696. }
  697. return common.Combine(errs...)
  698. }
  699. func (s *SettingService) preserveRedactedSecrets(allSetting *entity.AllSetting) error {
  700. if strings.TrimSpace(allSetting.TgBotToken) == "" {
  701. value, err := s.GetTgBotToken()
  702. if err != nil {
  703. return err
  704. }
  705. allSetting.TgBotToken = value
  706. }
  707. if strings.TrimSpace(allSetting.LdapPassword) == "" {
  708. value, err := s.GetLdapPassword()
  709. if err != nil {
  710. return err
  711. }
  712. allSetting.LdapPassword = value
  713. }
  714. if allSetting.TwoFactorEnable && strings.TrimSpace(allSetting.TwoFactorToken) == "" {
  715. value, err := s.GetTwoFactorToken()
  716. if err != nil {
  717. return err
  718. }
  719. allSetting.TwoFactorToken = value
  720. }
  721. return nil
  722. }
  723. func validateSettingsURLs(allSetting *entity.AllSetting) error {
  724. if allSetting.ExternalTrafficInformURI != "" {
  725. u, err := SanitizeHTTPURL(allSetting.ExternalTrafficInformURI)
  726. if err != nil {
  727. return common.NewError("external traffic inform URI is invalid:", err)
  728. }
  729. allSetting.ExternalTrafficInformURI = u
  730. }
  731. if allSetting.TgBotAPIServer != "" {
  732. u, err := SanitizeHTTPURL(allSetting.TgBotAPIServer)
  733. if err != nil {
  734. return common.NewError("telegram API server URL is invalid:", err)
  735. }
  736. allSetting.TgBotAPIServer = u
  737. }
  738. return nil
  739. }
  740. func (s *SettingService) UpdateSecret(key string, value string) error {
  741. switch key {
  742. case "tgBotToken", "ldapPassword", "twoFactorToken":
  743. return s.saveSetting(key, strings.TrimSpace(value))
  744. default:
  745. return common.NewError("secret key is not replaceable:", key)
  746. }
  747. }
  748. func (s *SettingService) GetDefaultXrayConfig() (any, error) {
  749. var jsonData any
  750. err := json.Unmarshal([]byte(xrayTemplateConfig), &jsonData)
  751. if err != nil {
  752. return nil, err
  753. }
  754. return jsonData, nil
  755. }
  756. func extractHostname(host string) string {
  757. h, _, err := net.SplitHostPort(host)
  758. // Err is not nil means host does not contain port
  759. if err != nil {
  760. h = host
  761. }
  762. ip := net.ParseIP(h)
  763. // If it's not an IP, return as is
  764. if ip == nil {
  765. return h
  766. }
  767. // If it's an IPv4, return as is
  768. if ip.To4() != nil {
  769. return h
  770. }
  771. // IPv6 needs bracketing
  772. return "[" + h + "]"
  773. }
  774. // BuildSubURIBase is shared by GetDefaultSettings (the panel's Client
  775. // Information page) and the subscription page so both render subscription
  776. // URLs identically.
  777. func (s *SettingService) BuildSubURIBase(host string) string {
  778. subPort, _ := s.GetSubPort()
  779. subDomain, _ := s.GetSubDomain()
  780. subKeyFile, _ := s.GetSubKeyFile()
  781. subCertFile, _ := s.GetSubCertFile()
  782. subTLS := subKeyFile != "" && subCertFile != ""
  783. if subDomain == "" {
  784. subDomain = extractHostname(host)
  785. }
  786. scheme := "http"
  787. if subTLS {
  788. scheme = "https"
  789. }
  790. if (subPort == 443 && subTLS) || (subPort == 80 && !subTLS) {
  791. return scheme + "://" + subDomain
  792. }
  793. return fmt.Sprintf("%s://%s:%d", scheme, subDomain, subPort)
  794. }
  795. func (s *SettingService) GetDefaultSettings(host string) (any, error) {
  796. type settingFunc func() (any, error)
  797. settings := map[string]settingFunc{
  798. "expireDiff": func() (any, error) { return s.GetExpireDiff() },
  799. "trafficDiff": func() (any, error) { return s.GetTrafficDiff() },
  800. "pageSize": func() (any, error) { return s.GetPageSize() },
  801. "defaultCert": func() (any, error) { return s.GetCertFile() },
  802. "defaultKey": func() (any, error) { return s.GetKeyFile() },
  803. "tgBotEnable": func() (any, error) { return s.GetTgbotEnabled() },
  804. "subEnable": func() (any, error) { return s.GetSubEnable() },
  805. "subJsonEnable": func() (any, error) { return s.GetSubJsonEnable() },
  806. "subClashEnable": func() (any, error) { return s.GetSubClashEnable() },
  807. "subTitle": func() (any, error) { return s.GetSubTitle() },
  808. "subURI": func() (any, error) { return s.GetSubURI() },
  809. "subJsonURI": func() (any, error) { return s.GetSubJsonURI() },
  810. "subClashURI": func() (any, error) { return s.GetSubClashURI() },
  811. "remarkModel": func() (any, error) { return s.GetRemarkModel() },
  812. "datepicker": func() (any, error) { return s.GetDatepicker() },
  813. "ipLimitEnable": func() (any, error) { return s.GetIpLimitEnable() },
  814. }
  815. result := make(map[string]any)
  816. for key, fn := range settings {
  817. value, err := fn()
  818. if err != nil {
  819. return "", err
  820. }
  821. result[key] = value
  822. }
  823. subEnable := result["subEnable"].(bool)
  824. subJsonEnable := false
  825. if v, ok := result["subJsonEnable"]; ok {
  826. if b, ok2 := v.(bool); ok2 {
  827. subJsonEnable = b
  828. }
  829. }
  830. subClashEnable := false
  831. if v, ok := result["subClashEnable"]; ok {
  832. if b, ok2 := v.(bool); ok2 {
  833. subClashEnable = b
  834. }
  835. }
  836. if (subEnable && result["subURI"].(string) == "") || (subJsonEnable && result["subJsonURI"].(string) == "") || (subClashEnable && result["subClashURI"].(string) == "") {
  837. subURI := s.BuildSubURIBase(host)
  838. subTitle, _ := s.GetSubTitle()
  839. subPath, _ := s.GetSubPath()
  840. subJsonPath, _ := s.GetSubJsonPath()
  841. subClashPath, _ := s.GetSubClashPath()
  842. if subEnable && result["subURI"].(string) == "" {
  843. result["subURI"] = subURI + subPath
  844. }
  845. if result["subTitle"].(string) == "" {
  846. result["subTitle"] = subTitle
  847. }
  848. if subJsonEnable && result["subJsonURI"].(string) == "" {
  849. result["subJsonURI"] = subURI + subJsonPath
  850. }
  851. if subClashEnable && result["subClashURI"].(string) == "" {
  852. result["subClashURI"] = subURI + subClashPath
  853. }
  854. }
  855. return result, nil
  856. }