setting.go 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806
  1. package service
  2. import (
  3. _ "embed"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "os"
  10. "reflect"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/google/uuid"
  16. "github.com/xlzd/gotp"
  17. "gorm.io/gorm"
  18. "github.com/mhsanaei/3x-ui/v3/internal/config"
  19. "github.com/mhsanaei/3x-ui/v3/internal/database"
  20. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  21. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  22. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  23. "github.com/mhsanaei/3x-ui/v3/internal/util/netproxy"
  24. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  25. "github.com/mhsanaei/3x-ui/v3/internal/util/reflect_util"
  26. "github.com/mhsanaei/3x-ui/v3/internal/web/entity"
  27. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  28. "github.com/mhsanaei/3x-ui/v3/internal/xray/dnsconf"
  29. )
  30. //go:embed config.json
  31. var xrayTemplateConfig string
  32. const (
  33. DefaultSubClashUserAgentRegex = `(?i)(clash|mihomo)`
  34. DefaultSubJsonUserAgentRegex = ``
  35. DefaultRemarkTemplate = "{{INBOUND}}-{{EMAIL}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D"
  36. DefaultSubExpiredTemplate = "⛔ {{EMAIL}} | Expired: {{EXPIRE_DATE}}"
  37. DefaultSubTrafficDepletedTemplate = "🚫 {{EMAIL}} | Traffic Depleted | {{TRAFFIC_USED}}/{{TRAFFIC_TOTAL}}"
  38. DefaultTrustedProxyCIDRs = "127.0.0.1/32,::1/128"
  39. maxRegexLength = 2048
  40. )
  41. var defaultValueMap = map[string]string{
  42. "xrayTemplateConfig": xrayTemplateConfig,
  43. "webListen": "",
  44. "webDomain": "",
  45. "webPort": "2053",
  46. "webCertFile": "",
  47. "webKeyFile": "",
  48. "secret": random.Seq(32),
  49. "panelGuid": uuid.NewString(),
  50. "apiToken": "",
  51. // Node mTLS material (opt-in). All default empty: the CA + master client
  52. // cert are minted lazily on first use, and the node-side trust CA is pasted
  53. // in by the operator. Kept out of entity.AllSetting so private keys never
  54. // reach the settings UI/export.
  55. "nodeMtlsCaCertPem": "",
  56. "nodeMtlsCaKeyPem": "",
  57. "nodeMtlsClientCertPem": "",
  58. "nodeMtlsClientKeyPem": "",
  59. "nodeMtlsClientCertSha256": "",
  60. "nodeMtlsClientCAPem": "",
  61. "webBasePath": normalizeBasePath(getEnv("XUI_INIT_WEB_BASE_PATH", "/")),
  62. "sessionMaxAge": "360",
  63. "trustedProxyCIDRs": DefaultTrustedProxyCIDRs,
  64. "ipLimitAllowlist": "",
  65. "pageSize": "25",
  66. "expireDiff": "0",
  67. "trafficDiff": "0",
  68. "remarkTemplate": DefaultRemarkTemplate,
  69. "subShowIdentityOnAllLinks": "false",
  70. "subInfoNodeEnable": "false",
  71. "subExpiredTemplate": DefaultSubExpiredTemplate,
  72. "subTrafficDepletedTemplate": DefaultSubTrafficDepletedTemplate,
  73. "timeLocation": "Local",
  74. "tgBotEnable": "false",
  75. "tgBotToken": "",
  76. "tgBotProxy": "",
  77. "tgBotAPIServer": "",
  78. "tgBotChatId": "",
  79. "tgRunTime": "@daily",
  80. "tgBotBackup": "false",
  81. "tgCpu": "80",
  82. "tgMemory": "80",
  83. "tgLang": "en-US",
  84. "twoFactorEnable": "false",
  85. "twoFactorToken": "",
  86. "happLinkEnable": "false",
  87. "subEnable": "true",
  88. "subJsonEnable": "false",
  89. "subJsonAutoDetect": "false",
  90. "subJsonAlwaysArray": "false",
  91. "subJsonUserAgentRegex": "",
  92. "subClashAutoDetect": "false",
  93. "subClashUserAgentRegex": "",
  94. "subTitle": "",
  95. "subSupportUrl": "",
  96. "subProfileUrl": "",
  97. "subAnnounce": "",
  98. "subEnableRouting": "false",
  99. "subRoutingRules": "",
  100. "subHideSettings": "false",
  101. "subHappAutoDetect": "false",
  102. "subHappProviderId": "",
  103. "subHappNewUrl": "",
  104. "subHappFallbackUrl": "",
  105. "subHappSubInfoColor": "blue",
  106. "subHappSubInfoText": "",
  107. "subHappSubInfoButtonText": "",
  108. "subHappSubInfoButtonLink": "",
  109. "subHappSubExpire": "false",
  110. "subHappSubExpireButtonLink": "",
  111. "subHappNotificationExpire": "false",
  112. "subHappNoLimit": "false",
  113. "subHappAlwaysHwid": "false",
  114. "subHappTunMode": "",
  115. "subHappTunType": "",
  116. "subHappExcludeRoutes": "",
  117. "subHappExcludeApns": "false",
  118. "subHappColorProfile": "",
  119. "subHappPingType": "",
  120. "subHappAutoConnect": "false",
  121. "subHappAutoConnectType": "lowestdelay",
  122. "subHappPerAppMode": "off",
  123. "subHappPerAppList": "",
  124. "subIncyEnableRouting": "false",
  125. "subIncyRoutingRules": "",
  126. "subListen": "",
  127. "subPort": "2096",
  128. "subPath": "/sub/",
  129. "subDomain": "",
  130. "subCertFile": "",
  131. "subKeyFile": "",
  132. "subUpdates": "12",
  133. "subEncrypt": "true",
  134. "subURI": "",
  135. "subJsonPath": "/json/",
  136. "subJsonURI": "",
  137. "subClashEnable": "false",
  138. "subClashPath": "/clash/",
  139. "subClashURI": "",
  140. "subClashEnableRouting": "false",
  141. "subClashRules": "",
  142. "subJsonMux": "",
  143. "subJsonRules": "",
  144. "subJsonRoutingRules": "",
  145. "subJsonDns": "",
  146. "subJsonFinalMask": "",
  147. "subJsonObservatory": "",
  148. "subThemeDir": "",
  149. "datepicker": "gregorian",
  150. "warp": "",
  151. "warpUpdateInterval": "0",
  152. "nord": "",
  153. "pia": "",
  154. "externalTrafficInformEnable": "false",
  155. "externalTrafficInformURI": "",
  156. "restartXrayOnClientDisable": "true",
  157. "xrayOutboundTestUrl": "https://www.google.com/generate_204",
  158. "panelOutbound": "",
  159. "devChannelEnable": "false",
  160. // LDAP defaults
  161. "ldapEnable": "false",
  162. "ldapHost": "",
  163. "ldapPort": "389",
  164. "ldapUseTLS": "false",
  165. "ldapInsecureSkipVerify": "false",
  166. "ldapBindDN": "",
  167. "ldapPassword": "",
  168. "ldapBaseDN": "",
  169. "ldapUserFilter": "(objectClass=person)",
  170. "ldapUserAttr": "mail",
  171. "ldapVlessField": "vless_enabled",
  172. "ldapSyncCron": "@every 1m",
  173. "ldapFlagField": "",
  174. "ldapTruthyValues": "true,1,yes,on",
  175. "ldapInvertFlag": "false",
  176. "ldapInboundTags": "",
  177. "ldapAutoCreate": "false",
  178. "ldapAutoDelete": "false",
  179. "ldapDefaultTotalGB": "0",
  180. "ldapDefaultExpiryDays": "0",
  181. "ldapDefaultLimitIP": "0",
  182. // Event bus — per-subscriber event filtering (empty = all disabled)
  183. "tgEnabledEvents": "login.attempt,cpu.high",
  184. "smtpEnabledEvents": "login.attempt,cpu.high",
  185. "smtpCpu": "80",
  186. "smtpMemory": "80",
  187. // Consecutive failed observatory probes before an outbound.down event fires
  188. "outboundDownThreshold": "3",
  189. // Email (SMTP) notifications
  190. "smtpEnable": "false",
  191. "smtpHost": "",
  192. "smtpPort": "587",
  193. "smtpUsername": "",
  194. "smtpPassword": "",
  195. "smtpFrom": "",
  196. "smtpFromName": "",
  197. "smtpTo": "",
  198. "smtpEncryptionType": "starttls", // no, starttls, tls
  199. // Discord bot notifications
  200. "discordBotEnable": "false",
  201. "discordBotToken": "",
  202. "discordChannelId": "",
  203. "discordAdminIds": "",
  204. "discordRunTime": "@daily",
  205. "discordBotBackup": "false",
  206. "discordCpu": "80",
  207. "discordMemory": "80",
  208. "discordLang": "en-US",
  209. "discordEnabledEvents": "login.attempt,cpu.high",
  210. }
  211. // SettingService provides business logic for application settings management.
  212. // It handles configuration storage, retrieval, and validation for all system settings.
  213. type SettingService struct{}
  214. func (s *SettingService) GetAllSetting() (*entity.AllSetting, error) {
  215. db := database.GetDB()
  216. settings := make([]*model.Setting, 0)
  217. err := db.Model(model.Setting{}).Not("key = ?", "xrayTemplateConfig").Find(&settings).Error
  218. if err != nil {
  219. return nil, err
  220. }
  221. allSetting := &entity.AllSetting{}
  222. t := reflect.TypeFor[entity.AllSetting]()
  223. v := reflect.ValueOf(allSetting).Elem()
  224. fields := reflect_util.GetFields(t)
  225. setSetting := func(key, value string) (err error) {
  226. defer func() {
  227. panicErr := recover()
  228. if panicErr != nil {
  229. err = errors.New(fmt.Sprint(panicErr))
  230. }
  231. }()
  232. var found bool
  233. var field reflect.StructField
  234. for _, f := range fields {
  235. if f.Tag.Get("json") == key {
  236. field = f
  237. found = true
  238. break
  239. }
  240. }
  241. if !found {
  242. // Some settings are automatically generated, no need to return to the front end to modify the user
  243. return nil
  244. }
  245. fieldV := v.FieldByName(field.Name)
  246. switch t := fieldV.Interface().(type) {
  247. case int:
  248. n, err := strconv.ParseInt(effectiveSettingValue(key, value), 10, 64)
  249. if err != nil {
  250. return err
  251. }
  252. fieldV.SetInt(n)
  253. case string:
  254. fieldV.SetString(value)
  255. case bool:
  256. fieldV.SetBool(effectiveSettingValue(key, value) == "true")
  257. default:
  258. return common.NewErrorf("unknown field %v type %v", key, t)
  259. }
  260. return
  261. }
  262. keyMap := map[string]bool{}
  263. for _, setting := range settings {
  264. err := setSetting(setting.Key, setting.Value)
  265. if err != nil {
  266. return nil, err
  267. }
  268. keyMap[setting.Key] = true
  269. }
  270. for key, value := range defaultValueMap {
  271. if keyMap[key] {
  272. continue
  273. }
  274. err := setSetting(key, value)
  275. if err != nil {
  276. return nil, err
  277. }
  278. }
  279. return allSetting, nil
  280. }
  281. func (s *SettingService) GetAllSettingView() (*entity.AllSettingView, error) {
  282. allSetting, err := s.GetAllSetting()
  283. if err != nil {
  284. return nil, err
  285. }
  286. view := &entity.AllSettingView{AllSetting: *allSetting}
  287. view.HasTgBotToken = secretConfigured(allSetting.TgBotToken)
  288. view.HasTwoFactorToken = secretConfigured(allSetting.TwoFactorToken)
  289. view.HasLdapPassword = secretConfigured(allSetting.LdapPassword)
  290. view.HasWarpSecret = secretConfigured(mustString(s.GetWarp()))
  291. view.HasNordSecret = secretConfigured(mustString(s.GetNord()))
  292. view.HasSmtpPassword = secretConfigured(allSetting.SmtpPassword)
  293. view.HasDiscordBotToken = secretConfigured(allSetting.DiscordBotToken)
  294. var apiTokenCount int64
  295. if err := database.GetDB().Model(model.ApiToken{}).Where("enabled = ?", true).Count(&apiTokenCount).Error; err == nil {
  296. view.HasApiToken = apiTokenCount > 0
  297. }
  298. view.TgBotToken = ""
  299. view.TwoFactorToken = ""
  300. view.LdapPassword = ""
  301. view.SmtpPassword = ""
  302. view.DiscordBotToken = ""
  303. return view, nil
  304. }
  305. func secretConfigured(value string) bool {
  306. return strings.TrimSpace(value) != ""
  307. }
  308. func mustString(value string, _ error) string {
  309. return value
  310. }
  311. func getEnv(key, fallback string) string {
  312. val, ok := os.LookupEnv(key)
  313. if !ok {
  314. return fallback
  315. }
  316. val = strings.TrimSpace(val)
  317. if val == "" {
  318. return fallback
  319. }
  320. return val
  321. }
  322. func (s *SettingService) ResetSettings() error {
  323. db := database.GetDB()
  324. return db.Transaction(func(tx *gorm.DB) error {
  325. if err := tx.Where("1 = 1").Delete(model.Setting{}).Error; err != nil {
  326. return err
  327. }
  328. paths := []model.Setting{
  329. {Key: "subPath", Value: "/" + random.NumLower(16) + "/"},
  330. {Key: "subJsonPath", Value: "/" + random.NumLower(16) + "/"},
  331. {Key: "subClashPath", Value: "/" + random.NumLower(16) + "/"},
  332. }
  333. return tx.Create(&paths).Error
  334. })
  335. }
  336. func (s *SettingService) getSetting(key string) (*model.Setting, error) {
  337. db := database.GetDB()
  338. setting := &model.Setting{}
  339. err := db.Model(model.Setting{}).Where("key = ?", key).First(setting).Error
  340. if err != nil {
  341. return nil, err
  342. }
  343. return setting, nil
  344. }
  345. func (s *SettingService) saveSetting(key string, value string) error {
  346. setting, err := s.getSetting(key)
  347. db := database.GetDB()
  348. if database.IsNotFound(err) {
  349. return db.Create(&model.Setting{
  350. Key: key,
  351. Value: value,
  352. }).Error
  353. } else if err != nil {
  354. return err
  355. }
  356. setting.Key = key
  357. setting.Value = value
  358. return db.Save(setting).Error
  359. }
  360. func (s *SettingService) getString(key string) (string, error) {
  361. setting, err := s.getSetting(key)
  362. if database.IsNotFound(err) {
  363. value, ok := defaultValueMap[key]
  364. if !ok {
  365. return "", common.NewErrorf("key <%v> not in defaultValueMap", key)
  366. }
  367. return value, nil
  368. } else if err != nil {
  369. return "", err
  370. }
  371. return setting.Value, nil
  372. }
  373. func (s *SettingService) setString(key string, value string) error {
  374. return s.saveSetting(key, value)
  375. }
  376. func effectiveSettingValue(key, stored string) string {
  377. if stored == "" {
  378. if def, ok := defaultValueMap[key]; ok {
  379. return def
  380. }
  381. }
  382. return stored
  383. }
  384. func (s *SettingService) getBool(key string) (bool, error) {
  385. str, err := s.getString(key)
  386. if err != nil {
  387. return false, err
  388. }
  389. return strconv.ParseBool(effectiveSettingValue(key, str))
  390. }
  391. func (s *SettingService) setBool(key string, value bool) error {
  392. return s.setString(key, strconv.FormatBool(value))
  393. }
  394. func (s *SettingService) getInt(key string) (int, error) {
  395. str, err := s.getString(key)
  396. if err != nil {
  397. return 0, err
  398. }
  399. return strconv.Atoi(effectiveSettingValue(key, str))
  400. }
  401. func (s *SettingService) setInt(key string, value int) error {
  402. return s.setString(key, strconv.Itoa(value))
  403. }
  404. func (s *SettingService) GetWarpLastUpdate() (int64, error) {
  405. setting, err := s.getSetting("warpLastUpdate")
  406. if database.IsNotFound(err) {
  407. return 0, nil
  408. }
  409. if err != nil {
  410. return 0, err
  411. }
  412. if setting.Value == "" {
  413. return 0, nil
  414. }
  415. return strconv.ParseInt(setting.Value, 10, 64)
  416. }
  417. func (s *SettingService) SetWarpLastUpdate(val int64) error {
  418. return s.saveSetting("warpLastUpdate", strconv.FormatInt(val, 10))
  419. }
  420. func (s *SettingService) SetWarpUpdateInterval(val int) error {
  421. return s.setInt("warpUpdateInterval", val)
  422. }
  423. func (s *SettingService) GetXrayConfigTemplate() (string, error) {
  424. return s.getString("xrayTemplateConfig")
  425. }
  426. func (s *SettingService) GetXrayOutboundTestUrl() (string, error) {
  427. return s.getString("xrayOutboundTestUrl")
  428. }
  429. func (s *SettingService) SetXrayOutboundTestUrl(url string) error {
  430. clean, err := SanitizeHTTPURL(url)
  431. if err != nil {
  432. return err
  433. }
  434. return s.setString("xrayOutboundTestUrl", clean)
  435. }
  436. func (s *SettingService) GetListen() (string, error) {
  437. return s.getString("webListen")
  438. }
  439. func (s *SettingService) SetListen(ip string) error {
  440. return s.setString("webListen", ip)
  441. }
  442. func (s *SettingService) GetWebDomain() (string, error) {
  443. return s.getString("webDomain")
  444. }
  445. func (s *SettingService) GetTgBotToken() (string, error) {
  446. return s.getString("tgBotToken")
  447. }
  448. func (s *SettingService) SetTgBotToken(token string) error {
  449. return s.setString("tgBotToken", token)
  450. }
  451. func (s *SettingService) GetTgBotProxy() (string, error) {
  452. return s.getString("tgBotProxy")
  453. }
  454. func (s *SettingService) SetTgBotProxy(token string) error {
  455. return s.setString("tgBotProxy", token)
  456. }
  457. // GetPanelOutbound returns the Xray outbound tag the panel's own outbound
  458. // requests (version checks, Telegram, subscription fetches) are routed through.
  459. func (s *SettingService) GetPanelOutbound() (string, error) {
  460. return s.getString("panelOutbound")
  461. }
  462. func (s *SettingService) SetPanelOutbound(tag string) error {
  463. return s.setString("panelOutbound", tag)
  464. }
  465. // PanelEgressProxyURL resolves the loopback SOCKS bridge that the generated
  466. // config exposes when a panel outbound is configured (see injectPanelEgress).
  467. // It returns "" — meaning a direct connection — when the feature is off or
  468. // the bridge is not present in the running core yet.
  469. func (s *SettingService) PanelEgressProxyURL() string {
  470. tag, err := s.GetPanelOutbound()
  471. if err != nil || tag == "" {
  472. return ""
  473. }
  474. proc := XrayProcess()
  475. if proc == nil || !proc.IsRunning() {
  476. logger.Warning("panel outbound [", tag, "] is set but Xray is not running, using a direct connection")
  477. return ""
  478. }
  479. cfg := proc.GetConfig()
  480. if cfg == nil {
  481. return ""
  482. }
  483. for i := range cfg.InboundConfigs {
  484. if cfg.InboundConfigs[i].Tag == PanelEgressInboundTag {
  485. return fmt.Sprintf("socks5://127.0.0.1:%d", cfg.InboundConfigs[i].Port)
  486. }
  487. }
  488. logger.Warning("panel outbound [", tag, "] is set but the egress bridge is not in the running config, using a direct connection")
  489. return ""
  490. }
  491. func (s *SettingService) NodeEgressProxyURL(nodeID int) string {
  492. tag := NodeEgressInboundTag(nodeID)
  493. proc := XrayProcess()
  494. if proc == nil || !proc.IsRunning() {
  495. logger.Warning("node outbound [", tag, "] is set but Xray is not running, using a direct connection")
  496. return ""
  497. }
  498. cfg := proc.GetConfig()
  499. if cfg == nil {
  500. return ""
  501. }
  502. for i := range cfg.InboundConfigs {
  503. if cfg.InboundConfigs[i].Tag == tag {
  504. return fmt.Sprintf("socks5://127.0.0.1:%d", cfg.InboundConfigs[i].Port)
  505. }
  506. }
  507. logger.Warning("node outbound [", tag, "] is set but the egress bridge is not in the running config, using a direct connection")
  508. return ""
  509. }
  510. // NewProxiedHTTPClient returns an HTTP client that routes the panel's own
  511. // outbound requests through the configured panel outbound (via the loopback
  512. // SOCKS bridge in the running Xray). When the feature is off or the bridge
  513. // is unavailable it falls back to a direct client.
  514. func (s *SettingService) NewProxiedHTTPClient(timeout time.Duration) *http.Client {
  515. proxyUrl := s.PanelEgressProxyURL()
  516. client, err := netproxy.NewHTTPClient(proxyUrl, timeout)
  517. if err != nil {
  518. logger.Warningf("Invalid panel egress proxy %q, using direct connection: %v", proxyUrl, err)
  519. return &http.Client{Timeout: timeout}
  520. }
  521. return client
  522. }
  523. func (s *SettingService) GetTgBotAPIServer() (string, error) {
  524. return s.getString("tgBotAPIServer")
  525. }
  526. func (s *SettingService) SetTgBotAPIServer(token string) error {
  527. return s.setString("tgBotAPIServer", token)
  528. }
  529. func (s *SettingService) GetTgBotChatId() (string, error) {
  530. return s.getString("tgBotChatId")
  531. }
  532. func (s *SettingService) SetTgBotChatId(chatIds string) error {
  533. return s.setString("tgBotChatId", chatIds)
  534. }
  535. func (s *SettingService) GetTgbotEnabled() (bool, error) {
  536. return s.getBool("tgBotEnable")
  537. }
  538. func (s *SettingService) SetTgbotEnabled(value bool) error {
  539. return s.setBool("tgBotEnable", value)
  540. }
  541. func (s *SettingService) GetTgbotRuntime() (string, error) {
  542. return s.getString("tgRunTime")
  543. }
  544. func (s *SettingService) SetTgbotRuntime(time string) error {
  545. return s.setString("tgRunTime", time)
  546. }
  547. func (s *SettingService) GetTgBotBackup() (bool, error) {
  548. return s.getBool("tgBotBackup")
  549. }
  550. func (s *SettingService) GetTgCpu() (int, error) {
  551. return s.getInt("tgCpu")
  552. }
  553. func (s *SettingService) GetTgMemory() (int, error) {
  554. return s.getInt("tgMemory")
  555. }
  556. func (s *SettingService) SetTgMemory(value int) error {
  557. return s.setInt("tgMemory", value)
  558. }
  559. func (s *SettingService) GetTgLang() (string, error) {
  560. return s.getString("tgLang")
  561. }
  562. func (s *SettingService) GetTwoFactorEnable() (bool, error) {
  563. return s.getBool("twoFactorEnable")
  564. }
  565. func (s *SettingService) SetTwoFactorEnable(value bool) error {
  566. return s.setBool("twoFactorEnable", value)
  567. }
  568. func (s *SettingService) GetTwoFactorToken() (string, error) {
  569. return s.getString("twoFactorToken")
  570. }
  571. func (s *SettingService) SetTwoFactorToken(value string) error {
  572. return s.setString("twoFactorToken", value)
  573. }
  574. func (s *SettingService) VerifyTwoFactorCode(code string) error {
  575. enabled, err := s.GetTwoFactorEnable()
  576. if err != nil {
  577. return err
  578. }
  579. if !enabled {
  580. return nil
  581. }
  582. token, err := s.GetTwoFactorToken()
  583. if err != nil {
  584. return err
  585. }
  586. if strings.TrimSpace(token) == "" || !gotp.NewDefaultTOTP(token).Verify(strings.TrimSpace(code), time.Now().Unix()) {
  587. return common.NewError("invalid two factor code")
  588. }
  589. return nil
  590. }
  591. func (s *SettingService) GetPort() (int, error) {
  592. return s.getInt("webPort")
  593. }
  594. func (s *SettingService) SetPort(port int) error {
  595. return s.setInt("webPort", port)
  596. }
  597. func (s *SettingService) SetCertFile(webCertFile string) error {
  598. return s.setString("webCertFile", webCertFile)
  599. }
  600. func (s *SettingService) GetCertFile() (string, error) {
  601. return s.getString("webCertFile")
  602. }
  603. func (s *SettingService) SetKeyFile(webKeyFile string) error {
  604. return s.setString("webKeyFile", webKeyFile)
  605. }
  606. func (s *SettingService) GetKeyFile() (string, error) {
  607. return s.getString("webKeyFile")
  608. }
  609. func (s *SettingService) GetExpireDiff() (int, error) {
  610. return s.getInt("expireDiff")
  611. }
  612. func (s *SettingService) GetTrafficDiff() (int, error) {
  613. return s.getInt("trafficDiff")
  614. }
  615. func (s *SettingService) GetSessionMaxAge() (int, error) {
  616. return s.getInt("sessionMaxAge")
  617. }
  618. // GetIpLimitAllowlist returns the operator's trusted addresses and networks,
  619. // which the IP limit neither counts nor bans.
  620. func (s *SettingService) GetIpLimitAllowlist() (string, error) {
  621. return s.getString("ipLimitAllowlist")
  622. }
  623. func (s *SettingService) GetTrustedProxyCIDRs() (string, error) {
  624. return s.getString("trustedProxyCIDRs")
  625. }
  626. func (s *SettingService) GetRemarkTemplate() (string, error) {
  627. return s.getString("remarkTemplate")
  628. }
  629. func (s *SettingService) GetSubShowIdentityOnAllLinks() (bool, error) {
  630. return s.getBool("subShowIdentityOnAllLinks")
  631. }
  632. func (s *SettingService) GetSubInfoNodeEnable() (bool, error) {
  633. return s.getBool("subInfoNodeEnable")
  634. }
  635. func (s *SettingService) GetSubExpiredTemplate() (string, error) {
  636. return s.getString("subExpiredTemplate")
  637. }
  638. func (s *SettingService) GetSubTrafficDepletedTemplate() (string, error) {
  639. return s.getString("subTrafficDepletedTemplate")
  640. }
  641. func (s *SettingService) GetSecret() ([]byte, error) {
  642. secret, err := s.getString("secret")
  643. if secret == "" || secret == defaultValueMap["secret"] {
  644. if secret == "" {
  645. secret = defaultValueMap["secret"]
  646. }
  647. saveErr := s.saveSetting("secret", secret)
  648. if saveErr != nil {
  649. logger.Warning("save secret failed:", saveErr)
  650. }
  651. }
  652. return []byte(secret), err
  653. }
  654. // GetPanelGuid returns this panel's stable self-identifier, persisting a
  655. // freshly generated UUID on first read. It is the globally stable node
  656. // identity used to attribute online clients and inbounds to the physical
  657. // node that hosts them across a chain of nodes (#4983), where per-panel
  658. // autoincrement node ids are meaningless one hop away.
  659. func (s *SettingService) GetPanelGuid() (string, error) {
  660. guid, err := s.getString("panelGuid")
  661. if err != nil {
  662. return "", err
  663. }
  664. if guid == defaultValueMap["panelGuid"] {
  665. if saveErr := s.saveSetting("panelGuid", guid); saveErr != nil {
  666. logger.Warning("save panelGuid failed:", saveErr)
  667. }
  668. }
  669. return guid, nil
  670. }
  671. func (s *SettingService) SetBasePath(basePath string) error {
  672. if !strings.HasPrefix(basePath, "/") {
  673. basePath = "/" + basePath
  674. }
  675. if !strings.HasSuffix(basePath, "/") {
  676. basePath += "/"
  677. }
  678. return s.setString("webBasePath", basePath)
  679. }
  680. func (s *SettingService) GetBasePath() (string, error) {
  681. basePath, err := s.getString("webBasePath")
  682. if err != nil {
  683. return "", err
  684. }
  685. return normalizeBasePath(basePath), nil
  686. }
  687. func (s *SettingService) GetTimeLocation() (*time.Location, error) {
  688. l, err := s.getString("timeLocation")
  689. if err != nil {
  690. return nil, err
  691. }
  692. location, err := time.LoadLocation(l)
  693. if err != nil {
  694. defaultLocation := defaultValueMap["timeLocation"]
  695. logger.Errorf("location <%v> not exist, using default location: %v", l, defaultLocation)
  696. location, err = time.LoadLocation(defaultLocation)
  697. if err != nil {
  698. logger.Errorf("failed to load default location, using UTC: %v", err)
  699. return time.UTC, nil
  700. }
  701. return location, nil
  702. }
  703. return location, nil
  704. }
  705. func (s *SettingService) GetSubEnable() (bool, error) {
  706. return s.getBool("subEnable")
  707. }
  708. func (s *SettingService) GetHappLinkEnable() (bool, error) {
  709. return s.getBool("happLinkEnable")
  710. }
  711. func (s *SettingService) GetSubJsonEnable() (bool, error) {
  712. return s.getBool("subJsonEnable")
  713. }
  714. func (s *SettingService) GetSubJsonAutoDetect() (bool, error) {
  715. return s.getBool("subJsonAutoDetect")
  716. }
  717. func (s *SettingService) GetSubJsonAlwaysArray() (bool, error) {
  718. return s.getBool("subJsonAlwaysArray")
  719. }
  720. func (s *SettingService) GetSubJsonUserAgentRegex() (string, error) {
  721. return s.getString("subJsonUserAgentRegex")
  722. }
  723. func (s *SettingService) GetSubClashAutoDetect() (bool, error) {
  724. return s.getBool("subClashAutoDetect")
  725. }
  726. func (s *SettingService) GetSubClashUserAgentRegex() (string, error) {
  727. return s.getString("subClashUserAgentRegex")
  728. }
  729. func (s *SettingService) GetSubTitle() (string, error) {
  730. return s.getString("subTitle")
  731. }
  732. func (s *SettingService) GetSubSupportUrl() (string, error) {
  733. value, err := s.getString("subSupportUrl")
  734. return common.EnsureURLScheme(value), err
  735. }
  736. func (s *SettingService) GetSubProfileUrl() (string, error) {
  737. value, err := s.getString("subProfileUrl")
  738. return common.EnsureURLScheme(value), err
  739. }
  740. func (s *SettingService) GetSubAnnounce() (string, error) {
  741. return s.getString("subAnnounce")
  742. }
  743. func (s *SettingService) GetSubEnableRouting() (bool, error) {
  744. return s.getBool("subEnableRouting")
  745. }
  746. func (s *SettingService) GetSubRoutingRules() (string, error) {
  747. return s.getString("subRoutingRules")
  748. }
  749. func (s *SettingService) GetSubHideSettings() (bool, error) {
  750. return s.getBool("subHideSettings")
  751. }
  752. func (s *SettingService) GetSubHappAutoDetect() (bool, error) {
  753. return s.getBool("subHappAutoDetect")
  754. }
  755. func (s *SettingService) GetSubHappProviderId() (string, error) {
  756. return s.getString("subHappProviderId")
  757. }
  758. func (s *SettingService) GetSubHappNewUrl() (string, error) {
  759. return s.getString("subHappNewUrl")
  760. }
  761. func (s *SettingService) GetSubHappFallbackUrl() (string, error) {
  762. return s.getString("subHappFallbackUrl")
  763. }
  764. func (s *SettingService) GetSubHappSubInfoColor() (string, error) {
  765. return s.getString("subHappSubInfoColor")
  766. }
  767. func (s *SettingService) GetSubHappSubInfoText() (string, error) {
  768. return s.getString("subHappSubInfoText")
  769. }
  770. func (s *SettingService) GetSubHappSubInfoButtonText() (string, error) {
  771. return s.getString("subHappSubInfoButtonText")
  772. }
  773. func (s *SettingService) GetSubHappSubInfoButtonLink() (string, error) {
  774. return s.getString("subHappSubInfoButtonLink")
  775. }
  776. func (s *SettingService) GetSubHappSubExpire() (bool, error) {
  777. return s.getBool("subHappSubExpire")
  778. }
  779. func (s *SettingService) GetSubHappSubExpireButtonLink() (string, error) {
  780. return s.getString("subHappSubExpireButtonLink")
  781. }
  782. func (s *SettingService) GetSubHappNotificationExpire() (bool, error) {
  783. return s.getBool("subHappNotificationExpire")
  784. }
  785. func (s *SettingService) GetSubHappNoLimit() (bool, error) {
  786. return s.getBool("subHappNoLimit")
  787. }
  788. func (s *SettingService) GetSubHappAlwaysHwid() (bool, error) {
  789. return s.getBool("subHappAlwaysHwid")
  790. }
  791. func (s *SettingService) GetSubHappTunMode() (string, error) {
  792. return s.getString("subHappTunMode")
  793. }
  794. func (s *SettingService) GetSubHappTunType() (string, error) {
  795. return s.getString("subHappTunType")
  796. }
  797. func (s *SettingService) GetSubHappExcludeRoutes() (string, error) {
  798. return s.getString("subHappExcludeRoutes")
  799. }
  800. func (s *SettingService) GetSubHappExcludeApns() (bool, error) {
  801. return s.getBool("subHappExcludeApns")
  802. }
  803. func (s *SettingService) GetSubHappColorProfile() (string, error) {
  804. return s.getString("subHappColorProfile")
  805. }
  806. func (s *SettingService) GetSubHappPingType() (string, error) {
  807. return s.getString("subHappPingType")
  808. }
  809. func (s *SettingService) GetSubHappAutoConnect() (bool, error) {
  810. return s.getBool("subHappAutoConnect")
  811. }
  812. func (s *SettingService) GetSubHappAutoConnectType() (string, error) {
  813. return s.getString("subHappAutoConnectType")
  814. }
  815. func (s *SettingService) GetSubHappPerAppMode() (string, error) {
  816. return s.getString("subHappPerAppMode")
  817. }
  818. func (s *SettingService) GetSubHappPerAppList() (string, error) {
  819. return s.getString("subHappPerAppList")
  820. }
  821. func (s *SettingService) GetSubIncyEnableRouting() (bool, error) {
  822. return s.getBool("subIncyEnableRouting")
  823. }
  824. func (s *SettingService) GetSubIncyRoutingRules() (string, error) {
  825. return s.getString("subIncyRoutingRules")
  826. }
  827. func (s *SettingService) GetSubListen() (string, error) {
  828. return s.getString("subListen")
  829. }
  830. func (s *SettingService) GetSubPort() (int, error) {
  831. return s.getInt("subPort")
  832. }
  833. func (s *SettingService) GetSubPath() (string, error) {
  834. return s.getString("subPath")
  835. }
  836. func (s *SettingService) GetSubJsonPath() (string, error) {
  837. return s.getString("subJsonPath")
  838. }
  839. func (s *SettingService) GetSubDomain() (string, error) {
  840. return s.getString("subDomain")
  841. }
  842. func (s *SettingService) SetSubCertFile(subCertFile string) error {
  843. return s.setString("subCertFile", subCertFile)
  844. }
  845. func (s *SettingService) GetSubCertFile() (string, error) {
  846. return s.getString("subCertFile")
  847. }
  848. func (s *SettingService) SetSubKeyFile(subKeyFile string) error {
  849. return s.setString("subKeyFile", subKeyFile)
  850. }
  851. func (s *SettingService) GetSubKeyFile() (string, error) {
  852. return s.getString("subKeyFile")
  853. }
  854. func (s *SettingService) GetSubUpdates() (string, error) {
  855. return s.getString("subUpdates")
  856. }
  857. func (s *SettingService) GetSubEncrypt() (bool, error) {
  858. return s.getBool("subEncrypt")
  859. }
  860. func (s *SettingService) GetPageSize() (int, error) {
  861. return s.getInt("pageSize")
  862. }
  863. func (s *SettingService) GetSubURI() (string, error) {
  864. return s.getString("subURI")
  865. }
  866. func (s *SettingService) GetSubJsonURI() (string, error) {
  867. return s.getString("subJsonURI")
  868. }
  869. func (s *SettingService) GetSubClashEnable() (bool, error) {
  870. return s.getBool("subClashEnable")
  871. }
  872. func (s *SettingService) GetSubClashPath() (string, error) {
  873. return s.getString("subClashPath")
  874. }
  875. func (s *SettingService) GetSubClashURI() (string, error) {
  876. return s.getString("subClashURI")
  877. }
  878. func (s *SettingService) GetSubClashEnableRouting() (bool, error) {
  879. return s.getBool("subClashEnableRouting")
  880. }
  881. func (s *SettingService) GetSubClashRules() (string, error) {
  882. return s.getString("subClashRules")
  883. }
  884. func (s *SettingService) GetSubJsonMux() (string, error) {
  885. return s.getString("subJsonMux")
  886. }
  887. func (s *SettingService) GetSubJsonRules() (string, error) {
  888. return s.getString("subJsonRules")
  889. }
  890. func (s *SettingService) GetSubJsonRoutingRules() (string, error) {
  891. return s.getString("subJsonRoutingRules")
  892. }
  893. func (s *SettingService) GetSubJsonDns() (string, error) {
  894. return s.getString("subJsonDns")
  895. }
  896. func (s *SettingService) GetSubJsonFinalMask() (string, error) {
  897. return s.getString("subJsonFinalMask")
  898. }
  899. func (s *SettingService) GetSubJsonObservatory() (string, error) {
  900. return s.getString("subJsonObservatory")
  901. }
  902. func (s *SettingService) GetSubThemeDir() (string, error) {
  903. return s.getString("subThemeDir")
  904. }
  905. func (s *SettingService) GetDatepicker() (string, error) {
  906. return s.getString("datepicker")
  907. }
  908. func (s *SettingService) GetWarp() (string, error) {
  909. return s.getString("warp")
  910. }
  911. func (s *SettingService) SetWarp(data string) error {
  912. return s.setString("warp", data)
  913. }
  914. func (s *SettingService) GetNord() (string, error) {
  915. return s.getString("nord")
  916. }
  917. func (s *SettingService) SetNord(data string) error {
  918. return s.setString("nord", data)
  919. }
  920. func (s *SettingService) GetPia() (string, error) {
  921. return s.getString("pia")
  922. }
  923. func (s *SettingService) SetPia(data string) error {
  924. return s.setString("pia", data)
  925. }
  926. func (s *SettingService) GetExternalTrafficInformEnable() (bool, error) {
  927. return s.getBool("externalTrafficInformEnable")
  928. }
  929. func (s *SettingService) SetExternalTrafficInformEnable(value bool) error {
  930. return s.setBool("externalTrafficInformEnable", value)
  931. }
  932. func (s *SettingService) GetExternalTrafficInformURI() (string, error) {
  933. return s.getString("externalTrafficInformURI")
  934. }
  935. func (s *SettingService) SetExternalTrafficInformURI(InformURI string) error {
  936. return s.setString("externalTrafficInformURI", InformURI)
  937. }
  938. func (s *SettingService) GetRestartXrayOnClientDisable() (bool, error) {
  939. return s.getBool("restartXrayOnClientDisable")
  940. }
  941. func (s *SettingService) SetRestartXrayOnClientDisable(value bool) error {
  942. return s.setBool("restartXrayOnClientDisable", value)
  943. }
  944. // GetDevChannelEnable reports whether the panel self-update tracks the rolling
  945. // per-commit dev release instead of the latest stable tag.
  946. func (s *SettingService) GetDevChannelEnable() (bool, error) {
  947. return s.getBool("devChannelEnable")
  948. }
  949. func (s *SettingService) SetDevChannelEnable(value bool) error {
  950. return s.setBool("devChannelEnable", value)
  951. }
  952. // GetIpLimitEnable reports whether the IP-limit feature is available. Always
  953. // true since the panel enforces limits via the core's online-stats API; on an
  954. // older core the job falls back to access-log parsing and warns there when the
  955. // log is missing, so the UI no longer hides the field behind that condition.
  956. func (s *SettingService) GetIpLimitEnable() (bool, error) {
  957. return true, nil
  958. }
  959. // GetAccessLogEnable reports whether an Xray access log is configured. Used by
  960. // the UI for features that genuinely read the log file (the xray log viewer) —
  961. // distinct from IP limiting, which works without it.
  962. func (s *SettingService) GetAccessLogEnable() (bool, error) {
  963. accessLogPath, err := xray.GetAccessLogPath()
  964. if err != nil {
  965. return false, err
  966. }
  967. return (accessLogPath != "none" && accessLogPath != ""), nil
  968. }
  969. // GetLdapEnable returns whether LDAP is enabled.
  970. func (s *SettingService) GetLdapEnable() (bool, error) {
  971. return s.getBool("ldapEnable")
  972. }
  973. func (s *SettingService) GetLdapHost() (string, error) {
  974. return s.getString("ldapHost")
  975. }
  976. func (s *SettingService) GetLdapPort() (int, error) {
  977. return s.getInt("ldapPort")
  978. }
  979. func (s *SettingService) GetLdapUseTLS() (bool, error) {
  980. return s.getBool("ldapUseTLS")
  981. }
  982. func (s *SettingService) GetLdapInsecureSkipVerify() (bool, error) {
  983. return s.getBool("ldapInsecureSkipVerify")
  984. }
  985. func (s *SettingService) GetLdapBindDN() (string, error) {
  986. return s.getString("ldapBindDN")
  987. }
  988. func (s *SettingService) GetLdapPassword() (string, error) {
  989. return s.getString("ldapPassword")
  990. }
  991. func (s *SettingService) GetLdapBaseDN() (string, error) {
  992. return s.getString("ldapBaseDN")
  993. }
  994. func (s *SettingService) GetLdapUserFilter() (string, error) {
  995. return s.getString("ldapUserFilter")
  996. }
  997. func (s *SettingService) GetLdapUserAttr() (string, error) {
  998. return s.getString("ldapUserAttr")
  999. }
  1000. func (s *SettingService) GetLdapVlessField() (string, error) {
  1001. return s.getString("ldapVlessField")
  1002. }
  1003. func (s *SettingService) GetLdapSyncCron() (string, error) {
  1004. return s.getString("ldapSyncCron")
  1005. }
  1006. func (s *SettingService) GetLdapFlagField() (string, error) {
  1007. return s.getString("ldapFlagField")
  1008. }
  1009. func (s *SettingService) GetLdapTruthyValues() (string, error) {
  1010. return s.getString("ldapTruthyValues")
  1011. }
  1012. func (s *SettingService) GetLdapInvertFlag() (bool, error) {
  1013. return s.getBool("ldapInvertFlag")
  1014. }
  1015. func (s *SettingService) GetLdapInboundTags() (string, error) {
  1016. return s.getString("ldapInboundTags")
  1017. }
  1018. func (s *SettingService) GetLdapAutoCreate() (bool, error) {
  1019. return s.getBool("ldapAutoCreate")
  1020. }
  1021. func (s *SettingService) GetLdapAutoDelete() (bool, error) {
  1022. return s.getBool("ldapAutoDelete")
  1023. }
  1024. func (s *SettingService) GetLdapDefaultTotalGB() (int, error) {
  1025. return s.getInt("ldapDefaultTotalGB")
  1026. }
  1027. func (s *SettingService) GetLdapDefaultExpiryDays() (int, error) {
  1028. return s.getInt("ldapDefaultExpiryDays")
  1029. }
  1030. func (s *SettingService) GetLdapDefaultLimitIP() (int, error) {
  1031. return s.getInt("ldapDefaultLimitIP")
  1032. }
  1033. // Event bus — per-subscriber event filtering
  1034. func (s *SettingService) GetTgEnabledEvents() (string, error) {
  1035. return s.getString("tgEnabledEvents")
  1036. }
  1037. func (s *SettingService) SetTgEnabledEvents(events string) error {
  1038. return s.setString("tgEnabledEvents", events)
  1039. }
  1040. func (s *SettingService) GetSmtpEnabledEvents() (string, error) {
  1041. return s.getString("smtpEnabledEvents")
  1042. }
  1043. func (s *SettingService) SetSmtpEnabledEvents(events string) error {
  1044. return s.setString("smtpEnabledEvents", events)
  1045. }
  1046. // Email (SMTP) settings
  1047. func (s *SettingService) GetSmtpEnable() (bool, error) {
  1048. return s.getBool("smtpEnable")
  1049. }
  1050. func (s *SettingService) SetSmtpEnable(value bool) error {
  1051. return s.setBool("smtpEnable", value)
  1052. }
  1053. func (s *SettingService) GetSmtpHost() (string, error) {
  1054. return s.getString("smtpHost")
  1055. }
  1056. func (s *SettingService) SetSmtpHost(value string) error {
  1057. return s.setString("smtpHost", value)
  1058. }
  1059. func (s *SettingService) GetSmtpPort() (int, error) {
  1060. return s.getInt("smtpPort")
  1061. }
  1062. func (s *SettingService) SetSmtpPort(value int) error {
  1063. return s.setInt("smtpPort", value)
  1064. }
  1065. func (s *SettingService) GetSmtpUsername() (string, error) {
  1066. return s.getString("smtpUsername")
  1067. }
  1068. func (s *SettingService) SetSmtpUsername(value string) error {
  1069. return s.setString("smtpUsername", value)
  1070. }
  1071. func (s *SettingService) GetSmtpFrom() (string, error) {
  1072. return s.getString("smtpFrom")
  1073. }
  1074. func (s *SettingService) SetSmtpFrom(value string) error {
  1075. return s.setString("smtpFrom", value)
  1076. }
  1077. func (s *SettingService) GetSmtpFromName() (string, error) {
  1078. return s.getString("smtpFromName")
  1079. }
  1080. func (s *SettingService) SetSmtpFromName(value string) error {
  1081. return s.setString("smtpFromName", value)
  1082. }
  1083. func (s *SettingService) GetSmtpPassword() (string, error) {
  1084. return s.getString("smtpPassword")
  1085. }
  1086. func (s *SettingService) SetSmtpPassword(value string) error {
  1087. return s.setString("smtpPassword", value)
  1088. }
  1089. func (s *SettingService) GetSmtpTo() (string, error) {
  1090. return s.getString("smtpTo")
  1091. }
  1092. func (s *SettingService) SetSmtpTo(value string) error {
  1093. return s.setString("smtpTo", value)
  1094. }
  1095. func (s *SettingService) GetSmtpEncryptionType() (string, error) {
  1096. return s.getString("smtpEncryptionType")
  1097. }
  1098. func (s *SettingService) SetSmtpEncryptionType(value string) error {
  1099. return s.setString("smtpEncryptionType", value)
  1100. }
  1101. func (s *SettingService) GetSmtpCpu() (int, error) {
  1102. return s.getInt("smtpCpu")
  1103. }
  1104. func (s *SettingService) SetSmtpCpu(value int) error {
  1105. return s.setInt("smtpCpu", value)
  1106. }
  1107. func (s *SettingService) GetSmtpMemory() (int, error) {
  1108. return s.getInt("smtpMemory")
  1109. }
  1110. func (s *SettingService) SetSmtpMemory(value int) error {
  1111. return s.setInt("smtpMemory", value)
  1112. }
  1113. // Discord bot settings
  1114. func (s *SettingService) GetDiscordBotEnable() (bool, error) {
  1115. return s.getBool("discordBotEnable")
  1116. }
  1117. func (s *SettingService) SetDiscordBotEnable(value bool) error {
  1118. return s.setBool("discordBotEnable", value)
  1119. }
  1120. func (s *SettingService) GetDiscordBotToken() (string, error) {
  1121. return s.getString("discordBotToken")
  1122. }
  1123. func (s *SettingService) SetDiscordBotToken(value string) error {
  1124. return s.setString("discordBotToken", value)
  1125. }
  1126. func (s *SettingService) GetDiscordChannelId() (string, error) {
  1127. return s.getString("discordChannelId")
  1128. }
  1129. func (s *SettingService) SetDiscordChannelId(value string) error {
  1130. return s.setString("discordChannelId", value)
  1131. }
  1132. func (s *SettingService) GetDiscordAdminIds() (string, error) {
  1133. return s.getString("discordAdminIds")
  1134. }
  1135. func (s *SettingService) SetDiscordAdminIds(value string) error {
  1136. return s.setString("discordAdminIds", value)
  1137. }
  1138. func (s *SettingService) GetDiscordEnabledEvents() (string, error) {
  1139. return s.getString("discordEnabledEvents")
  1140. }
  1141. func (s *SettingService) SetDiscordEnabledEvents(events string) error {
  1142. return s.setString("discordEnabledEvents", events)
  1143. }
  1144. func (s *SettingService) GetDiscordCpu() (int, error) {
  1145. return s.getInt("discordCpu")
  1146. }
  1147. func (s *SettingService) SetDiscordCpu(value int) error {
  1148. return s.setInt("discordCpu", value)
  1149. }
  1150. func (s *SettingService) GetDiscordMemory() (int, error) {
  1151. return s.getInt("discordMemory")
  1152. }
  1153. func (s *SettingService) SetDiscordMemory(value int) error {
  1154. return s.setInt("discordMemory", value)
  1155. }
  1156. func (s *SettingService) GetDiscordRunTime() (string, error) {
  1157. return s.getString("discordRunTime")
  1158. }
  1159. func (s *SettingService) SetDiscordRunTime(value string) error {
  1160. return s.setString("discordRunTime", value)
  1161. }
  1162. func (s *SettingService) GetDiscordBotBackup() (bool, error) {
  1163. return s.getBool("discordBotBackup")
  1164. }
  1165. func (s *SettingService) SetDiscordBotBackup(value bool) error {
  1166. return s.setBool("discordBotBackup", value)
  1167. }
  1168. func (s *SettingService) GetDiscordLang() (string, error) {
  1169. return s.getString("discordLang")
  1170. }
  1171. func (s *SettingService) SetDiscordLang(value string) error {
  1172. return s.setString("discordLang", value)
  1173. }
  1174. // GetOutboundDownThreshold returns how many consecutive failed observatory
  1175. // probes an outbound must accumulate before an outbound.down notification is
  1176. // emitted. 1 preserves the legacy "notify on the first failed probe" behaviour.
  1177. func (s *SettingService) GetOutboundDownThreshold() (int, error) {
  1178. return s.getInt("outboundDownThreshold")
  1179. }
  1180. func (s *SettingService) SetOutboundDownThreshold(value int) error {
  1181. return s.setInt("outboundDownThreshold", value)
  1182. }
  1183. // SecretClears marks redacted secrets the user explicitly emptied. Without a
  1184. // flag, a blank submitted secret means "unchanged" (the field is always served
  1185. // blank to the browser) and the stored value is preserved.
  1186. type SecretClears struct {
  1187. TgBotToken bool
  1188. LdapPassword bool
  1189. SmtpPassword bool
  1190. DiscordBotToken bool
  1191. }
  1192. func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting, clears SecretClears) error {
  1193. if err := s.preserveRedactedSecrets(allSetting, clears); err != nil {
  1194. return err
  1195. }
  1196. if err := validateSettingsURLs(allSetting); err != nil {
  1197. return err
  1198. }
  1199. if err := validateSubUserAgentRegexes(allSetting); err != nil {
  1200. return err
  1201. }
  1202. if err := validateSubJsonDnsSetting(allSetting); err != nil {
  1203. return err
  1204. }
  1205. if err := allSetting.CheckValid(); err != nil {
  1206. return err
  1207. }
  1208. v := reflect.ValueOf(allSetting).Elem()
  1209. t := reflect.TypeFor[entity.AllSetting]()
  1210. fields := reflect_util.GetFields(t)
  1211. db := database.GetDB()
  1212. return db.Transaction(func(tx *gorm.DB) error {
  1213. var existing []*model.Setting
  1214. if err := tx.Find(&existing).Error; err != nil {
  1215. return err
  1216. }
  1217. byKey := make(map[string]*model.Setting, len(existing))
  1218. for _, st := range existing {
  1219. byKey[st.Key] = st
  1220. }
  1221. for _, field := range fields {
  1222. key := field.Tag.Get("json")
  1223. fieldV := v.FieldByName(field.Name)
  1224. value := fmt.Sprint(fieldV.Interface())
  1225. if st, ok := byKey[key]; ok {
  1226. if st.Value == value {
  1227. continue
  1228. }
  1229. st.Value = value
  1230. if err := tx.Save(st).Error; err != nil {
  1231. return err
  1232. }
  1233. continue
  1234. }
  1235. if err := tx.Create(&model.Setting{Key: key, Value: value}).Error; err != nil {
  1236. return err
  1237. }
  1238. }
  1239. return nil
  1240. })
  1241. }
  1242. func validateSubUserAgentRegexes(allSetting *entity.AllSetting) error {
  1243. jsonPattern, err := validateSubUserAgentRegex("Xray JSON", allSetting.SubJsonUserAgentRegex, DefaultSubJsonUserAgentRegex)
  1244. if err != nil {
  1245. return err
  1246. }
  1247. clashPattern, err := validateSubUserAgentRegex("Clash/Mihomo", allSetting.SubClashUserAgentRegex, DefaultSubClashUserAgentRegex)
  1248. if err != nil {
  1249. return err
  1250. }
  1251. allSetting.SubJsonUserAgentRegex = jsonPattern
  1252. allSetting.SubClashUserAgentRegex = clashPattern
  1253. return nil
  1254. }
  1255. func validateSubUserAgentRegex(name, pattern, defaultPattern string) (string, error) {
  1256. pattern = strings.TrimSpace(pattern)
  1257. effectivePattern := pattern
  1258. if effectivePattern == "" {
  1259. effectivePattern = defaultPattern
  1260. }
  1261. if len(effectivePattern) > maxRegexLength {
  1262. return "", common.NewErrorf("%s User-Agent regex must not exceed %d characters", name, maxRegexLength)
  1263. }
  1264. if _, err := regexp.Compile(effectivePattern); err != nil {
  1265. return "", common.NewErrorf("%s User-Agent regex is invalid: %v", name, err)
  1266. }
  1267. // Return the original pattern (empty string if cleared) so the caller
  1268. // can distinguish "user explicitly set empty" from "user set a value".
  1269. // The empty value is stored in the DB and inherited as runtime default.
  1270. return pattern, nil
  1271. }
  1272. func ValidateRegex(pattern string) error {
  1273. if len(pattern) > maxRegexLength {
  1274. return common.NewErrorf("Regular expression must not exceed %d characters", maxRegexLength)
  1275. }
  1276. if _, err := regexp.Compile(pattern); err != nil {
  1277. return common.NewError("Regular expression is invalid:", err)
  1278. }
  1279. return nil
  1280. }
  1281. func (s *SettingService) preserveRedactedSecrets(allSetting *entity.AllSetting, clears SecretClears) error {
  1282. if !clears.TgBotToken && strings.TrimSpace(allSetting.TgBotToken) == "" {
  1283. value, err := s.GetTgBotToken()
  1284. if err != nil {
  1285. return err
  1286. }
  1287. allSetting.TgBotToken = value
  1288. }
  1289. if !clears.LdapPassword && strings.TrimSpace(allSetting.LdapPassword) == "" {
  1290. value, err := s.GetLdapPassword()
  1291. if err != nil {
  1292. return err
  1293. }
  1294. allSetting.LdapPassword = value
  1295. }
  1296. if allSetting.TwoFactorEnable && strings.TrimSpace(allSetting.TwoFactorToken) == "" {
  1297. value, err := s.GetTwoFactorToken()
  1298. if err != nil {
  1299. return err
  1300. }
  1301. allSetting.TwoFactorToken = value
  1302. }
  1303. if !clears.SmtpPassword && strings.TrimSpace(allSetting.SmtpPassword) == "" {
  1304. value, err := s.GetSmtpPassword()
  1305. if err != nil {
  1306. return err
  1307. }
  1308. allSetting.SmtpPassword = value
  1309. }
  1310. if !clears.DiscordBotToken && strings.TrimSpace(allSetting.DiscordBotToken) == "" {
  1311. value, err := s.GetDiscordBotToken()
  1312. if err != nil {
  1313. return err
  1314. }
  1315. allSetting.DiscordBotToken = value
  1316. }
  1317. return nil
  1318. }
  1319. func validateSettingsURLs(allSetting *entity.AllSetting) error {
  1320. if allSetting.ExternalTrafficInformURI != "" {
  1321. u, err := SanitizeHTTPURL(allSetting.ExternalTrafficInformURI)
  1322. if err != nil {
  1323. return common.NewError("external traffic inform URI is invalid:", err)
  1324. }
  1325. allSetting.ExternalTrafficInformURI = u
  1326. }
  1327. if allSetting.TgBotAPIServer != "" {
  1328. u, err := SanitizeHTTPURL(allSetting.TgBotAPIServer)
  1329. if err != nil {
  1330. return common.NewError("telegram API server URL is invalid:", err)
  1331. }
  1332. allSetting.TgBotAPIServer = u
  1333. }
  1334. // Support/profile links land in subscription headers and page data, where
  1335. // client apps resolve a scheme-less value against the panel's own domain.
  1336. // Non-http schemes (tg://, mailto:) are legitimate here, so only default
  1337. // the scheme instead of forcing SanitizeHTTPURL's http(s)-only rule.
  1338. allSetting.SubSupportUrl = common.EnsureURLScheme(allSetting.SubSupportUrl)
  1339. allSetting.SubProfileUrl = common.EnsureURLScheme(allSetting.SubProfileUrl)
  1340. for _, ptr := range []*string{
  1341. &allSetting.SubHappNewUrl,
  1342. &allSetting.SubHappFallbackUrl,
  1343. &allSetting.SubHappSubInfoButtonLink,
  1344. &allSetting.SubHappSubExpireButtonLink,
  1345. } {
  1346. if strings.TrimSpace(*ptr) != "" {
  1347. *ptr = common.EnsureURLScheme(strings.TrimSpace(*ptr))
  1348. }
  1349. }
  1350. for name, value := range map[string]*string{
  1351. "Happ routing source": &allSetting.SubRoutingRules,
  1352. "Clash/Mihomo routing source": &allSetting.SubClashRules,
  1353. "Incy routing source": &allSetting.SubIncyRoutingRules,
  1354. "JSON subscription routing source": &allSetting.SubJsonRoutingRules,
  1355. } {
  1356. if err := validateRemoteRoutingURLSetting(name, value); err != nil {
  1357. return err
  1358. }
  1359. }
  1360. return nil
  1361. }
  1362. func validateRemoteRoutingURLSetting(name string, value *string) error {
  1363. canonical, remote, err := common.ParseRemoteRoutingURL(*value)
  1364. if err != nil {
  1365. return common.NewError(name, err.Error())
  1366. }
  1367. if remote {
  1368. *value = canonical
  1369. }
  1370. return nil
  1371. }
  1372. // The same parser the sub server uses, so a value can never be saved as valid
  1373. // and then silently ignored at request time.
  1374. func validateSubJsonDnsSetting(allSetting *entity.AllSetting) error {
  1375. value := strings.TrimSpace(allSetting.SubJsonDns)
  1376. if value != "" {
  1377. if _, err := dnsconf.Parse(value); err != nil {
  1378. return common.NewError("JSON subscription DNS is invalid:", err.Error())
  1379. }
  1380. }
  1381. allSetting.SubJsonDns = value
  1382. return nil
  1383. }
  1384. func (s *SettingService) UpdateSecret(key string, value string) error {
  1385. switch key {
  1386. case "tgBotToken", "ldapPassword", "twoFactorToken":
  1387. return s.saveSetting(key, strings.TrimSpace(value))
  1388. default:
  1389. return common.NewError("secret key is not replaceable:", key)
  1390. }
  1391. }
  1392. func (s *SettingService) GetDefaultXrayConfig() (any, error) {
  1393. var jsonData any
  1394. err := json.Unmarshal([]byte(xrayTemplateConfig), &jsonData)
  1395. if err != nil {
  1396. return nil, err
  1397. }
  1398. return jsonData, nil
  1399. }
  1400. func extractHostname(host string) string {
  1401. h, _, err := net.SplitHostPort(host)
  1402. // Err is not nil means host does not contain port
  1403. if err != nil {
  1404. h = host
  1405. }
  1406. ip := net.ParseIP(h)
  1407. // If it's not an IP, return as is
  1408. if ip == nil {
  1409. return h
  1410. }
  1411. // If it's an IPv4, return as is
  1412. if ip.To4() != nil {
  1413. return h
  1414. }
  1415. // IPv6 needs bracketing
  1416. return "[" + h + "]"
  1417. }
  1418. // BuildSubURIBase is shared by GetDefaultSettings (the panel's Client
  1419. // Information page) and the subscription page so both render subscription
  1420. // URLs identically.
  1421. func (s *SettingService) BuildSubURIBase(host string) string {
  1422. subPort, _ := s.GetSubPort()
  1423. subDomain, _ := s.GetSubDomain()
  1424. subKeyFile, _ := s.GetSubKeyFile()
  1425. subCertFile, _ := s.GetSubCertFile()
  1426. subTLS := subKeyFile != "" && subCertFile != ""
  1427. if subDomain == "" {
  1428. subDomain = extractHostname(host)
  1429. }
  1430. scheme := "http"
  1431. if subTLS {
  1432. scheme = "https"
  1433. }
  1434. if (subPort == 443 && subTLS) || (subPort == 80 && !subTLS) {
  1435. return scheme + "://" + subDomain
  1436. }
  1437. return fmt.Sprintf("%s://%s:%d", scheme, subDomain, subPort)
  1438. }
  1439. func (s *SettingService) GetDefaultSettings(host string) (any, error) {
  1440. type settingFunc func() (any, error)
  1441. settings := map[string]settingFunc{
  1442. "expireDiff": func() (any, error) { return s.GetExpireDiff() },
  1443. "trafficDiff": func() (any, error) { return s.GetTrafficDiff() },
  1444. "pageSize": func() (any, error) { return s.GetPageSize() },
  1445. "defaultCert": func() (any, error) { return s.GetCertFile() },
  1446. "defaultKey": func() (any, error) { return s.GetKeyFile() },
  1447. "tgBotEnable": func() (any, error) { return s.GetTgbotEnabled() },
  1448. "subThemeDir": func() (any, error) { return s.GetSubThemeDir() },
  1449. "happLinkEnable": func() (any, error) { return s.GetHappLinkEnable() },
  1450. "subEnable": func() (any, error) { return s.GetSubEnable() },
  1451. "subJsonEnable": func() (any, error) { return s.GetSubJsonEnable() },
  1452. "subClashEnable": func() (any, error) { return s.GetSubClashEnable() },
  1453. "subTitle": func() (any, error) { return s.GetSubTitle() },
  1454. "subURI": func() (any, error) { return s.GetSubURI() },
  1455. "subJsonURI": func() (any, error) { return s.GetSubJsonURI() },
  1456. "subClashURI": func() (any, error) { return s.GetSubClashURI() },
  1457. "datepicker": func() (any, error) { return s.GetDatepicker() },
  1458. "ipLimitEnable": func() (any, error) { return s.GetIpLimitEnable() },
  1459. "accessLogEnable": func() (any, error) { return s.GetAccessLogEnable() },
  1460. "webDomain": func() (any, error) { return s.GetWebDomain() },
  1461. "subDomain": func() (any, error) { return s.GetSubDomain() },
  1462. "devChannelEnable": func() (any, error) { return s.GetDevChannelEnable() },
  1463. "isDevBuild": func() (any, error) { return config.IsDevBuild(), nil },
  1464. }
  1465. result := make(map[string]any)
  1466. for key, fn := range settings {
  1467. value, err := fn()
  1468. if err != nil {
  1469. return "", err
  1470. }
  1471. result[key] = value
  1472. }
  1473. subEnable := result["subEnable"].(bool)
  1474. subJsonEnable := false
  1475. if v, ok := result["subJsonEnable"]; ok {
  1476. if b, ok2 := v.(bool); ok2 {
  1477. subJsonEnable = b
  1478. }
  1479. }
  1480. subClashEnable := false
  1481. if v, ok := result["subClashEnable"]; ok {
  1482. if b, ok2 := v.(bool); ok2 {
  1483. subClashEnable = b
  1484. }
  1485. }
  1486. if (subEnable && result["subURI"].(string) == "") || (subJsonEnable && result["subJsonURI"].(string) == "") || (subClashEnable && result["subClashURI"].(string) == "") {
  1487. subURI := s.BuildSubURIBase(host)
  1488. subTitle, _ := s.GetSubTitle()
  1489. subPath, _ := s.GetSubPath()
  1490. subJsonPath, _ := s.GetSubJsonPath()
  1491. subClashPath, _ := s.GetSubClashPath()
  1492. if subEnable && result["subURI"].(string) == "" {
  1493. result["subURI"] = subURI + subPath
  1494. }
  1495. if result["subTitle"].(string) == "" {
  1496. result["subTitle"] = subTitle
  1497. }
  1498. if subJsonEnable && result["subJsonURI"].(string) == "" {
  1499. result["subJsonURI"] = subURI + subJsonPath
  1500. }
  1501. if subClashEnable && result["subClashURI"].(string) == "" {
  1502. result["subClashURI"] = subURI + subClashPath
  1503. }
  1504. }
  1505. return result, nil
  1506. }
  1507. var factoryDefaultSecretKeys = map[string]bool{
  1508. "tgBotToken": true,
  1509. "twoFactorToken": true,
  1510. "ldapPassword": true,
  1511. "smtpPassword": true,
  1512. "discordBotToken": true,
  1513. }
  1514. /*
  1515. GetFactoryDefaults returns the shipped default value per setting, keyed by
  1516. the AllSetting json field name. Unlike GetDefaultSettings (which reports
  1517. current effective values), this is defaultValueMap projected through the
  1518. AllSetting field set: only keys that exist as an AllSetting json tag are
  1519. returned, minus the credential fields in factoryDefaultSecretKeys. Keys
  1520. with no AllSetting field (secret, panelGuid, the node mTLS material,
  1521. xrayTemplateConfig) are excluded structurally rather than by deny-list.
  1522. */
  1523. func (s *SettingService) GetFactoryDefaults() map[string]string {
  1524. result := make(map[string]string)
  1525. for _, field := range reflect_util.GetFields(reflect.TypeFor[entity.AllSetting]()) {
  1526. key := field.Tag.Get("json")
  1527. if key == "" || factoryDefaultSecretKeys[key] {
  1528. continue
  1529. }
  1530. if value, ok := defaultValueMap[key]; ok {
  1531. result[key] = value
  1532. }
  1533. }
  1534. return result
  1535. }