setting.go 49 KB

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