1
0

entity.go 15 KB

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