1
0

entity.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. package entity
  2. import (
  3. "crypto/tls"
  4. "math"
  5. "net"
  6. "net/mail"
  7. "net/netip"
  8. "strings"
  9. "time"
  10. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  11. )
  12. type Msg struct {
  13. Success bool `json:"success"`
  14. Msg string `json:"msg"`
  15. Obj any `json:"obj"`
  16. }
  17. type AllSetting struct {
  18. WebListen string `json:"webListen" form:"webListen"`
  19. WebDomain string `json:"webDomain" form:"webDomain"`
  20. WebPort int `json:"webPort" form:"webPort" validate:"gte=1,lte=65535"`
  21. WebCertFile string `json:"webCertFile" form:"webCertFile"`
  22. WebKeyFile string `json:"webKeyFile" form:"webKeyFile"`
  23. WebBasePath string `json:"webBasePath" form:"webBasePath"`
  24. SessionMaxAge int `json:"sessionMaxAge" form:"sessionMaxAge" validate:"gte=1,lte=525600"`
  25. TrustedProxyCIDRs string `json:"trustedProxyCIDRs" form:"trustedProxyCIDRs"`
  26. IpLimitAllowlist string `json:"ipLimitAllowlist" form:"ipLimitAllowlist"`
  27. PanelOutbound string `json:"panelOutbound" form:"panelOutbound"`
  28. PageSize int `json:"pageSize" form:"pageSize" validate:"gte=0,lte=1000"`
  29. ExpireDiff int `json:"expireDiff" form:"expireDiff" validate:"gte=0"`
  30. TrafficDiff int `json:"trafficDiff" form:"trafficDiff" validate:"gte=0,lte=100"`
  31. RemarkTemplate string `json:"remarkTemplate" form:"remarkTemplate"`
  32. SubShowIdentityOnAllLinks bool `json:"subShowIdentityOnAllLinks" form:"subShowIdentityOnAllLinks"`
  33. SubInfoNodeEnable bool `json:"subInfoNodeEnable" form:"subInfoNodeEnable"`
  34. SubExpiredTemplate string `json:"subExpiredTemplate" form:"subExpiredTemplate"`
  35. SubTrafficDepletedTemplate string `json:"subTrafficDepletedTemplate" form:"subTrafficDepletedTemplate"`
  36. Datepicker string `json:"datepicker" form:"datepicker"`
  37. TgBotEnable bool `json:"tgBotEnable" form:"tgBotEnable"`
  38. TgBotToken string `json:"tgBotToken" form:"tgBotToken"`
  39. TgBotProxy string `json:"tgBotProxy" form:"tgBotProxy"`
  40. TgBotAPIServer string `json:"tgBotAPIServer" form:"tgBotAPIServer"`
  41. TgBotChatId string `json:"tgBotChatId" form:"tgBotChatId"`
  42. TgRunTime string `json:"tgRunTime" form:"tgRunTime"`
  43. TgBotBackup bool `json:"tgBotBackup" form:"tgBotBackup"`
  44. TgCpu int `json:"tgCpu" form:"tgCpu" validate:"gte=0,lte=100"`
  45. TgMemory int `json:"tgMemory" form:"tgMemory" validate:"gte=0,lte=100"`
  46. TgLang string `json:"tgLang" form:"tgLang"`
  47. TgEnabledEvents string `json:"tgEnabledEvents" form:"tgEnabledEvents"`
  48. SmtpEnable bool `json:"smtpEnable" form:"smtpEnable"`
  49. SmtpHost string `json:"smtpHost" form:"smtpHost"`
  50. SmtpPort int `json:"smtpPort" form:"smtpPort" validate:"gte=1,lte=65535"`
  51. SmtpUsername string `json:"smtpUsername" form:"smtpUsername"`
  52. SmtpPassword string `json:"smtpPassword" form:"smtpPassword"`
  53. SmtpFrom string `json:"smtpFrom" form:"smtpFrom"`
  54. SmtpFromName string `json:"smtpFromName" form:"smtpFromName"`
  55. SmtpTo string `json:"smtpTo" form:"smtpTo"`
  56. SmtpEncryptionType string `json:"smtpEncryptionType" form:"smtpEncryptionType"`
  57. SmtpEnabledEvents string `json:"smtpEnabledEvents" form:"smtpEnabledEvents"`
  58. SmtpCpu int `json:"smtpCpu" form:"smtpCpu" validate:"gte=0,lte=100"`
  59. SmtpMemory int `json:"smtpMemory" form:"smtpMemory" validate:"gte=0,lte=100"`
  60. OutboundDownThreshold int `json:"outboundDownThreshold" form:"outboundDownThreshold" validate:"gte=1,lte=100"`
  61. TimeLocation string `json:"timeLocation" form:"timeLocation"`
  62. TwoFactorEnable bool `json:"twoFactorEnable" form:"twoFactorEnable"`
  63. TwoFactorToken string `json:"twoFactorToken" form:"twoFactorToken"`
  64. SubEnable bool `json:"subEnable" form:"subEnable"`
  65. SubJsonEnable bool `json:"subJsonEnable" form:"subJsonEnable"`
  66. SubJsonAutoDetect bool `json:"subJsonAutoDetect" form:"subJsonAutoDetect"`
  67. SubJsonAlwaysArray bool `json:"subJsonAlwaysArray" form:"subJsonAlwaysArray"`
  68. SubJsonUserAgentRegex string `json:"subJsonUserAgentRegex" form:"subJsonUserAgentRegex"`
  69. SubClashAutoDetect bool `json:"subClashAutoDetect" form:"subClashAutoDetect"`
  70. SubClashUserAgentRegex string `json:"subClashUserAgentRegex" form:"subClashUserAgentRegex"`
  71. SubTitle string `json:"subTitle" form:"subTitle"`
  72. SubSupportUrl string `json:"subSupportUrl" form:"subSupportUrl"`
  73. SubProfileUrl string `json:"subProfileUrl" form:"subProfileUrl"`
  74. SubAnnounce string `json:"subAnnounce" form:"subAnnounce"`
  75. SubEnableRouting bool `json:"subEnableRouting" form:"subEnableRouting"`
  76. SubRoutingRules string `json:"subRoutingRules" form:"subRoutingRules"`
  77. SubIncyEnableRouting bool `json:"subIncyEnableRouting" form:"subIncyEnableRouting"`
  78. SubIncyRoutingRules string `json:"subIncyRoutingRules" form:"subIncyRoutingRules"`
  79. SubListen string `json:"subListen" form:"subListen"`
  80. SubPort int `json:"subPort" form:"subPort" validate:"gte=1,lte=65535"`
  81. SubPath string `json:"subPath" form:"subPath"`
  82. SubDomain string `json:"subDomain" form:"subDomain"`
  83. SubCertFile string `json:"subCertFile" form:"subCertFile"`
  84. SubKeyFile string `json:"subKeyFile" form:"subKeyFile"`
  85. SubUpdates int `json:"subUpdates" form:"subUpdates" validate:"gte=0,lte=525600"`
  86. ExternalTrafficInformEnable bool `json:"externalTrafficInformEnable" form:"externalTrafficInformEnable"`
  87. ExternalTrafficInformURI string `json:"externalTrafficInformURI" form:"externalTrafficInformURI"`
  88. RestartXrayOnClientDisable bool `json:"restartXrayOnClientDisable" form:"restartXrayOnClientDisable"`
  89. SubEncrypt bool `json:"subEncrypt" form:"subEncrypt"`
  90. SubURI string `json:"subURI" form:"subURI"`
  91. SubJsonPath string `json:"subJsonPath" form:"subJsonPath"`
  92. SubJsonURI string `json:"subJsonURI" form:"subJsonURI"`
  93. SubClashEnable bool `json:"subClashEnable" form:"subClashEnable"`
  94. SubClashPath string `json:"subClashPath" form:"subClashPath"`
  95. SubClashURI string `json:"subClashURI" form:"subClashURI"`
  96. SubClashEnableRouting bool `json:"subClashEnableRouting" form:"subClashEnableRouting"`
  97. SubClashRules string `json:"subClashRules" form:"subClashRules"`
  98. SubJsonMux string `json:"subJsonMux" form:"subJsonMux"`
  99. SubJsonRules string `json:"subJsonRules" form:"subJsonRules"`
  100. SubJsonFinalMask string `json:"subJsonFinalMask" form:"subJsonFinalMask"`
  101. SubJsonObservatory string `json:"subJsonObservatory" form:"subJsonObservatory"`
  102. SubThemeDir string `json:"subThemeDir" form:"subThemeDir"`
  103. SubHideSettings bool `json:"subHideSettings" form:"subHideSettings"`
  104. LdapEnable bool `json:"ldapEnable" form:"ldapEnable"`
  105. LdapHost string `json:"ldapHost" form:"ldapHost"`
  106. LdapPort int `json:"ldapPort" form:"ldapPort" validate:"gte=0,lte=65535"`
  107. LdapUseTLS bool `json:"ldapUseTLS" form:"ldapUseTLS"`
  108. LdapInsecureSkipVerify bool `json:"ldapInsecureSkipVerify" form:"ldapInsecureSkipVerify"`
  109. LdapBindDN string `json:"ldapBindDN" form:"ldapBindDN"`
  110. LdapPassword string `json:"ldapPassword" form:"ldapPassword"`
  111. LdapBaseDN string `json:"ldapBaseDN" form:"ldapBaseDN"`
  112. LdapUserFilter string `json:"ldapUserFilter" form:"ldapUserFilter"`
  113. LdapUserAttr string `json:"ldapUserAttr" form:"ldapUserAttr"`
  114. LdapVlessField string `json:"ldapVlessField" form:"ldapVlessField"`
  115. LdapSyncCron string `json:"ldapSyncCron" form:"ldapSyncCron"`
  116. LdapFlagField string `json:"ldapFlagField" form:"ldapFlagField"`
  117. LdapTruthyValues string `json:"ldapTruthyValues" form:"ldapTruthyValues"`
  118. LdapInvertFlag bool `json:"ldapInvertFlag" form:"ldapInvertFlag"`
  119. LdapInboundTags string `json:"ldapInboundTags" form:"ldapInboundTags"`
  120. LdapAutoCreate bool `json:"ldapAutoCreate" form:"ldapAutoCreate"`
  121. LdapAutoDelete bool `json:"ldapAutoDelete" form:"ldapAutoDelete"`
  122. LdapDefaultTotalGB int `json:"ldapDefaultTotalGB" form:"ldapDefaultTotalGB" validate:"gte=0"`
  123. LdapDefaultExpiryDays int `json:"ldapDefaultExpiryDays" form:"ldapDefaultExpiryDays" validate:"gte=0"`
  124. LdapDefaultLimitIP int `json:"ldapDefaultLimitIP" form:"ldapDefaultLimitIP" validate:"gte=0"`
  125. WarpUpdateInterval int `json:"warpUpdateInterval" form:"warpUpdateInterval" validate:"gte=0"`
  126. }
  127. type AllSettingView struct {
  128. AllSetting
  129. HasTgBotToken bool `json:"hasTgBotToken"`
  130. HasTwoFactorToken bool `json:"hasTwoFactorToken"`
  131. HasLdapPassword bool `json:"hasLdapPassword"`
  132. HasApiToken bool `json:"hasApiToken"`
  133. HasWarpSecret bool `json:"hasWarpSecret"`
  134. HasNordSecret bool `json:"hasNordSecret"`
  135. HasSmtpPassword bool `json:"hasSmtpPassword"`
  136. }
  137. func pathHasForbiddenChar(s string) bool {
  138. for _, r := range s {
  139. if r == '\\' || r == ' ' || r < 0x20 || r == 0x7f {
  140. return true
  141. }
  142. }
  143. return false
  144. }
  145. // CheckNetipAddrOrPrefixList mirrors parseIpLimitAllowlist exactly: net and netip
  146. // disagree (net accepts "/024", netip does not), so save and scan must share rules.
  147. func CheckNetipAddrOrPrefixList(list, message string) error {
  148. for entry := range strings.SplitSeq(list, ",") {
  149. entry = strings.TrimSpace(entry)
  150. if entry == "" {
  151. continue
  152. }
  153. if _, err := netip.ParseAddr(entry); err == nil {
  154. continue
  155. }
  156. if _, err := netip.ParsePrefix(entry); err != nil {
  157. return common.NewError(message, entry)
  158. }
  159. }
  160. return nil
  161. }
  162. // checkIPOrCIDRList rejects the first comma-separated entry that is neither a
  163. // bare address nor a CIDR, naming it with the caller's message.
  164. func checkIPOrCIDRList(list, message string) error {
  165. for entry := range strings.SplitSeq(list, ",") {
  166. entry = strings.TrimSpace(entry)
  167. if entry == "" {
  168. continue
  169. }
  170. if ip := net.ParseIP(entry); ip != nil {
  171. continue
  172. }
  173. if _, _, err := net.ParseCIDR(entry); err != nil {
  174. return common.NewError(message, entry)
  175. }
  176. }
  177. return nil
  178. }
  179. func (s *AllSetting) CheckValid() error {
  180. if s.WebListen != "" {
  181. ip := net.ParseIP(s.WebListen)
  182. if ip == nil {
  183. return common.NewError("web listen is not valid ip:", s.WebListen)
  184. }
  185. }
  186. if s.SubListen != "" {
  187. ip := net.ParseIP(s.SubListen)
  188. if ip == nil {
  189. return common.NewError("Sub listen is not valid ip:", s.SubListen)
  190. }
  191. }
  192. if s.WebPort <= 0 || s.WebPort > math.MaxUint16 {
  193. return common.NewError("web port is not a valid port:", s.WebPort)
  194. }
  195. if s.SubPort <= 0 || s.SubPort > math.MaxUint16 {
  196. return common.NewError("Sub port is not a valid port:", s.SubPort)
  197. }
  198. if (s.SubPort == s.WebPort) && listenAddressesConflict(s.WebListen, s.SubListen) {
  199. return common.NewError("Sub and Web could not use same ip:port, ", s.SubListen, ":", s.SubPort, " & ", s.WebListen, ":", s.WebPort)
  200. }
  201. if s.WebCertFile != "" || s.WebKeyFile != "" {
  202. _, err := tls.LoadX509KeyPair(s.WebCertFile, s.WebKeyFile)
  203. if err != nil {
  204. return common.NewErrorf("cert file <%v> or key file <%v> invalid: %v", s.WebCertFile, s.WebKeyFile, err)
  205. }
  206. }
  207. if s.SubCertFile != "" || s.SubKeyFile != "" {
  208. _, err := tls.LoadX509KeyPair(s.SubCertFile, s.SubKeyFile)
  209. if err != nil {
  210. return common.NewErrorf("cert file <%v> or key file <%v> invalid: %v", s.SubCertFile, s.SubKeyFile, err)
  211. }
  212. }
  213. for _, p := range []struct {
  214. name string
  215. value string
  216. }{
  217. {"web base path", s.WebBasePath},
  218. {"subscription path", s.SubPath},
  219. {"subscription JSON path", s.SubJsonPath},
  220. {"subscription Clash path", s.SubClashPath},
  221. } {
  222. if pathHasForbiddenChar(p.value) {
  223. return common.NewError("URI path contains an invalid character:", p.name)
  224. }
  225. }
  226. if !strings.HasPrefix(s.WebBasePath, "/") {
  227. s.WebBasePath = "/" + s.WebBasePath
  228. }
  229. if !strings.HasSuffix(s.WebBasePath, "/") {
  230. s.WebBasePath += "/"
  231. }
  232. if !strings.HasPrefix(s.SubPath, "/") {
  233. s.SubPath = "/" + s.SubPath
  234. }
  235. if !strings.HasSuffix(s.SubPath, "/") {
  236. s.SubPath += "/"
  237. }
  238. if !strings.HasPrefix(s.SubJsonPath, "/") {
  239. s.SubJsonPath = "/" + s.SubJsonPath
  240. }
  241. if !strings.HasSuffix(s.SubJsonPath, "/") {
  242. s.SubJsonPath += "/"
  243. }
  244. if !strings.HasPrefix(s.SubClashPath, "/") {
  245. s.SubClashPath = "/" + s.SubClashPath
  246. }
  247. if !strings.HasSuffix(s.SubClashPath, "/") {
  248. s.SubClashPath += "/"
  249. }
  250. if err := checkIPOrCIDRList(s.TrustedProxyCIDRs, "trusted proxy CIDR is not valid:"); err != nil {
  251. return err
  252. }
  253. // Rejected here rather than skipped at scan time: a typo in an allowlist
  254. // entry silently leaves the address unprotected until a trusted network gets banned.
  255. if err := CheckNetipAddrOrPrefixList(s.IpLimitAllowlist, "IP limit allowlist entry is not valid:"); err != nil {
  256. return err
  257. }
  258. _, err := time.LoadLocation(s.TimeLocation)
  259. if err != nil {
  260. return common.NewError("time location not exist:", s.TimeLocation)
  261. }
  262. if s.SmtpFrom != "" {
  263. if _, err := mail.ParseAddress(s.SmtpFrom); err != nil {
  264. return common.NewError("SMTP from address is not valid:", s.SmtpFrom)
  265. }
  266. }
  267. return nil
  268. }
  269. // listenAddressesConflict reports whether two listen addresses on the same port
  270. // would collide at bind time. A wildcard listen ("", "0.0.0.0", "::") overlaps
  271. // every address, so it conflicts with anything on that port; two specific
  272. // addresses conflict only when identical.
  273. func listenAddressesConflict(a, b string) bool {
  274. if a == b {
  275. return true
  276. }
  277. return isWildcardListen(a) || isWildcardListen(b)
  278. }
  279. func isWildcardListen(listen string) bool {
  280. if listen == "" {
  281. return true
  282. }
  283. if ip := net.ParseIP(listen); ip != nil {
  284. return ip.IsUnspecified()
  285. }
  286. return false
  287. }
  288. type HostGroup struct {
  289. GroupId string `json:"groupId"`
  290. InboundIds []int `json:"inboundIds" validate:"required,min=1"`
  291. Hosts []string `json:"hosts" validate:"omitempty"`
  292. SortOrder int `json:"sortOrder"`
  293. Remark string `json:"remark" validate:"required,max=256"`
  294. ServerDescription string `json:"serverDescription" validate:"omitempty,max=64"`
  295. IsDisabled bool `json:"isDisabled"`
  296. IsHidden bool `json:"isHidden"`
  297. Tags []string `json:"tags"`
  298. Port int `json:"port" validate:"gte=0,lte=65535"`
  299. Security string `json:"security" validate:"omitempty,oneof=same tls none reality"`
  300. Sni string `json:"sni"`
  301. HostHeader string `json:"hostHeader"`
  302. Path string `json:"path"`
  303. Alpn []string `json:"alpn"`
  304. Fingerprint string `json:"fingerprint"`
  305. OverrideSniFromAddress bool `json:"overrideSniFromAddress"`
  306. KeepSniBlank bool `json:"keepSniBlank"`
  307. PinnedPeerCertSha256 []string `json:"pinnedPeerCertSha256"`
  308. VerifyPeerCertByName string `json:"verifyPeerCertByName"`
  309. AllowInsecure bool `json:"allowInsecure"`
  310. EchConfigList string `json:"echConfigList"`
  311. MuxParams string `json:"muxParams"`
  312. SockoptParams string `json:"sockoptParams"`
  313. FinalMask string `json:"finalMask"`
  314. VlessRoute string `json:"vlessRoute"`
  315. ExcludeFromSubTypes []string `json:"excludeFromSubTypes"`
  316. NodeGuids []string `json:"nodeGuids"`
  317. MihomoIpVersion string `json:"mihomoIpVersion" validate:"omitempty,oneof=dual ipv4 ipv6 ipv4-prefer ipv6-prefer"`
  318. MihomoX25519 bool `json:"mihomoX25519"`
  319. ShuffleHost bool `json:"shuffleHost"`
  320. }