setting.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. package service
  2. import (
  3. _ "embed"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "reflect"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "x-ui/database"
  12. "x-ui/database/model"
  13. "x-ui/logger"
  14. "x-ui/util/common"
  15. "x-ui/util/random"
  16. "x-ui/util/reflect_util"
  17. "x-ui/web/entity"
  18. "x-ui/xray"
  19. )
  20. //go:embed config.json
  21. var xrayTemplateConfig string
  22. var defaultValueMap = map[string]string{
  23. "xrayTemplateConfig": xrayTemplateConfig,
  24. "webListen": "",
  25. "webDomain": "",
  26. "webPort": "2053",
  27. "webCertFile": "",
  28. "webKeyFile": "",
  29. "secret": random.Seq(32),
  30. "webBasePath": "/",
  31. "sessionMaxAge": "60",
  32. "pageSize": "50",
  33. "expireDiff": "0",
  34. "trafficDiff": "0",
  35. "remarkModel": "-ieo",
  36. "timeLocation": "Asia/Tehran",
  37. "tgBotEnable": "false",
  38. "tgBotToken": "",
  39. "tgBotProxy": "",
  40. "tgBotAPIServer": "",
  41. "tgBotChatId": "",
  42. "tgRunTime": "@daily",
  43. "tgBotBackup": "false",
  44. "tgBotLoginNotify": "true",
  45. "tgCpu": "80",
  46. "tgLang": "en-US",
  47. "secretEnable": "false",
  48. "subEnable": "false",
  49. "subListen": "",
  50. "subPort": "2096",
  51. "subPath": "/sub/",
  52. "subDomain": "",
  53. "subCertFile": "",
  54. "subKeyFile": "",
  55. "subUpdates": "12",
  56. "subEncrypt": "true",
  57. "subShowInfo": "true",
  58. "subURI": "",
  59. "subJsonPath": "/json/",
  60. "subJsonURI": "",
  61. "subJsonFragment": "",
  62. "subJsonNoises": "",
  63. "subJsonMux": "",
  64. "subJsonRules": "",
  65. "datepicker": "gregorian",
  66. "warp": "",
  67. }
  68. type SettingService struct{}
  69. func (s *SettingService) GetDefaultJsonConfig() (interface{}, error) {
  70. var jsonData interface{}
  71. err := json.Unmarshal([]byte(xrayTemplateConfig), &jsonData)
  72. if err != nil {
  73. return nil, err
  74. }
  75. return jsonData, nil
  76. }
  77. func (s *SettingService) GetAllSetting() (*entity.AllSetting, error) {
  78. db := database.GetDB()
  79. settings := make([]*model.Setting, 0)
  80. err := db.Model(model.Setting{}).Not("key = ?", "xrayTemplateConfig").Find(&settings).Error
  81. if err != nil {
  82. return nil, err
  83. }
  84. allSetting := &entity.AllSetting{}
  85. t := reflect.TypeOf(allSetting).Elem()
  86. v := reflect.ValueOf(allSetting).Elem()
  87. fields := reflect_util.GetFields(t)
  88. setSetting := func(key, value string) (err error) {
  89. defer func() {
  90. panicErr := recover()
  91. if panicErr != nil {
  92. err = errors.New(fmt.Sprint(panicErr))
  93. }
  94. }()
  95. var found bool
  96. var field reflect.StructField
  97. for _, f := range fields {
  98. if f.Tag.Get("json") == key {
  99. field = f
  100. found = true
  101. break
  102. }
  103. }
  104. if !found {
  105. // Some settings are automatically generated, no need to return to the front end to modify the user
  106. return nil
  107. }
  108. fieldV := v.FieldByName(field.Name)
  109. switch t := fieldV.Interface().(type) {
  110. case int:
  111. n, err := strconv.ParseInt(value, 10, 64)
  112. if err != nil {
  113. return err
  114. }
  115. fieldV.SetInt(n)
  116. case string:
  117. fieldV.SetString(value)
  118. case bool:
  119. fieldV.SetBool(value == "true")
  120. default:
  121. return common.NewErrorf("unknown field %v type %v", key, t)
  122. }
  123. return
  124. }
  125. keyMap := map[string]bool{}
  126. for _, setting := range settings {
  127. err := setSetting(setting.Key, setting.Value)
  128. if err != nil {
  129. return nil, err
  130. }
  131. keyMap[setting.Key] = true
  132. }
  133. for key, value := range defaultValueMap {
  134. if keyMap[key] {
  135. continue
  136. }
  137. err := setSetting(key, value)
  138. if err != nil {
  139. return nil, err
  140. }
  141. }
  142. return allSetting, nil
  143. }
  144. func (s *SettingService) ResetSettings() error {
  145. db := database.GetDB()
  146. err := db.Where("1 = 1").Delete(model.Setting{}).Error
  147. if err != nil {
  148. return err
  149. }
  150. return db.Model(model.User{}).
  151. Where("1 = 1").
  152. Update("login_secret", "").Error
  153. }
  154. func (s *SettingService) getSetting(key string) (*model.Setting, error) {
  155. db := database.GetDB()
  156. setting := &model.Setting{}
  157. err := db.Model(model.Setting{}).Where("key = ?", key).First(setting).Error
  158. if err != nil {
  159. return nil, err
  160. }
  161. return setting, nil
  162. }
  163. func (s *SettingService) saveSetting(key string, value string) error {
  164. setting, err := s.getSetting(key)
  165. db := database.GetDB()
  166. if database.IsNotFound(err) {
  167. return db.Create(&model.Setting{
  168. Key: key,
  169. Value: value,
  170. }).Error
  171. } else if err != nil {
  172. return err
  173. }
  174. setting.Key = key
  175. setting.Value = value
  176. return db.Save(setting).Error
  177. }
  178. func (s *SettingService) getString(key string) (string, error) {
  179. setting, err := s.getSetting(key)
  180. if database.IsNotFound(err) {
  181. value, ok := defaultValueMap[key]
  182. if !ok {
  183. return "", common.NewErrorf("key <%v> not in defaultValueMap", key)
  184. }
  185. return value, nil
  186. } else if err != nil {
  187. return "", err
  188. }
  189. return setting.Value, nil
  190. }
  191. func (s *SettingService) setString(key string, value string) error {
  192. return s.saveSetting(key, value)
  193. }
  194. func (s *SettingService) getBool(key string) (bool, error) {
  195. str, err := s.getString(key)
  196. if err != nil {
  197. return false, err
  198. }
  199. return strconv.ParseBool(str)
  200. }
  201. func (s *SettingService) setBool(key string, value bool) error {
  202. return s.setString(key, strconv.FormatBool(value))
  203. }
  204. func (s *SettingService) getInt(key string) (int, error) {
  205. str, err := s.getString(key)
  206. if err != nil {
  207. return 0, err
  208. }
  209. return strconv.Atoi(str)
  210. }
  211. func (s *SettingService) setInt(key string, value int) error {
  212. return s.setString(key, strconv.Itoa(value))
  213. }
  214. func (s *SettingService) GetXrayConfigTemplate() (string, error) {
  215. return s.getString("xrayTemplateConfig")
  216. }
  217. func (s *SettingService) GetListen() (string, error) {
  218. return s.getString("webListen")
  219. }
  220. func (s *SettingService) SetListen(ip string) error {
  221. return s.setString("webListen", ip)
  222. }
  223. func (s *SettingService) GetWebDomain() (string, error) {
  224. return s.getString("webDomain")
  225. }
  226. func (s *SettingService) GetTgBotToken() (string, error) {
  227. return s.getString("tgBotToken")
  228. }
  229. func (s *SettingService) SetTgBotToken(token string) error {
  230. return s.setString("tgBotToken", token)
  231. }
  232. func (s *SettingService) GetTgBotProxy() (string, error) {
  233. return s.getString("tgBotProxy")
  234. }
  235. func (s *SettingService) SetTgBotProxy(token string) error {
  236. return s.setString("tgBotProxy", token)
  237. }
  238. func (s *SettingService) GetTgBotAPIServer() (string, error) {
  239. return s.getString("tgBotAPIServer")
  240. }
  241. func (s *SettingService) SetTgBotAPIServer(token string) error {
  242. return s.setString("tgBotAPIServer", token)
  243. }
  244. func (s *SettingService) GetTgBotChatId() (string, error) {
  245. return s.getString("tgBotChatId")
  246. }
  247. func (s *SettingService) SetTgBotChatId(chatIds string) error {
  248. return s.setString("tgBotChatId", chatIds)
  249. }
  250. func (s *SettingService) GetTgbotEnabled() (bool, error) {
  251. return s.getBool("tgBotEnable")
  252. }
  253. func (s *SettingService) SetTgbotEnabled(value bool) error {
  254. return s.setBool("tgBotEnable", value)
  255. }
  256. func (s *SettingService) GetTgbotRuntime() (string, error) {
  257. return s.getString("tgRunTime")
  258. }
  259. func (s *SettingService) SetTgbotRuntime(time string) error {
  260. return s.setString("tgRunTime", time)
  261. }
  262. func (s *SettingService) GetTgBotBackup() (bool, error) {
  263. return s.getBool("tgBotBackup")
  264. }
  265. func (s *SettingService) GetTgBotLoginNotify() (bool, error) {
  266. return s.getBool("tgBotLoginNotify")
  267. }
  268. func (s *SettingService) GetTgCpu() (int, error) {
  269. return s.getInt("tgCpu")
  270. }
  271. func (s *SettingService) GetTgLang() (string, error) {
  272. return s.getString("tgLang")
  273. }
  274. func (s *SettingService) GetPort() (int, error) {
  275. return s.getInt("webPort")
  276. }
  277. func (s *SettingService) SetPort(port int) error {
  278. return s.setInt("webPort", port)
  279. }
  280. func (s *SettingService) SetCertFile(webCertFile string) error {
  281. return s.setString("webCertFile", webCertFile)
  282. }
  283. func (s *SettingService) GetCertFile() (string, error) {
  284. return s.getString("webCertFile")
  285. }
  286. func (s *SettingService) SetKeyFile(webKeyFile string) error {
  287. return s.setString("webKeyFile", webKeyFile)
  288. }
  289. func (s *SettingService) GetKeyFile() (string, error) {
  290. return s.getString("webKeyFile")
  291. }
  292. func (s *SettingService) GetExpireDiff() (int, error) {
  293. return s.getInt("expireDiff")
  294. }
  295. func (s *SettingService) GetTrafficDiff() (int, error) {
  296. return s.getInt("trafficDiff")
  297. }
  298. func (s *SettingService) GetSessionMaxAge() (int, error) {
  299. return s.getInt("sessionMaxAge")
  300. }
  301. func (s *SettingService) GetRemarkModel() (string, error) {
  302. return s.getString("remarkModel")
  303. }
  304. func (s *SettingService) GetSecretStatus() (bool, error) {
  305. return s.getBool("secretEnable")
  306. }
  307. func (s *SettingService) SetSecretStatus(value bool) error {
  308. return s.setBool("secretEnable", value)
  309. }
  310. func (s *SettingService) GetSecret() ([]byte, error) {
  311. secret, err := s.getString("secret")
  312. if secret == defaultValueMap["secret"] {
  313. err := s.saveSetting("secret", secret)
  314. if err != nil {
  315. logger.Warning("save secret failed:", err)
  316. }
  317. }
  318. return []byte(secret), err
  319. }
  320. func (s *SettingService) SetBasePath(basePath string) error {
  321. if !strings.HasPrefix(basePath, "/") {
  322. basePath = "/" + basePath
  323. }
  324. if !strings.HasSuffix(basePath, "/") {
  325. basePath += "/"
  326. }
  327. return s.setString("webBasePath", basePath)
  328. }
  329. func (s *SettingService) GetBasePath() (string, error) {
  330. basePath, err := s.getString("webBasePath")
  331. if err != nil {
  332. return "", err
  333. }
  334. if !strings.HasPrefix(basePath, "/") {
  335. basePath = "/" + basePath
  336. }
  337. if !strings.HasSuffix(basePath, "/") {
  338. basePath += "/"
  339. }
  340. return basePath, nil
  341. }
  342. func (s *SettingService) GetTimeLocation() (*time.Location, error) {
  343. l, err := s.getString("timeLocation")
  344. if err != nil {
  345. return nil, err
  346. }
  347. location, err := time.LoadLocation(l)
  348. if err != nil {
  349. defaultLocation := defaultValueMap["timeLocation"]
  350. logger.Errorf("location <%v> not exist, using default location: %v", l, defaultLocation)
  351. return time.LoadLocation(defaultLocation)
  352. }
  353. return location, nil
  354. }
  355. func (s *SettingService) GetSubEnable() (bool, error) {
  356. return s.getBool("subEnable")
  357. }
  358. func (s *SettingService) GetSubListen() (string, error) {
  359. return s.getString("subListen")
  360. }
  361. func (s *SettingService) GetSubPort() (int, error) {
  362. return s.getInt("subPort")
  363. }
  364. func (s *SettingService) GetSubPath() (string, error) {
  365. return s.getString("subPath")
  366. }
  367. func (s *SettingService) GetSubJsonPath() (string, error) {
  368. return s.getString("subJsonPath")
  369. }
  370. func (s *SettingService) GetSubDomain() (string, error) {
  371. return s.getString("subDomain")
  372. }
  373. func (s *SettingService) GetSubCertFile() (string, error) {
  374. return s.getString("subCertFile")
  375. }
  376. func (s *SettingService) GetSubKeyFile() (string, error) {
  377. return s.getString("subKeyFile")
  378. }
  379. func (s *SettingService) GetSubUpdates() (string, error) {
  380. return s.getString("subUpdates")
  381. }
  382. func (s *SettingService) GetSubEncrypt() (bool, error) {
  383. return s.getBool("subEncrypt")
  384. }
  385. func (s *SettingService) GetSubShowInfo() (bool, error) {
  386. return s.getBool("subShowInfo")
  387. }
  388. func (s *SettingService) GetPageSize() (int, error) {
  389. return s.getInt("pageSize")
  390. }
  391. func (s *SettingService) GetSubURI() (string, error) {
  392. return s.getString("subURI")
  393. }
  394. func (s *SettingService) GetSubJsonURI() (string, error) {
  395. return s.getString("subJsonURI")
  396. }
  397. func (s *SettingService) GetSubJsonFragment() (string, error) {
  398. return s.getString("subJsonFragment")
  399. }
  400. func (s *SettingService) GetSubJsonNoises() (string, error) {
  401. return s.getString("subJsonNoises")
  402. }
  403. func (s *SettingService) GetSubJsonMux() (string, error) {
  404. return s.getString("subJsonMux")
  405. }
  406. func (s *SettingService) GetSubJsonRules() (string, error) {
  407. return s.getString("subJsonRules")
  408. }
  409. func (s *SettingService) GetDatepicker() (string, error) {
  410. return s.getString("datepicker")
  411. }
  412. func (s *SettingService) GetWarp() (string, error) {
  413. return s.getString("warp")
  414. }
  415. func (s *SettingService) SetWarp(data string) error {
  416. return s.setString("warp", data)
  417. }
  418. func (s *SettingService) GetIpLimitEnable() (bool, error) {
  419. accessLogPath, err := xray.GetAccessLogPath()
  420. if err != nil {
  421. return false, err
  422. }
  423. return (accessLogPath != "none" && accessLogPath != ""), nil
  424. }
  425. func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting) error {
  426. if err := allSetting.CheckValid(); err != nil {
  427. return err
  428. }
  429. v := reflect.ValueOf(allSetting).Elem()
  430. t := reflect.TypeOf(allSetting).Elem()
  431. fields := reflect_util.GetFields(t)
  432. errs := make([]error, 0)
  433. for _, field := range fields {
  434. key := field.Tag.Get("json")
  435. fieldV := v.FieldByName(field.Name)
  436. value := fmt.Sprint(fieldV.Interface())
  437. err := s.saveSetting(key, value)
  438. if err != nil {
  439. errs = append(errs, err)
  440. }
  441. }
  442. return common.Combine(errs...)
  443. }
  444. func (s *SettingService) GetDefaultXrayConfig() (interface{}, error) {
  445. var jsonData interface{}
  446. err := json.Unmarshal([]byte(xrayTemplateConfig), &jsonData)
  447. if err != nil {
  448. return nil, err
  449. }
  450. return jsonData, nil
  451. }
  452. func (s *SettingService) GetDefaultSettings(host string) (interface{}, error) {
  453. type settingFunc func() (interface{}, error)
  454. settings := map[string]settingFunc{
  455. "expireDiff": func() (interface{}, error) { return s.GetExpireDiff() },
  456. "trafficDiff": func() (interface{}, error) { return s.GetTrafficDiff() },
  457. "pageSize": func() (interface{}, error) { return s.GetPageSize() },
  458. "defaultCert": func() (interface{}, error) { return s.GetCertFile() },
  459. "defaultKey": func() (interface{}, error) { return s.GetKeyFile() },
  460. "tgBotEnable": func() (interface{}, error) { return s.GetTgbotEnabled() },
  461. "subEnable": func() (interface{}, error) { return s.GetSubEnable() },
  462. "subURI": func() (interface{}, error) { return s.GetSubURI() },
  463. "subJsonURI": func() (interface{}, error) { return s.GetSubJsonURI() },
  464. "remarkModel": func() (interface{}, error) { return s.GetRemarkModel() },
  465. "datepicker": func() (interface{}, error) { return s.GetDatepicker() },
  466. "ipLimitEnable": func() (interface{}, error) { return s.GetIpLimitEnable() },
  467. }
  468. result := make(map[string]interface{})
  469. for key, fn := range settings {
  470. value, err := fn()
  471. if err != nil {
  472. return "", err
  473. }
  474. result[key] = value
  475. }
  476. if result["subEnable"].(bool) && (result["subURI"].(string) == "" || result["subJsonURI"].(string) == "") {
  477. subURI := ""
  478. subPort, _ := s.GetSubPort()
  479. subPath, _ := s.GetSubPath()
  480. subJsonPath, _ := s.GetSubJsonPath()
  481. subDomain, _ := s.GetSubDomain()
  482. subKeyFile, _ := s.GetSubKeyFile()
  483. subCertFile, _ := s.GetSubCertFile()
  484. subTLS := false
  485. if subKeyFile != "" && subCertFile != "" {
  486. subTLS = true
  487. }
  488. if subDomain == "" {
  489. subDomain = strings.Split(host, ":")[0]
  490. }
  491. if subTLS {
  492. subURI = "https://"
  493. } else {
  494. subURI = "http://"
  495. }
  496. if (subPort == 443 && subTLS) || (subPort == 80 && !subTLS) {
  497. subURI += subDomain
  498. } else {
  499. subURI += fmt.Sprintf("%s:%d", subDomain, subPort)
  500. }
  501. if result["subURI"].(string) == "" {
  502. result["subURI"] = subURI + subPath
  503. }
  504. if result["subJsonURI"].(string) == "" {
  505. result["subJsonURI"] = subURI + subJsonPath
  506. }
  507. }
  508. return result, nil
  509. }