entity.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. SubJsonObservatory string `json:"subJsonObservatory" form:"subJsonObservatory"`
  99. SubThemeDir string `json:"subThemeDir" form:"subThemeDir"`
  100. SubHideSettings bool `json:"subHideSettings" form:"subHideSettings"`
  101. LdapEnable bool `json:"ldapEnable" form:"ldapEnable"`
  102. LdapHost string `json:"ldapHost" form:"ldapHost"`
  103. LdapPort int `json:"ldapPort" form:"ldapPort" validate:"gte=0,lte=65535"`
  104. LdapUseTLS bool `json:"ldapUseTLS" form:"ldapUseTLS"`
  105. LdapInsecureSkipVerify bool `json:"ldapInsecureSkipVerify" form:"ldapInsecureSkipVerify"`
  106. LdapBindDN string `json:"ldapBindDN" form:"ldapBindDN"`
  107. LdapPassword string `json:"ldapPassword" form:"ldapPassword"`
  108. LdapBaseDN string `json:"ldapBaseDN" form:"ldapBaseDN"`
  109. LdapUserFilter string `json:"ldapUserFilter" form:"ldapUserFilter"`
  110. LdapUserAttr string `json:"ldapUserAttr" form:"ldapUserAttr"`
  111. LdapVlessField string `json:"ldapVlessField" form:"ldapVlessField"`
  112. LdapSyncCron string `json:"ldapSyncCron" form:"ldapSyncCron"`
  113. LdapFlagField string `json:"ldapFlagField" form:"ldapFlagField"`
  114. LdapTruthyValues string `json:"ldapTruthyValues" form:"ldapTruthyValues"`
  115. LdapInvertFlag bool `json:"ldapInvertFlag" form:"ldapInvertFlag"`
  116. LdapInboundTags string `json:"ldapInboundTags" form:"ldapInboundTags"`
  117. LdapAutoCreate bool `json:"ldapAutoCreate" form:"ldapAutoCreate"`
  118. LdapAutoDelete bool `json:"ldapAutoDelete" form:"ldapAutoDelete"`
  119. LdapDefaultTotalGB int `json:"ldapDefaultTotalGB" form:"ldapDefaultTotalGB" validate:"gte=0"`
  120. LdapDefaultExpiryDays int `json:"ldapDefaultExpiryDays" form:"ldapDefaultExpiryDays" validate:"gte=0"`
  121. LdapDefaultLimitIP int `json:"ldapDefaultLimitIP" form:"ldapDefaultLimitIP" validate:"gte=0"`
  122. WarpUpdateInterval int `json:"warpUpdateInterval" form:"warpUpdateInterval" validate:"gte=0"`
  123. }
  124. type AllSettingView struct {
  125. AllSetting
  126. HasTgBotToken bool `json:"hasTgBotToken"`
  127. HasTwoFactorToken bool `json:"hasTwoFactorToken"`
  128. HasLdapPassword bool `json:"hasLdapPassword"`
  129. HasApiToken bool `json:"hasApiToken"`
  130. HasWarpSecret bool `json:"hasWarpSecret"`
  131. HasNordSecret bool `json:"hasNordSecret"`
  132. HasSmtpPassword bool `json:"hasSmtpPassword"`
  133. }
  134. func pathHasForbiddenChar(s string) bool {
  135. for _, r := range s {
  136. if r == '\\' || r == ' ' || r < 0x20 || r == 0x7f {
  137. return true
  138. }
  139. }
  140. return false
  141. }
  142. // CheckNetipAddrOrPrefixList mirrors parseIpLimitAllowlist exactly: net and netip
  143. // disagree (net accepts "/024", netip does not), so save and scan must share rules.
  144. func CheckNetipAddrOrPrefixList(list, message string) error {
  145. for entry := range strings.SplitSeq(list, ",") {
  146. entry = strings.TrimSpace(entry)
  147. if entry == "" {
  148. continue
  149. }
  150. if _, err := netip.ParseAddr(entry); err == nil {
  151. continue
  152. }
  153. if _, err := netip.ParsePrefix(entry); err != nil {
  154. return common.NewError(message, entry)
  155. }
  156. }
  157. return nil
  158. }
  159. // checkIPOrCIDRList rejects the first comma-separated entry that is neither a
  160. // bare address nor a CIDR, naming it with the caller's message.
  161. func checkIPOrCIDRList(list, message string) error {
  162. for entry := range strings.SplitSeq(list, ",") {
  163. entry = strings.TrimSpace(entry)
  164. if entry == "" {
  165. continue
  166. }
  167. if ip := net.ParseIP(entry); ip != nil {
  168. continue
  169. }
  170. if _, _, err := net.ParseCIDR(entry); err != nil {
  171. return common.NewError(message, entry)
  172. }
  173. }
  174. return nil
  175. }
  176. func (s *AllSetting) CheckValid() error {
  177. if s.WebListen != "" {
  178. ip := net.ParseIP(s.WebListen)
  179. if ip == nil {
  180. return common.NewError("web listen is not valid ip:", s.WebListen)
  181. }
  182. }
  183. if s.SubListen != "" {
  184. ip := net.ParseIP(s.SubListen)
  185. if ip == nil {
  186. return common.NewError("Sub listen is not valid ip:", s.SubListen)
  187. }
  188. }
  189. if s.WebPort <= 0 || s.WebPort > math.MaxUint16 {
  190. return common.NewError("web port is not a valid port:", s.WebPort)
  191. }
  192. if s.SubPort <= 0 || s.SubPort > math.MaxUint16 {
  193. return common.NewError("Sub port is not a valid port:", s.SubPort)
  194. }
  195. if (s.SubPort == s.WebPort) && listenAddressesConflict(s.WebListen, s.SubListen) {
  196. return common.NewError("Sub and Web could not use same ip:port, ", s.SubListen, ":", s.SubPort, " & ", s.WebListen, ":", s.WebPort)
  197. }
  198. if s.WebCertFile != "" || s.WebKeyFile != "" {
  199. _, err := tls.LoadX509KeyPair(s.WebCertFile, s.WebKeyFile)
  200. if err != nil {
  201. return common.NewErrorf("cert file <%v> or key file <%v> invalid: %v", s.WebCertFile, s.WebKeyFile, err)
  202. }
  203. }
  204. if s.SubCertFile != "" || s.SubKeyFile != "" {
  205. _, err := tls.LoadX509KeyPair(s.SubCertFile, s.SubKeyFile)
  206. if err != nil {
  207. return common.NewErrorf("cert file <%v> or key file <%v> invalid: %v", s.SubCertFile, s.SubKeyFile, err)
  208. }
  209. }
  210. for _, p := range []struct {
  211. name string
  212. value string
  213. }{
  214. {"web base path", s.WebBasePath},
  215. {"subscription path", s.SubPath},
  216. {"subscription JSON path", s.SubJsonPath},
  217. {"subscription Clash path", s.SubClashPath},
  218. } {
  219. if pathHasForbiddenChar(p.value) {
  220. return common.NewError("URI path contains an invalid character:", p.name)
  221. }
  222. }
  223. if !strings.HasPrefix(s.WebBasePath, "/") {
  224. s.WebBasePath = "/" + s.WebBasePath
  225. }
  226. if !strings.HasSuffix(s.WebBasePath, "/") {
  227. s.WebBasePath += "/"
  228. }
  229. if !strings.HasPrefix(s.SubPath, "/") {
  230. s.SubPath = "/" + s.SubPath
  231. }
  232. if !strings.HasSuffix(s.SubPath, "/") {
  233. s.SubPath += "/"
  234. }
  235. if !strings.HasPrefix(s.SubJsonPath, "/") {
  236. s.SubJsonPath = "/" + s.SubJsonPath
  237. }
  238. if !strings.HasSuffix(s.SubJsonPath, "/") {
  239. s.SubJsonPath += "/"
  240. }
  241. if !strings.HasPrefix(s.SubClashPath, "/") {
  242. s.SubClashPath = "/" + s.SubClashPath
  243. }
  244. if !strings.HasSuffix(s.SubClashPath, "/") {
  245. s.SubClashPath += "/"
  246. }
  247. if err := checkIPOrCIDRList(s.TrustedProxyCIDRs, "trusted proxy CIDR is not valid:"); err != nil {
  248. return err
  249. }
  250. // Rejected here rather than skipped at scan time: a typo in an allowlist
  251. // entry silently leaves the address unprotected until a trusted network gets banned.
  252. if err := CheckNetipAddrOrPrefixList(s.IpLimitAllowlist, "IP limit allowlist entry is not valid:"); err != nil {
  253. return err
  254. }
  255. _, err := time.LoadLocation(s.TimeLocation)
  256. if err != nil {
  257. return common.NewError("time location not exist:", s.TimeLocation)
  258. }
  259. if s.SmtpFrom != "" {
  260. if _, err := mail.ParseAddress(s.SmtpFrom); err != nil {
  261. return common.NewError("SMTP from address is not valid:", s.SmtpFrom)
  262. }
  263. }
  264. return nil
  265. }
  266. // listenAddressesConflict reports whether two listen addresses on the same port
  267. // would collide at bind time. A wildcard listen ("", "0.0.0.0", "::") overlaps
  268. // every address, so it conflicts with anything on that port; two specific
  269. // addresses conflict only when identical.
  270. func listenAddressesConflict(a, b string) bool {
  271. if a == b {
  272. return true
  273. }
  274. return isWildcardListen(a) || isWildcardListen(b)
  275. }
  276. func isWildcardListen(listen string) bool {
  277. if listen == "" {
  278. return true
  279. }
  280. if ip := net.ParseIP(listen); ip != nil {
  281. return ip.IsUnspecified()
  282. }
  283. return false
  284. }
  285. type HostGroup struct {
  286. GroupId string `json:"groupId"`
  287. InboundIds []int `json:"inboundIds" validate:"required,min=1"`
  288. Hosts []string `json:"hosts" validate:"omitempty"`
  289. SortOrder int `json:"sortOrder"`
  290. Remark string `json:"remark" validate:"required,max=256"`
  291. ServerDescription string `json:"serverDescription" validate:"omitempty,max=64"`
  292. IsDisabled bool `json:"isDisabled"`
  293. IsHidden bool `json:"isHidden"`
  294. Tags []string `json:"tags"`
  295. Port int `json:"port" validate:"gte=0,lte=65535"`
  296. Security string `json:"security" validate:"omitempty,oneof=same tls none reality"`
  297. Sni string `json:"sni"`
  298. HostHeader string `json:"hostHeader"`
  299. Path string `json:"path"`
  300. Alpn []string `json:"alpn"`
  301. Fingerprint string `json:"fingerprint"`
  302. OverrideSniFromAddress bool `json:"overrideSniFromAddress"`
  303. KeepSniBlank bool `json:"keepSniBlank"`
  304. PinnedPeerCertSha256 []string `json:"pinnedPeerCertSha256"`
  305. VerifyPeerCertByName string `json:"verifyPeerCertByName"`
  306. AllowInsecure bool `json:"allowInsecure"`
  307. EchConfigList string `json:"echConfigList"`
  308. MuxParams string `json:"muxParams"`
  309. SockoptParams string `json:"sockoptParams"`
  310. FinalMask string `json:"finalMask"`
  311. VlessRoute string `json:"vlessRoute"`
  312. ExcludeFromSubTypes []string `json:"excludeFromSubTypes"`
  313. NodeGuids []string `json:"nodeGuids"`
  314. MihomoIpVersion string `json:"mihomoIpVersion" validate:"omitempty,oneof=dual ipv4 ipv6 ipv4-prefer ipv6-prefer"`
  315. MihomoX25519 bool `json:"mihomoX25519"`
  316. ShuffleHost bool `json:"shuffleHost"`
  317. }