setting.go 49 KB

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