setting.go 52 KB

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