1
0

setting.go 48 KB

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