setting.go 48 KB

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