setting.go 28 KB

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