inbound.go 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096
  1. // Package service provides business logic services for the 3x-ui web panel,
  2. // including inbound/outbound management, user administration, settings, and Xray integration.
  3. package service
  4. import (
  5. "context"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "net"
  10. "regexp"
  11. "slices"
  12. "sort"
  13. "strings"
  14. "time"
  15. "github.com/google/uuid"
  16. "github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
  17. "github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
  18. "github.com/mhsanaei/3x-ui/v3/internal/database"
  19. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  20. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  21. "github.com/mhsanaei/3x-ui/v3/internal/mtproto"
  22. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  23. "github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
  24. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  25. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  26. "gorm.io/gorm"
  27. "gorm.io/gorm/clause"
  28. )
  29. type InboundService struct {
  30. clientService ClientService
  31. fallbackService FallbackService
  32. // FromNodeSync marks a master push: the row was validated where the operator
  33. // acted, and a node that refuses it only falls out of sync.
  34. FromNodeSync bool
  35. }
  36. func normalizeTrafficResetDay(day int) int {
  37. if day < 1 {
  38. return 1
  39. }
  40. return min(day, 31)
  41. }
  42. func normalizeInboundShareAddrStrategy(strategy string) string {
  43. strategy = strings.TrimSpace(strategy)
  44. switch strategy {
  45. case "listen", "custom":
  46. return strategy
  47. default:
  48. return "node"
  49. }
  50. }
  51. func normalizeInboundShareAddress(inbound *model.Inbound) {
  52. if inbound == nil {
  53. return
  54. }
  55. if inbound.Protocol == model.MTProto {
  56. inbound.ShareAddrStrategy = "listen"
  57. inbound.ShareAddr = ""
  58. return
  59. }
  60. inbound.ShareAddrStrategy = normalizeInboundShareAddrStrategy(inbound.ShareAddrStrategy)
  61. if addr, err := normalizeInboundShareHost(inbound.ShareAddr); err == nil {
  62. inbound.ShareAddr = addr
  63. } else {
  64. inbound.ShareAddr = strings.TrimSpace(inbound.ShareAddr)
  65. }
  66. }
  67. func normalizeInboundShareAddressStrict(inbound *model.Inbound) error {
  68. if inbound == nil {
  69. return nil
  70. }
  71. if inbound.Protocol == model.MTProto {
  72. inbound.ShareAddrStrategy = "listen"
  73. inbound.ShareAddr = ""
  74. return nil
  75. }
  76. inbound.ShareAddrStrategy = normalizeInboundShareAddrStrategy(inbound.ShareAddrStrategy)
  77. addr, err := normalizeInboundShareHost(inbound.ShareAddr)
  78. if err != nil {
  79. return common.NewError("shareAddr must be a host or IP without scheme or port")
  80. }
  81. inbound.ShareAddr = addr
  82. return nil
  83. }
  84. func normalizeInboundShareHost(raw string) (string, error) {
  85. addr := strings.TrimSpace(raw)
  86. if addr == "" {
  87. return "", nil
  88. }
  89. if strings.Contains(addr, "://") || strings.HasPrefix(addr, "//") || strings.ContainsAny(addr, "/?#@") {
  90. return "", fmt.Errorf("invalid share address %q", raw)
  91. }
  92. if strings.HasPrefix(addr, "[") {
  93. if !strings.HasSuffix(addr, "]") {
  94. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  95. }
  96. ip := net.ParseIP(addr[1 : len(addr)-1])
  97. if ip == nil || ip.To4() != nil {
  98. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  99. }
  100. return "[" + ip.String() + "]", nil
  101. }
  102. if strings.Contains(addr, ":") {
  103. if _, _, err := net.SplitHostPort(addr); err == nil {
  104. return "", fmt.Errorf("share address must not include port")
  105. }
  106. ip := net.ParseIP(addr)
  107. if ip == nil || ip.To4() != nil {
  108. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  109. }
  110. return "[" + ip.String() + "]", nil
  111. }
  112. host, err := netsafe.NormalizeHost(addr)
  113. if err != nil {
  114. return "", err
  115. }
  116. return host, nil
  117. }
  118. func legacyMtprotoShareAddr(inbound *model.Inbound) string {
  119. if inbound == nil || inbound.Protocol != model.MTProto || strings.TrimSpace(inbound.ShareAddrStrategy) != "custom" {
  120. return ""
  121. }
  122. addr, err := normalizeInboundShareHost(inbound.ShareAddr)
  123. if err != nil {
  124. return ""
  125. }
  126. return addr
  127. }
  128. func normalizeInboundShareAddressColumns(tx *gorm.DB) error {
  129. if tx == nil || !tx.Migrator().HasColumn(&model.Inbound{}, "share_addr_strategy") {
  130. return nil
  131. }
  132. strategyExpr := `CASE TRIM(COALESCE(share_addr_strategy, '')) WHEN 'listen' THEN 'listen' WHEN 'custom' THEN 'custom' ELSE 'node' END`
  133. if err := tx.Exec(`UPDATE inbounds SET share_addr_strategy = ` + strategyExpr + ` WHERE share_addr_strategy IS NULL OR share_addr_strategy <> ` + strategyExpr).Error; err != nil {
  134. return err
  135. }
  136. hasShareAddr := tx.Migrator().HasColumn(&model.Inbound{}, "share_addr")
  137. if hasShareAddr {
  138. if err := tx.Exec(`UPDATE inbounds SET share_addr = TRIM(share_addr) WHERE share_addr IS NOT NULL AND share_addr <> TRIM(share_addr)`).Error; err != nil {
  139. return err
  140. }
  141. }
  142. if !hasShareAddr {
  143. return nil
  144. }
  145. var rows []struct {
  146. Id int
  147. ShareAddrStrategy string
  148. ShareAddr string
  149. }
  150. if err := tx.Model(&model.Inbound{}).Select("id", "share_addr_strategy", "share_addr").Find(&rows).Error; err != nil {
  151. return err
  152. }
  153. for _, row := range rows {
  154. strategy := normalizeInboundShareAddrStrategy(row.ShareAddrStrategy)
  155. addr, addrErr := normalizeInboundShareHost(row.ShareAddr)
  156. if addrErr != nil {
  157. strategy = "node"
  158. addr = ""
  159. }
  160. updates := map[string]any{}
  161. if strategy != row.ShareAddrStrategy {
  162. updates["share_addr_strategy"] = strategy
  163. }
  164. if addr != row.ShareAddr {
  165. updates["share_addr"] = addr
  166. }
  167. if len(updates) > 0 {
  168. if err := tx.Model(&model.Inbound{}).Where("id = ?", row.Id).Updates(updates).Error; err != nil {
  169. return err
  170. }
  171. }
  172. }
  173. return nil
  174. }
  175. // GetInbounds retrieves all inbounds for a specific user with client stats.
  176. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  177. db := database.GetDB()
  178. var inbounds []*model.Inbound
  179. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  180. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  181. return nil, err
  182. }
  183. s.enrichClientStats(db, inbounds)
  184. s.annotateFallbackParents(db, inbounds)
  185. s.annotateLocalOriginGuid(inbounds)
  186. return inbounds, nil
  187. }
  188. // annotateLocalOriginGuid fills OriginNodeGuid for this panel's OWN inbounds
  189. // (NodeID == nil) with the panel's stable GUID; inbounds synced from a node
  190. // already carry the originating node's GUID. Read-time only (not persisted) so
  191. // the per-inbound online view can scope by GUID uniformly across a chain of
  192. // nodes (#4983).
  193. func (s *InboundService) annotateLocalOriginGuid(inbounds []*model.Inbound) {
  194. if len(inbounds) == 0 {
  195. return
  196. }
  197. guid := s.panelGuid()
  198. if guid == "" {
  199. return
  200. }
  201. for _, ib := range inbounds {
  202. if ib.OriginNodeGuid == "" && ib.NodeID == nil {
  203. ib.OriginNodeGuid = guid
  204. }
  205. }
  206. }
  207. // GetInboundsSlim returns the same list of inbounds as GetInbounds but
  208. // strips every per-client field other than email / enable / comment from
  209. // settings.clients and skips UUID/SubId enrichment on ClientStats. The
  210. // inbounds page only needs those three to roll up client counts and
  211. // render badges, so this trims tens of bytes per client (UUID, password,
  212. // flow, security, totalGB, expiryTime, limitIp, tgId, ...) which adds
  213. // up fast on installs with thousands of clients.
  214. //
  215. // Full client data is still available through GET /panel/api/inbounds/get/:id
  216. // for the edit/info/qr/export/clone flows that need it.
  217. func (s *InboundService) GetInboundsSlim(userId int) ([]*model.Inbound, error) {
  218. db := database.GetDB()
  219. var inbounds []*model.Inbound
  220. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  221. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  222. return nil, err
  223. }
  224. s.annotateFallbackParents(db, inbounds)
  225. s.annotateLocalOriginGuid(inbounds)
  226. // Top up stats rows owned by sibling inbounds (multi-attached clients)
  227. // so the list's depleted/expiring badges see every client; the UUID/SubId
  228. // enrichment stays skipped. Must run before slimming strips the settings.
  229. s.backfillClientStats(db, inbounds)
  230. // Slim feeds the panel UI only (masters poll the full list), so the badge
  231. // math may see the cross-panel totals a master pushed.
  232. s.overlayInboundsClientStats(db, inbounds)
  233. for _, ib := range inbounds {
  234. ib.Settings = slimSettingsClients(ib.Settings)
  235. }
  236. return inbounds, nil
  237. }
  238. // slimSettingsClients rewrites the inbound settings JSON so settings.clients[]
  239. // keeps only the fields the list view actually reads. Returns the input
  240. // unchanged when the JSON can't be parsed or has no clients array.
  241. func slimSettingsClients(settings string) string {
  242. if settings == "" {
  243. return settings
  244. }
  245. var raw map[string]any
  246. if err := json.Unmarshal([]byte(settings), &raw); err != nil {
  247. return settings
  248. }
  249. clients, ok := raw["clients"].([]any)
  250. if !ok || len(clients) == 0 {
  251. return settings
  252. }
  253. slim := make([]any, 0, len(clients))
  254. for _, entry := range clients {
  255. c, ok := entry.(map[string]any)
  256. if !ok {
  257. continue
  258. }
  259. row := make(map[string]any, 3)
  260. if v, ok := c["email"]; ok {
  261. row["email"] = v
  262. }
  263. if v, ok := c["enable"]; ok {
  264. row["enable"] = v
  265. }
  266. if v, ok := c["comment"]; ok && v != "" {
  267. row["comment"] = v
  268. }
  269. slim = append(slim, row)
  270. }
  271. raw["clients"] = slim
  272. out, err := json.Marshal(raw)
  273. if err != nil {
  274. return settings
  275. }
  276. return string(out)
  277. }
  278. // annotateFallbackParents fills FallbackParent on each inbound that is
  279. // the child side of a fallback rule. One DB round-trip serves the full
  280. // list — the frontend needs this to rewrite the child's client-share
  281. // link so it points at the master's reachable endpoint.
  282. func (s *InboundService) annotateFallbackParents(db *gorm.DB, inbounds []*model.Inbound) {
  283. if len(inbounds) == 0 {
  284. return
  285. }
  286. childIds := make([]int, 0, len(inbounds))
  287. for _, ib := range inbounds {
  288. childIds = append(childIds, ib.Id)
  289. }
  290. var rows []model.InboundFallback
  291. if err := db.Where("child_id IN ?", childIds).
  292. Order("sort_order ASC, id ASC").
  293. Find(&rows).Error; err != nil {
  294. return
  295. }
  296. first := make(map[int]model.InboundFallback, len(rows))
  297. for _, r := range rows {
  298. if _, ok := first[r.ChildId]; !ok {
  299. first[r.ChildId] = r
  300. }
  301. }
  302. for _, ib := range inbounds {
  303. if r, ok := first[ib.Id]; ok {
  304. ib.FallbackParent = &model.FallbackParentInfo{
  305. MasterId: r.MasterId,
  306. Path: r.Path,
  307. }
  308. }
  309. }
  310. }
  311. type InboundOption struct {
  312. Id int `json:"id" example:"1"`
  313. Remark string `json:"remark" example:"VLESS-443"`
  314. Tag string `json:"tag" example:"in-443-tcp"`
  315. Protocol string `json:"protocol" example:"vless"`
  316. Port int `json:"port" example:"443"`
  317. Enable bool `json:"enable" example:"true"`
  318. TlsFlowCapable bool `json:"tlsFlowCapable" example:"true"`
  319. SsMethod string `json:"ssMethod"`
  320. WgPublicKey string `json:"wgPublicKey,omitempty"`
  321. WgMtu int `json:"wgMtu,omitempty"`
  322. WgDns string `json:"wgDns,omitempty"`
  323. MtprotoDomain string `json:"mtprotoDomain,omitempty"`
  324. // AwgServer carries the full AmneziaWG server block (keys, subnet,
  325. // obfuscation params) so the clients page can render a downloadable
  326. // per-client .conf without a second round trip.
  327. AwgServer *amneziawg.ServerSettings `json:"awgServer,omitempty"`
  328. // Hosting node; nil for this panel's own inbounds. Lets the clients
  329. // page map a node filter onto inbound IDs (#4997).
  330. NodeId *int `json:"nodeId,omitempty"`
  331. // Share-host resolution inputs, mirroring the subscription's
  332. // resolveInboundAddress so the clients page renders a node-managed WireGuard
  333. // Endpoint that points at the node, not the master panel. NodeAddress is the
  334. // hosting node's externally reachable address (empty for this panel's own
  335. // inbounds); Listen and ShareAddrStrategy/ShareAddr feed the same
  336. // node→listen→custom fallback the share/QR links already use.
  337. NodeAddress string `json:"nodeAddress,omitempty"`
  338. Listen string `json:"listen,omitempty"`
  339. ShareAddr string `json:"shareAddr,omitempty"`
  340. ShareAddrStrategy string `json:"shareAddrStrategy,omitempty"`
  341. }
  342. func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error) {
  343. db := database.GetDB()
  344. var rows []struct {
  345. Id int `gorm:"column:id"`
  346. Remark string `gorm:"column:remark"`
  347. Tag string `gorm:"column:tag"`
  348. Protocol string `gorm:"column:protocol"`
  349. Port int `gorm:"column:port"`
  350. Enable bool `gorm:"column:enable"`
  351. StreamSettings string `gorm:"column:stream_settings"`
  352. Settings string `gorm:"column:settings"`
  353. Listen string `gorm:"column:listen"`
  354. ShareAddr string `gorm:"column:share_addr"`
  355. ShareAddrStrategy string `gorm:"column:share_addr_strategy"`
  356. NodeId *int `gorm:"column:node_id"`
  357. NodeAddress string `gorm:"column:node_address"`
  358. DisableFlow bool `gorm:"column:disable_flow"`
  359. }
  360. err := db.Table("inbounds").
  361. Select("inbounds.id, inbounds.remark, inbounds.tag, inbounds.protocol, inbounds.port, inbounds.enable, inbounds.stream_settings, inbounds.settings, inbounds.listen, inbounds.share_addr, inbounds.share_addr_strategy, inbounds.node_id, COALESCE(nodes.address, '') AS node_address, inbounds.disable_flow").
  362. Joins("LEFT JOIN nodes ON nodes.id = inbounds.node_id").
  363. Where("inbounds.user_id = ?", userId).
  364. Order("inbounds.id ASC").
  365. Scan(&rows).Error
  366. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  367. return nil, err
  368. }
  369. out := make([]InboundOption, 0, len(rows))
  370. for _, r := range rows {
  371. wgPublicKey, wgMtu, wgDns := inboundWireguardHints(r.Protocol, r.Settings)
  372. shareAddrStrategy := r.ShareAddrStrategy
  373. if shareAddrStrategy == "node" {
  374. shareAddrStrategy = ""
  375. }
  376. out = append(out, InboundOption{
  377. Id: r.Id,
  378. Remark: r.Remark,
  379. Tag: r.Tag,
  380. Protocol: r.Protocol,
  381. Port: r.Port,
  382. Enable: r.Enable,
  383. TlsFlowCapable: !r.DisableFlow && inboundCanEnableTlsFlow(r.Protocol, r.StreamSettings, r.Settings),
  384. SsMethod: inboundShadowsocksMethod(r.Protocol, r.Settings),
  385. WgPublicKey: wgPublicKey,
  386. WgMtu: wgMtu,
  387. WgDns: wgDns,
  388. MtprotoDomain: inboundMtprotoDomain(r.Protocol, r.Settings),
  389. AwgServer: inboundAmneziaWGServer(r.Protocol, r.Settings),
  390. NodeId: r.NodeId,
  391. NodeAddress: r.NodeAddress,
  392. Listen: r.Listen,
  393. ShareAddr: r.ShareAddr,
  394. ShareAddrStrategy: shareAddrStrategy,
  395. })
  396. }
  397. return out, nil
  398. }
  399. func inboundWireguardHints(protocol string, settings string) (string, int, string) {
  400. if protocol != string(model.WireGuard) || strings.TrimSpace(settings) == "" {
  401. return "", 0, ""
  402. }
  403. var parsed struct {
  404. PublicKey string `json:"publicKey"`
  405. PubKey string `json:"pubKey"`
  406. SecretKey string `json:"secretKey"`
  407. MTU int `json:"mtu"`
  408. DNS string `json:"dns"`
  409. }
  410. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  411. return "", 0, ""
  412. }
  413. publicKey := parsed.PublicKey
  414. if publicKey == "" {
  415. publicKey = parsed.PubKey
  416. }
  417. if publicKey == "" && parsed.SecretKey != "" {
  418. if derived, err := wgutil.PublicKeyFromPrivate(parsed.SecretKey); err == nil {
  419. publicKey = derived
  420. }
  421. }
  422. return publicKey, parsed.MTU, parsed.DNS
  423. }
  424. // inboundAmneziaWGServer returns the AmneziaWG server block for the clients
  425. // page's config-download builder, or nil when the inbound isn't AmneziaWG or
  426. // its settings don't parse. PrivateKey is redacted: GetInboundOptions is a
  427. // shared, admin-wide list used to fill dropdowns, not a place a live tunnel
  428. // secret needs to travel — the frontend's own AwgServerOptionSchema never
  429. // reads it, so nothing is lost by not sending it, and it shouldn't widen the
  430. // blast radius of a log capture, proxy cache, or browser devtools screenshot.
  431. func inboundAmneziaWGServer(protocol string, settings string) *amneziawg.ServerSettings {
  432. if protocol != string(model.AmneziaWG) || strings.TrimSpace(settings) == "" {
  433. return nil
  434. }
  435. var parsed amneziawg.InboundSettings
  436. if err := json.Unmarshal([]byte(settings), &parsed); err != nil || parsed.Server == nil {
  437. return nil
  438. }
  439. redacted := *parsed.Server
  440. redacted.PrivateKey = ""
  441. return &redacted
  442. }
  443. // inboundMtprotoDomain returns the inbound-level FakeTLS default domain, used by
  444. // the clients UI to seed a new mtproto client's secret with the right fronting
  445. // hostname.
  446. func inboundMtprotoDomain(protocol string, settings string) string {
  447. if protocol != string(model.MTProto) || strings.TrimSpace(settings) == "" {
  448. return ""
  449. }
  450. var parsed struct {
  451. FakeTLSDomain string `json:"fakeTlsDomain"`
  452. }
  453. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  454. return ""
  455. }
  456. return strings.TrimSpace(parsed.FakeTLSDomain)
  457. }
  458. // GetAllInbounds retrieves all inbounds with client stats.
  459. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  460. db := database.GetDB()
  461. var inbounds []*model.Inbound
  462. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  463. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  464. return nil, err
  465. }
  466. s.enrichClientStats(db, inbounds)
  467. return inbounds, nil
  468. }
  469. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  470. db := database.GetDB()
  471. var inbounds []*model.Inbound
  472. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  473. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  474. return nil, err
  475. }
  476. return inbounds, nil
  477. }
  478. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  479. return ParseInboundSettingsClients(inbound.Settings)
  480. }
  481. // GetClientsBySubId returns the inbound's clients with the given subscription
  482. // id, resolved from the normalized clients tables (the same source the running
  483. // Xray users are built from) instead of parsing the settings JSON blob.
  484. func (s *InboundService) GetClientsBySubId(inboundId int, subId string) ([]model.Client, error) {
  485. return s.clientService.ListForInboundBySubId(nil, inboundId, subId)
  486. }
  487. func (s *InboundService) GetAllEmails() ([]string, error) {
  488. db := database.GetDB()
  489. var emails []string
  490. query := fmt.Sprintf(
  491. "SELECT DISTINCT %s %s",
  492. database.JSONFieldText("client.value", "email"),
  493. database.JSONClientsFromInbound(),
  494. )
  495. if err := db.Raw(query).Scan(&emails).Error; err != nil {
  496. return nil, err
  497. }
  498. return emails, nil
  499. }
  500. // emailSubIDsForClients returns lower(email)→subId for just the emails being
  501. // checked. One clients row owns an email's identity, so the answer no longer
  502. // needs a scan of every inbound's settings JSON (#6252).
  503. func (s *InboundService) emailSubIDsForClients(clients []model.Client) (map[string]string, error) {
  504. want := make(map[string]struct{}, len(clients))
  505. for i := range clients {
  506. if email := strings.ToLower(strings.TrimSpace(clients[i].Email)); email != "" {
  507. want[email] = struct{}{}
  508. }
  509. }
  510. result := make(map[string]string, len(want))
  511. if len(want) == 0 {
  512. return result, nil
  513. }
  514. lowered := make([]string, 0, len(want))
  515. for email := range want {
  516. lowered = append(lowered, email)
  517. }
  518. db := database.GetDB()
  519. for _, batch := range chunkStrings(lowered, sqlInChunk) {
  520. var rows []struct {
  521. Email string
  522. SubID string `gorm:"column:sub_id"`
  523. }
  524. err := db.Model(&model.ClientRecord{}).
  525. Select("email, sub_id").
  526. Where("LOWER(email) IN ?", batch).
  527. Scan(&rows).Error
  528. if err != nil {
  529. return nil, err
  530. }
  531. for _, r := range rows {
  532. result[strings.ToLower(r.Email)] = r.SubID
  533. }
  534. }
  535. return result, nil
  536. }
  537. // normalizeStreamSettings clears StreamSettings for protocols that don't use it.
  538. // Only vmess, vless, trojan, shadowsocks, hysteria, wireguard, and tunnel
  539. // protocols use streamSettings (wireguard for finalmask UDP masks and sockopt on
  540. // its listener; tunnel for sockopt, notably sockopt.tproxy for its TProxy/redirect
  541. // mode). Streams keyed on "method" — xray-core v26.7.11's preferred alias for
  542. // "network" — are canonicalized to "network", which every panel reader (link
  543. // generation, port-conflict detection, flow eligibility) keys on.
  544. func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
  545. protocolsWithStream := map[model.Protocol]bool{
  546. model.VMESS: true,
  547. model.VLESS: true,
  548. model.Trojan: true,
  549. model.Shadowsocks: true,
  550. model.Hysteria: true,
  551. model.WireGuard: true,
  552. model.Tunnel: true,
  553. }
  554. if !protocolsWithStream[inbound.Protocol] {
  555. inbound.StreamSettings = ""
  556. return
  557. }
  558. inbound.StreamSettings = canonicalizeStreamNetworkKey(inbound.StreamSettings)
  559. }
  560. // canonicalizeStreamNetworkKey rewrites a streamSettings JSON that names its
  561. // transport under "method" to the panel-canonical "network" key. When both
  562. // keys are present, "method" wins — matching xray-core's own precedence.
  563. func canonicalizeStreamNetworkKey(streamSettings string) string {
  564. if streamSettings == "" {
  565. return streamSettings
  566. }
  567. var stream map[string]any
  568. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  569. return streamSettings
  570. }
  571. method, ok := stream["method"].(string)
  572. if !ok || method == "" {
  573. return streamSettings
  574. }
  575. stream["network"] = method
  576. delete(stream, "method")
  577. out, err := json.MarshalIndent(stream, "", " ")
  578. if err != nil {
  579. return streamSettings
  580. }
  581. return string(out)
  582. }
  583. // validateInboundTLSCertificates rejects incomplete TLS credentials before a save
  584. // can restart Xray. File paths belong to the node, so only presence is checked.
  585. func validateInboundTLSCertificates(streamSettings string) error {
  586. if strings.TrimSpace(streamSettings) == "" {
  587. return nil
  588. }
  589. var stream struct {
  590. Security string `json:"security"`
  591. TLSSettings json.RawMessage `json:"tlsSettings"`
  592. }
  593. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  594. return common.NewError("Invalid inbound stream settings: ", err)
  595. }
  596. if !strings.EqualFold(stream.Security, "tls") {
  597. return nil
  598. }
  599. var settings struct {
  600. Certificates []struct {
  601. CertificateFile string `json:"certificateFile"`
  602. KeyFile string `json:"keyFile"`
  603. Certificate []string `json:"certificate"`
  604. Key []string `json:"key"`
  605. Usage string `json:"usage"`
  606. } `json:"certificates"`
  607. }
  608. if len(stream.TLSSettings) > 0 {
  609. if err := json.Unmarshal(stream.TLSSettings, &settings); err != nil {
  610. return common.NewError("Invalid inbound TLS settings: ", err)
  611. }
  612. }
  613. hasServerCertificate := false
  614. for i, cert := range settings.Certificates {
  615. // Match Xray's file-over-inline precedence for each credential.
  616. certificate := cert.CertificateFile
  617. if certificate == "" {
  618. certificate = strings.Join(cert.Certificate, "\n")
  619. }
  620. if strings.TrimSpace(certificate) == "" {
  621. return common.NewErrorf("TLS certificate %d is missing. Configure a certificate file path or certificate content before saving the inbound.", i+1)
  622. }
  623. if strings.EqualFold(cert.Usage, "verify") {
  624. continue
  625. }
  626. key := cert.KeyFile
  627. if key == "" {
  628. key = strings.Join(cert.Key, "\n")
  629. }
  630. if strings.TrimSpace(key) == "" {
  631. return common.NewErrorf("TLS certificate %d is missing its private key. Configure a private key file path or private key content before saving the inbound.", i+1)
  632. }
  633. hasServerCertificate = true
  634. }
  635. if !hasServerCertificate {
  636. return common.NewError("TLS requires a server certificate and private key. Configure an encipherment or issue certificate before saving the inbound.")
  637. }
  638. return nil
  639. }
  640. // finalMaskRealityTcpMasks returns the stream's finalmask.tcp masks when the
  641. // stream uses REALITY security, or nil otherwise. A non-empty result means
  642. // this stream carries the finalmask+REALITY combination that panics
  643. // Xray-core (see https://github.com/XTLS/Xray-core/issues/6453): finalmask
  644. // wraps the connection before REALITY's handshake ever sees it, and
  645. // reality.Server() does an unchecked type assertion assuming a raw
  646. // *net.TCPConn, which panics once finalmask is in front of it.
  647. //
  648. // Only finalmask.tcp matters here — TcpmaskManager (the thing that wraps the
  649. // listener ahead of REALITY's handshake, in xray-core's own
  650. // transport/internet/memory_settings.go) is only constructed when tcp masks
  651. // are present; a finalmask.udp-only config never touches the TCP accept path
  652. // REALITY runs on, so it doesn't reproduce this panic and shouldn't be
  653. // rejected.
  654. func finalMaskRealityTcpMasks(stream map[string]any) []any {
  655. if stream["security"] != "reality" {
  656. return nil
  657. }
  658. finalmask, ok := stream["finalmask"].(map[string]any)
  659. if !ok {
  660. return nil
  661. }
  662. tcp, _ := finalmask["tcp"].([]any)
  663. return tcp
  664. }
  665. // validateFinalMaskRealityCombo rejects finalmask.tcp configured together
  666. // with REALITY security at save time. Upstream has confirmed this
  667. // combination will be documented as unsupported rather than made graceful,
  668. // so the panel must not let it be saved.
  669. func validateFinalMaskRealityCombo(streamSettings string) error {
  670. if streamSettings == "" {
  671. return nil
  672. }
  673. var stream map[string]any
  674. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  675. return nil
  676. }
  677. if len(finalMaskRealityTcpMasks(stream)) == 0 {
  678. return nil
  679. }
  680. return common.NewError("Finalmask is not supported with REALITY security — it crashes Xray-core on the first connection (see XTLS/Xray-core#6453). Remove the finalmask configuration or switch security to tls/none.")
  681. }
  682. var xmcProfileUsernamePattern = regexp.MustCompile(`^[A-Za-z0-9_]{3,16}$`)
  683. // xmcMaskProfilesComplete reports whether an xmc finalmask carries the signed
  684. // Minecraft session profiles xray-core has required since v26.7.28 (#6487).
  685. // The core replaced the old `usernames` string list with `profiles` objects
  686. // and removed the "default to Dream when empty" fallback, so a mask still on
  687. // the legacy shape — or one whose profiles are incomplete — now fails
  688. // conf.XMC.Build() and takes the entire config down with it rather than
  689. // degrading that one inbound.
  690. //
  691. // The texture fields are a signed blob only Mojang's session server can issue
  692. // (resolve the UUID by username, then fetch the profile with unsigned=false),
  693. // so the panel cannot synthesize a valid profile from a legacy username; an
  694. // incomplete mask can only be reported or dropped.
  695. func xmcMaskProfilesComplete(mask map[string]any) bool {
  696. settings, ok := mask["settings"].(map[string]any)
  697. if !ok {
  698. return false
  699. }
  700. profiles, _ := settings["profiles"].([]any)
  701. if len(profiles) == 0 {
  702. return false
  703. }
  704. for _, entry := range profiles {
  705. profile, ok := entry.(map[string]any)
  706. if !ok {
  707. return false
  708. }
  709. username, _ := profile["username"].(string)
  710. if !xmcProfileUsernamePattern.MatchString(username) {
  711. return false
  712. }
  713. id, _ := profile["uuid"].(string)
  714. if _, err := uuid.Parse(id); err != nil {
  715. return false
  716. }
  717. if value, _ := profile["texturesValue"].(string); value == "" {
  718. return false
  719. }
  720. if signature, _ := profile["texturesSignature"].(string); signature == "" {
  721. return false
  722. }
  723. }
  724. return true
  725. }
  726. // isIncompleteXmcMask reports whether a finalmask.tcp entry is an xmc mask
  727. // xray-core would refuse to build.
  728. func isIncompleteXmcMask(entry any) bool {
  729. mask, ok := entry.(map[string]any)
  730. if !ok {
  731. return false
  732. }
  733. if maskType, _ := mask["type"].(string); maskType != "xmc" {
  734. return false
  735. }
  736. return !xmcMaskProfilesComplete(mask)
  737. }
  738. // incompleteXmcMaskCount counts the stream's xmc finalmask entries that
  739. // xray-core would refuse to build.
  740. func incompleteXmcMaskCount(stream map[string]any) int {
  741. finalmask, ok := stream["finalmask"].(map[string]any)
  742. if !ok {
  743. return 0
  744. }
  745. tcp, _ := finalmask["tcp"].([]any)
  746. count := 0
  747. for _, entry := range tcp {
  748. if isIncompleteXmcMask(entry) {
  749. count++
  750. }
  751. }
  752. return count
  753. }
  754. // stripIncompleteXmcMasks removes every xmc finalmask entry xray-core would
  755. // refuse to build, returning how many were dropped, and clears the finalmask
  756. // object once nothing is left in it.
  757. //
  758. // AddInbound and UpdateInbound reject an incomplete mask at save time, but a
  759. // row that never went through those paths — an upgrade from a panel predating
  760. // v26.7.28, node sync, a restored backup, a direct DB edit — would otherwise
  761. // fail the whole config build and keep every other inbound offline too.
  762. // Dropping only the offending mask degrades that one inbound instead, which
  763. // the accompanying warning tells the admin to reconfigure.
  764. func stripIncompleteXmcMasks(stream map[string]any) int {
  765. finalmask, ok := stream["finalmask"].(map[string]any)
  766. if !ok {
  767. return 0
  768. }
  769. tcp, _ := finalmask["tcp"].([]any)
  770. if len(tcp) == 0 {
  771. return 0
  772. }
  773. kept := make([]any, 0, len(tcp))
  774. dropped := 0
  775. for _, entry := range tcp {
  776. if isIncompleteXmcMask(entry) {
  777. dropped++
  778. continue
  779. }
  780. kept = append(kept, entry)
  781. }
  782. if dropped == 0 {
  783. return 0
  784. }
  785. if len(kept) == 0 {
  786. delete(finalmask, "tcp")
  787. } else {
  788. finalmask["tcp"] = kept
  789. }
  790. if len(finalmask) == 0 {
  791. delete(stream, "finalmask")
  792. }
  793. return dropped
  794. }
  795. // dropEmptyRandPackets removes the leftover empty "packet" from finalmask
  796. // items that also carry a rand, and reports how many it cleared.
  797. //
  798. // xray-core treats even an empty array as a packet, and every item kind is
  799. // exclusive: noise refuses "len(item.Packet) > 0 && item.Rand.To > 0" and
  800. // header-custom refuses "exactly one item kind must be set". Either error
  801. // fails the whole config build, so one such item keeps every inbound offline.
  802. // The panel's mask editor wrote that pair whenever an item was switched to the
  803. // rand-driven array kind, so stored rows carry it; clearing an empty packet
  804. // changes nothing about the mask the admin configured.
  805. func dropEmptyRandPackets(node any) int {
  806. switch value := node.(type) {
  807. case map[string]any:
  808. cleared := 0
  809. if packet, ok := value["packet"].([]any); ok && len(packet) == 0 && randIsSet(value["rand"]) {
  810. delete(value, "packet")
  811. cleared++
  812. }
  813. for _, child := range value {
  814. cleared += dropEmptyRandPackets(child)
  815. }
  816. return cleared
  817. case []any:
  818. cleared := 0
  819. for _, child := range value {
  820. cleared += dropEmptyRandPackets(child)
  821. }
  822. return cleared
  823. default:
  824. return 0
  825. }
  826. }
  827. // randIsSet reports whether a finalmask item's rand selects a random packet.
  828. // It is a number on header-custom items and a dash-range string on noise ones.
  829. func randIsSet(value any) bool {
  830. switch rand := value.(type) {
  831. case float64:
  832. return rand > 0
  833. case string:
  834. return rand != "" && rand != "0" && rand != "0-0"
  835. default:
  836. return false
  837. }
  838. }
  839. // validateFinalMaskXmcProfiles rejects an xmc finalmask without complete
  840. // profiles at save time, so the admin gets a targeted error instead of a core
  841. // that refuses to start (or, after GetXrayConfig heals it, an inbound quietly
  842. // serving without the obfuscation they configured).
  843. func validateFinalMaskXmcProfiles(streamSettings string) error {
  844. if streamSettings == "" {
  845. return nil
  846. }
  847. var stream map[string]any
  848. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  849. return nil
  850. }
  851. if incompleteXmcMaskCount(stream) == 0 {
  852. return nil
  853. }
  854. return common.NewError("XMC finalmask requires at least one complete Minecraft profile — each needs a username (3-16 of A-Z a-z 0-9 _), a UUID, and both texture fields from Mojang's session server (XTLS/Xray-core#6487). Complete the profiles or remove the XMC mask.")
  855. }
  856. // normalizeMtprotoSecret rebuilds every mtproto client's FakeTLS secret so it is
  857. // always valid before the row is persisted, and drops the vestigial inbound-level
  858. // secret and adTag: MTProto is multi-client, so mtg and every share link read
  859. // only the per-client values. Leaving an inbound-level secret behind is what
  860. // produced stale links that failed with "incorrect client random".
  861. func (s *InboundService) normalizeMtprotoSecret(inbound *model.Inbound) {
  862. if inbound.Protocol != model.MTProto {
  863. return
  864. }
  865. if stripped, ok := model.StripMtprotoInboundSecret(inbound.Settings); ok {
  866. inbound.Settings = stripped
  867. }
  868. if stripped, ok := model.StripMtprotoInboundAdTag(inbound.Settings); ok {
  869. inbound.Settings = stripped
  870. }
  871. if healed, ok := model.HealMtprotoClientSecrets(inbound.Settings); ok {
  872. inbound.Settings = healed
  873. }
  874. }
  875. // mtprotoRoutesThroughXray reports whether an mtproto inbound is configured to
  876. // egress through the core's router (the loopback SOCKS bridge in §xray.go).
  877. func mtprotoRoutesThroughXray(inbound *model.Inbound) bool {
  878. if inbound == nil || inbound.Protocol != model.MTProto {
  879. return false
  880. }
  881. var parsed struct {
  882. RouteThroughXray bool `json:"routeThroughXray"`
  883. }
  884. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
  885. return false
  886. }
  887. return parsed.RouteThroughXray
  888. }
  889. func settingsRouteXrayPort(parsed map[string]any) int {
  890. switch v := parsed["routeXrayPort"].(type) {
  891. case float64:
  892. return int(v)
  893. case int:
  894. return v
  895. case json.Number:
  896. if n, err := v.Int64(); err == nil {
  897. return int(n)
  898. }
  899. }
  900. return 0
  901. }
  902. func parseRouteXrayPort(settings string) int {
  903. if settings == "" {
  904. return 0
  905. }
  906. var parsed map[string]any
  907. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  908. return 0
  909. }
  910. return settingsRouteXrayPort(parsed)
  911. }
  912. // normalizeMtprotoXrayPort guarantees a routed mtproto inbound carries a stable
  913. // loopback egress port in its settings, so the generated Xray SOCKS bridge and
  914. // the mtg sidecar agree on where mtg dials out. The port is backend-owned: it is
  915. // allocated once when routing is first enabled and preserved across edits
  916. // (carried over from oldSettings, which wins over any value the client echoed
  917. // back). When routing is off it — together with the now-inert outbound
  918. // selection — is stripped so a disabled bridge leaves nothing stale behind.
  919. //
  920. // It returns an error when an egress port cannot be allocated or persisted, so
  921. // the caller refuses the save rather than storing a routed-but-portless inbound,
  922. // which would otherwise route no traffic and have its mtg metrics skipped (see
  923. // mtproto_job) — silently losing its accounting.
  924. func (s *InboundService) normalizeMtprotoXrayPort(inbound *model.Inbound, oldSettings string) error {
  925. if inbound.Protocol != model.MTProto {
  926. return nil
  927. }
  928. var parsed map[string]any
  929. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed == nil {
  930. return nil
  931. }
  932. routed, _ := parsed["routeThroughXray"].(bool)
  933. if !routed {
  934. _, hadPort := parsed["routeXrayPort"]
  935. _, hadTag := parsed["outboundTag"]
  936. if !hadPort && !hadTag {
  937. return nil
  938. }
  939. delete(parsed, "routeXrayPort")
  940. delete(parsed, "outboundTag")
  941. if bs, err := json.MarshalIndent(parsed, "", " "); err == nil {
  942. inbound.Settings = string(bs)
  943. } else {
  944. logger.Warning("mtproto: failed to marshal settings after disabling routing:", err)
  945. }
  946. return nil
  947. }
  948. // Prefer the already-stored port (carried across edits), then any value the
  949. // client sent, then allocate a fresh one.
  950. port := parseRouteXrayPort(oldSettings)
  951. if port <= 0 {
  952. port = settingsRouteXrayPort(parsed)
  953. }
  954. if port <= 0 {
  955. allocated, err := mtproto.FreeLocalPort()
  956. if err != nil {
  957. return common.NewError("mtproto: could not allocate an Xray egress port:", err)
  958. }
  959. port = allocated
  960. }
  961. if settingsRouteXrayPort(parsed) == port {
  962. return nil
  963. }
  964. parsed["routeXrayPort"] = port
  965. bs, err := json.MarshalIndent(parsed, "", " ")
  966. if err != nil {
  967. return common.NewError("mtproto: could not persist the Xray egress port:", err)
  968. }
  969. inbound.Settings = string(bs)
  970. return nil
  971. }
  972. // AddInbound creates a new inbound configuration.
  973. // It validates port uniqueness, client email uniqueness, and required fields,
  974. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  975. // Returns the created inbound, whether Xray needs restart, and any error.
  976. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  977. inbound.Id = 0
  978. legacyShareAddr := legacyMtprotoShareAddr(inbound)
  979. inbound.TrafficResetDay = normalizeTrafficResetDay(inbound.TrafficResetDay)
  980. // Normalize streamSettings based on protocol
  981. s.normalizeStreamSettings(inbound)
  982. if !s.FromNodeSync {
  983. if err := validateInboundTLSCertificates(inbound.StreamSettings); err != nil {
  984. return inbound, false, err
  985. }
  986. }
  987. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  988. return inbound, false, err
  989. }
  990. if err := validateFinalMaskXmcProfiles(inbound.StreamSettings); err != nil {
  991. return inbound, false, err
  992. }
  993. s.normalizeMtprotoSecret(inbound)
  994. if err := s.normalizeMtprotoXrayPort(inbound, ""); err != nil {
  995. return inbound, false, err
  996. }
  997. if err := s.normalizeAmneziaWGSettings(inbound); err != nil {
  998. return inbound, false, err
  999. }
  1000. if inbound.NodeID != nil && !isNodeEligibleProtocol(inbound.Protocol) {
  1001. return inbound, false, common.NewErrorf("%s inbounds cannot be assigned to a node", inbound.Protocol)
  1002. }
  1003. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  1004. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1005. return inbound, false, err
  1006. }
  1007. tag, err := s.resolveInboundTag(inbound, 0)
  1008. if err != nil {
  1009. return inbound, false, err
  1010. }
  1011. inbound.Tag = tag
  1012. clients, err := s.GetClients(inbound)
  1013. if err != nil {
  1014. return inbound, false, err
  1015. }
  1016. existEmail, err := s.clientService.checkEmailsExistForClients(s, clients)
  1017. if err != nil {
  1018. return inbound, false, err
  1019. }
  1020. if existEmail != "" {
  1021. return inbound, false, common.NewError("Duplicate email:", existEmail)
  1022. }
  1023. if inbound.DisableFlow {
  1024. if stripped, changed := stripClientFlows(inbound.Settings); changed {
  1025. inbound.Settings = stripped
  1026. }
  1027. for i := range clients {
  1028. clients[i].Flow = ""
  1029. }
  1030. }
  1031. // Ensure created_at and updated_at on clients in settings
  1032. if len(clients) > 0 {
  1033. var settings map[string]any
  1034. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  1035. now := time.Now().Unix() * 1000
  1036. updatedClients := make([]model.Client, 0, len(clients))
  1037. for _, c := range clients {
  1038. if c.CreatedAt == 0 {
  1039. c.CreatedAt = now
  1040. }
  1041. c.UpdatedAt = now
  1042. updatedClients = append(updatedClients, c)
  1043. }
  1044. settings["clients"] = updatedClients
  1045. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  1046. inbound.Settings = string(bs)
  1047. } else {
  1048. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  1049. }
  1050. } else if err2 != nil {
  1051. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  1052. }
  1053. }
  1054. // Defensively fix any Shadowsocks-2022 client PSK whose length doesn't match
  1055. // the inbound method (e.g. an API caller supplied a wrong-size key).
  1056. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1057. inbound.Settings = normalized
  1058. }
  1059. // Secure client ID
  1060. for _, client := range clients {
  1061. switch inbound.Protocol {
  1062. case "trojan":
  1063. if client.Password == "" {
  1064. return inbound, false, common.NewError("empty client ID")
  1065. }
  1066. case "shadowsocks":
  1067. if client.Email == "" {
  1068. return inbound, false, common.NewError("empty client ID")
  1069. }
  1070. case "hysteria":
  1071. if client.Auth == "" {
  1072. return inbound, false, common.NewError("empty client ID")
  1073. }
  1074. case "wireguard", "amneziawg":
  1075. if client.PublicKey == "" {
  1076. return inbound, false, common.NewError("wireguard client requires a key")
  1077. }
  1078. case "mtproto":
  1079. if client.Secret == "" {
  1080. return inbound, false, common.NewError("mtproto client requires a secret")
  1081. }
  1082. if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
  1083. return inbound, false, common.NewError("mtproto client ad tag must be 32 hex characters")
  1084. }
  1085. default:
  1086. if client.ID == "" {
  1087. return inbound, false, common.NewError("empty client ID")
  1088. }
  1089. }
  1090. }
  1091. needRestart := false
  1092. var postCommitApply func()
  1093. err = runSerializedTx(func(tx *gorm.DB) error {
  1094. conflict, cErr := checkPortConflictTx(tx, inbound, 0)
  1095. if cErr != nil {
  1096. return cErr
  1097. }
  1098. if conflict != nil {
  1099. return common.NewError(conflict.String())
  1100. }
  1101. markDirty := false
  1102. if err := tx.Omit("ClientStats").Save(inbound).Error; err != nil {
  1103. return err
  1104. }
  1105. // The relay port is derived from the id, only known after Save; checkPortConflictTx
  1106. // ran the reverse-direction check above with ignoreId==0, so it couldn't yet.
  1107. if inbound.Protocol == model.AmneziaWG {
  1108. if amneziawgnet.SOCKSPortForInbound(inbound.Id) > 65535 {
  1109. return common.NewErrorf("amneziawg: inbound id %d exceeds the relay port window (ids above %d are not supported)",
  1110. inbound.Id, 65535-amneziawgnet.SOCKSBasePort)
  1111. }
  1112. conflict, cErr := checkAmneziawgnetSocksReverseConflict(tx, inbound.Id)
  1113. if cErr != nil {
  1114. return cErr
  1115. }
  1116. if conflict != nil {
  1117. return common.NewError(conflict.String())
  1118. }
  1119. }
  1120. // Emails seeded here (import's ClientStats, e.g. the controller's forced
  1121. // Enable=true on every imported stat row) are authoritative for this call
  1122. // and must not be clobbered by the AddClientStat loop below, which derives
  1123. // its enable/total/expiry/reset from Settings.clients[] instead — a second,
  1124. // possibly-stale source for the same columns on a plain (non-import) create.
  1125. statEmails := make(map[string]bool, len(inbound.ClientStats))
  1126. for i := range inbound.ClientStats {
  1127. if inbound.ClientStats[i].Email == "" {
  1128. continue
  1129. }
  1130. statEmails[inbound.ClientStats[i].Email] = true
  1131. inbound.ClientStats[i].Id = 0
  1132. inbound.ClientStats[i].InboundId = inbound.Id
  1133. if err := tx.Clauses(clause.OnConflict{
  1134. Columns: []clause.Column{{Name: "email"}},
  1135. DoNothing: true,
  1136. }).Create(&inbound.ClientStats[i]).Error; err != nil {
  1137. return err
  1138. }
  1139. }
  1140. for _, client := range clients {
  1141. if statEmails[client.Email] {
  1142. continue
  1143. }
  1144. if err := s.AddClientStat(tx, inbound.Id, &client); err != nil {
  1145. return err
  1146. }
  1147. }
  1148. if err := s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  1149. return err
  1150. }
  1151. if _, err := database.CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  1152. return err
  1153. }
  1154. if err := database.CreateHostFromMtprotoCustomShareAddr(tx, inbound.Id, legacyShareAddr); err != nil {
  1155. return err
  1156. }
  1157. if inbound.NodeID != nil {
  1158. nodeID := *inbound.NodeID
  1159. if err := (&NodeService{}).EnsureInboundTagAllowedTx(tx, nodeID, inbound.Tag); err != nil {
  1160. return err
  1161. }
  1162. }
  1163. if inbound.Enable {
  1164. if inbound.NodeID != nil {
  1165. markDirty = true
  1166. } else {
  1167. rt, push, _, perr := s.nodePushPlan(inbound)
  1168. if perr != nil {
  1169. return perr
  1170. }
  1171. if push {
  1172. payload := inbound
  1173. pushable := true
  1174. if inbound.Protocol == model.MTProto {
  1175. if built, bErr := s.buildInboundForLocalRuntime(tx, inbound); bErr == nil {
  1176. payload = built
  1177. } else {
  1178. logger.Debug("Unable to prepare runtime inbound config:", bErr)
  1179. pushable = false
  1180. }
  1181. }
  1182. if pushable {
  1183. postCommitApply = func() {
  1184. if err1 := rt.AddInbound(context.Background(), payload); err1 == nil {
  1185. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  1186. } else {
  1187. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  1188. needRestart = true
  1189. }
  1190. }
  1191. }
  1192. }
  1193. }
  1194. }
  1195. if markDirty && inbound.NodeID != nil {
  1196. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1197. }
  1198. return nil
  1199. })
  1200. if err != nil {
  1201. return inbound, false, err
  1202. }
  1203. if postCommitApply != nil {
  1204. postCommitApply()
  1205. }
  1206. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  1207. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  1208. // in the generated config, so force a regen to wire it in.
  1209. if mtprotoRoutesThroughXray(inbound) {
  1210. needRestart = true
  1211. }
  1212. return inbound, needRestart, err
  1213. }
  1214. func (s *InboundService) DelInbound(id int) (bool, error) {
  1215. db := database.GetDB()
  1216. needRestart := false
  1217. var postCommitApply func()
  1218. var ib model.Inbound
  1219. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  1220. if loadErr == nil {
  1221. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  1222. if shouldPushToRuntime {
  1223. if ib.NodeID != nil {
  1224. rt, push, _, perr := s.nodePushPlan(&ib)
  1225. if perr != nil {
  1226. logger.Warning("DelInbound: node runtime lookup failed, deleting central row anyway:", perr)
  1227. } else if push {
  1228. postCommitApply = func() {
  1229. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  1230. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  1231. } else {
  1232. logger.Warning("DelInbound on", rt.Name(), "failed after commit:", err1)
  1233. }
  1234. }
  1235. }
  1236. } else {
  1237. rt, push, _, perr := s.nodePushPlan(&ib)
  1238. if perr != nil {
  1239. logger.Warning("DelInbound: runtime lookup failed, deleting central row anyway:", perr)
  1240. } else if push {
  1241. postCommitApply = func() {
  1242. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  1243. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  1244. } else {
  1245. logger.Warning("DelInbound on", rt.Name(), "failed after commit:", err1)
  1246. needRestart = true
  1247. }
  1248. }
  1249. } else {
  1250. needRestart = true
  1251. }
  1252. }
  1253. } else {
  1254. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  1255. }
  1256. } else {
  1257. logger.Debug("DelInbound: inbound not found, id:", id)
  1258. }
  1259. if err := db.Transaction(func(tx *gorm.DB) error {
  1260. if err := s.clientService.DetachInbound(tx, id); err != nil {
  1261. return err
  1262. }
  1263. if err := tx.Delete(model.Inbound{}, id).Error; err != nil {
  1264. return err
  1265. }
  1266. if err := tx.Where("inbound_id = ?", id).Delete(&model.Host{}).Error; err != nil {
  1267. return err
  1268. }
  1269. // Drop the deleted inbound from any sub-balancer that selects it; a
  1270. // dangling id would emit a member no subscriber can resolve (#5648).
  1271. var balancers []model.SubBalancer
  1272. if err := tx.Find(&balancers).Error; err != nil {
  1273. return err
  1274. }
  1275. for i := range balancers {
  1276. before := balancers[i].InboundIds
  1277. balancers[i].InboundIds = slices.DeleteFunc(before, func(b int) bool { return b == id })
  1278. if len(balancers[i].InboundIds) == len(before) {
  1279. continue
  1280. }
  1281. if err := tx.Save(&balancers[i]).Error; err != nil {
  1282. return err
  1283. }
  1284. }
  1285. if loadErr == nil && ib.NodeID != nil {
  1286. return (&NodeService{}).MarkNodeDirtyTx(tx, *ib.NodeID)
  1287. }
  1288. return nil
  1289. }); err != nil {
  1290. return needRestart, err
  1291. }
  1292. if postCommitApply != nil {
  1293. postCommitApply()
  1294. }
  1295. if loadErr == nil && ib.Tag != "" {
  1296. if routingChanged, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(ib.Tag); syncErr != nil {
  1297. logger.Warning("DelInbound: sync routing on inbound delete failed:", syncErr)
  1298. } else if routingChanged {
  1299. needRestart = true
  1300. }
  1301. }
  1302. if !database.IsPostgres() {
  1303. var count int64
  1304. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  1305. return needRestart, err
  1306. }
  1307. if count == 0 {
  1308. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  1309. return needRestart, err
  1310. }
  1311. }
  1312. }
  1313. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  1314. if mtprotoRoutesThroughXray(&ib) {
  1315. needRestart = true
  1316. }
  1317. return needRestart, nil
  1318. }
  1319. type BulkDelInboundResult struct {
  1320. Deleted int `json:"deleted"`
  1321. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  1322. }
  1323. type BulkDelInboundReport struct {
  1324. Id int `json:"id"`
  1325. Reason string `json:"reason"`
  1326. }
  1327. // DelInbounds removes every inbound in the list, reusing the single-delete
  1328. // path per id. Failures are recorded in Skipped and processing continues for
  1329. // the rest; the aggregated needRestart is returned so the caller restarts
  1330. // xray at most once.
  1331. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  1332. result := BulkDelInboundResult{}
  1333. needRestart := false
  1334. for _, id := range ids {
  1335. r, err := s.DelInbound(id)
  1336. if err != nil {
  1337. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  1338. continue
  1339. }
  1340. result.Deleted++
  1341. if r {
  1342. needRestart = true
  1343. }
  1344. }
  1345. return result, needRestart, nil
  1346. }
  1347. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  1348. db := database.GetDB()
  1349. inbound := &model.Inbound{}
  1350. err := db.Model(model.Inbound{}).First(inbound, id).Error
  1351. if err != nil {
  1352. return nil, err
  1353. }
  1354. return inbound, nil
  1355. }
  1356. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  1357. db := database.GetDB()
  1358. inbound := &model.Inbound{}
  1359. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  1360. if err != nil {
  1361. return nil, err
  1362. }
  1363. s.enrichClientStats(db, []*model.Inbound{inbound})
  1364. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  1365. return inbound, nil
  1366. }
  1367. // SetInboundSubSortIndex changes only the subscription sort order, so a
  1368. // reorder cannot carry a stale settings/client payload over another edit.
  1369. func (s *InboundService) SetInboundSubSortIndex(id int, index int) error {
  1370. index = normalizeSubSortIndex(index)
  1371. inbound, err := s.GetInbound(id)
  1372. if err != nil {
  1373. return err
  1374. }
  1375. if inbound.SubSortIndex == index {
  1376. return nil
  1377. }
  1378. db := database.GetDB()
  1379. if err := db.Transaction(func(tx *gorm.DB) error {
  1380. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  1381. Update("sub_sort_index", index).Error; err != nil {
  1382. return err
  1383. }
  1384. if inbound.NodeID != nil {
  1385. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1386. }
  1387. return nil
  1388. }); err != nil {
  1389. return err
  1390. }
  1391. inbound.SubSortIndex = index
  1392. if inbound.NodeID == nil {
  1393. return nil
  1394. }
  1395. rt, push, _, perr := s.nodePushPlan(inbound)
  1396. if perr != nil {
  1397. return perr
  1398. }
  1399. if push {
  1400. narrow, ok := rt.(interface {
  1401. SetInboundSubSortIndex(context.Context, *model.Inbound, int) error
  1402. })
  1403. if !ok {
  1404. return fmt.Errorf("runtime %s does not support narrow subscription ordering updates", rt.Name())
  1405. }
  1406. if err := narrow.SetInboundSubSortIndex(context.Background(), inbound, index); err != nil {
  1407. logger.Warning("SetInboundSubSortIndex: remote metadata update on", rt.Name(), "failed:", err)
  1408. }
  1409. }
  1410. return nil
  1411. }
  1412. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  1413. inbound, err := s.GetInbound(id)
  1414. if err != nil {
  1415. return false, err
  1416. }
  1417. if inbound.Enable == enable {
  1418. return false, nil
  1419. }
  1420. db := database.GetDB()
  1421. if err := db.Transaction(func(tx *gorm.DB) error {
  1422. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  1423. Update("enable", enable).Error; err != nil {
  1424. return err
  1425. }
  1426. if inbound.NodeID != nil {
  1427. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1428. }
  1429. return nil
  1430. }); err != nil {
  1431. return false, err
  1432. }
  1433. inbound.Enable = enable
  1434. needRestart := false
  1435. rt, push, _, perr := s.nodePushPlan(inbound)
  1436. if perr != nil {
  1437. return false, perr
  1438. }
  1439. // Remote nodes interpret DelInbound as a real row delete (it hits
  1440. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  1441. // switch on a remote inbound used to wipe the row entirely (#4402).
  1442. // PATCH the remote row via UpdateInbound instead — preserves the
  1443. // settings/client history and just flips the enable flag.
  1444. if inbound.NodeID != nil {
  1445. if push {
  1446. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  1447. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  1448. }
  1449. }
  1450. return false, nil
  1451. }
  1452. if mtprotoRoutesThroughXray(inbound) {
  1453. needRestart = true
  1454. }
  1455. if !push {
  1456. return true, nil
  1457. }
  1458. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  1459. !strings.Contains(err.Error(), "not found") {
  1460. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  1461. needRestart = true
  1462. }
  1463. if !enable {
  1464. return needRestart, nil
  1465. }
  1466. runtimeInbound, err := s.buildInboundForLocalRuntime(db, inbound)
  1467. if err != nil {
  1468. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  1469. return true, nil
  1470. }
  1471. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  1472. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  1473. needRestart = true
  1474. }
  1475. return needRestart, nil
  1476. }
  1477. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  1478. legacyShareAddr := legacyMtprotoShareAddr(inbound)
  1479. inbound.TrafficResetDay = normalizeTrafficResetDay(inbound.TrafficResetDay)
  1480. // Normalize streamSettings based on protocol
  1481. s.normalizeStreamSettings(inbound)
  1482. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  1483. return inbound, false, err
  1484. }
  1485. if err := validateFinalMaskXmcProfiles(inbound.StreamSettings); err != nil {
  1486. return inbound, false, err
  1487. }
  1488. s.normalizeMtprotoSecret(inbound)
  1489. if err := s.normalizeAmneziaWGSettings(inbound); err != nil {
  1490. return inbound, false, err
  1491. }
  1492. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  1493. clients, err := s.GetClients(inbound)
  1494. if err != nil {
  1495. return inbound, false, err
  1496. }
  1497. if inbound.Protocol == model.Hysteria {
  1498. for _, client := range clients {
  1499. if client.Auth == "" {
  1500. return inbound, false, common.NewError("empty client ID")
  1501. }
  1502. }
  1503. }
  1504. oldInbound, err := s.GetInbound(inbound.Id)
  1505. if err != nil {
  1506. return inbound, false, err
  1507. }
  1508. // Grandfather a row that was already stored incomplete so it stays editable;
  1509. // only a save that breaks a previously valid TLS block is refused.
  1510. if !s.FromNodeSync {
  1511. if err := validateInboundTLSCertificates(inbound.StreamSettings); err != nil {
  1512. if validateInboundTLSCertificates(oldInbound.StreamSettings) == nil {
  1513. return inbound, false, err
  1514. }
  1515. }
  1516. }
  1517. // Restore the stored NodeID before the port-conflict check so a node inbound
  1518. // stays scoped to its own node (the payload's nodeId is unreliable, often absent).
  1519. inbound.NodeID = oldInbound.NodeID
  1520. if inbound.NodeID != nil && !isNodeEligibleProtocol(inbound.Protocol) {
  1521. return inbound, false, common.NewErrorf("%s inbounds cannot be assigned to a node", inbound.Protocol)
  1522. }
  1523. // Capture the pre-edit protocol and routing state before oldInbound is
  1524. // overwritten with the new values further down, then ensure a routed
  1525. // inbound keeps a stable egress port (reusing the one already stored).
  1526. oldProtocol := oldInbound.Protocol
  1527. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  1528. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  1529. return inbound, false, err
  1530. }
  1531. tag := oldInbound.Tag
  1532. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  1533. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  1534. needRestart := false
  1535. var postCommitApply func()
  1536. txErr := runSerializedTx(func(tx *gorm.DB) error {
  1537. conflict, cErr := checkPortConflictTx(tx, inbound, inbound.Id)
  1538. if cErr != nil {
  1539. return cErr
  1540. }
  1541. if conflict != nil {
  1542. return common.NewError(conflict.String())
  1543. }
  1544. if err := s.updateClientTraffics(tx, oldInbound, inbound); err != nil {
  1545. return err
  1546. }
  1547. // Ensure created_at and updated_at exist in inbound.Settings clients
  1548. {
  1549. var oldSettings map[string]any
  1550. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1551. emailToCreated := map[string]int64{}
  1552. emailToUpdated := map[string]int64{}
  1553. if oldSettings != nil {
  1554. if oc, ok := oldSettings["clients"].([]any); ok {
  1555. for _, it := range oc {
  1556. if m, ok2 := it.(map[string]any); ok2 {
  1557. if email, ok3 := m["email"].(string); ok3 {
  1558. switch v := m["created_at"].(type) {
  1559. case float64:
  1560. emailToCreated[email] = int64(v)
  1561. case int64:
  1562. emailToCreated[email] = v
  1563. }
  1564. switch v := m["updated_at"].(type) {
  1565. case float64:
  1566. emailToUpdated[email] = int64(v)
  1567. case int64:
  1568. emailToUpdated[email] = v
  1569. }
  1570. }
  1571. }
  1572. }
  1573. }
  1574. }
  1575. var newSettings map[string]any
  1576. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  1577. now := time.Now().Unix() * 1000
  1578. if nSlice, ok := newSettings["clients"].([]any); ok {
  1579. for i := range nSlice {
  1580. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  1581. email, _ := m["email"].(string)
  1582. if _, ok3 := m["created_at"]; !ok3 {
  1583. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  1584. m["created_at"] = v
  1585. } else {
  1586. m["created_at"] = now
  1587. }
  1588. }
  1589. // Preserve client's updated_at if present; do not bump on parent inbound update
  1590. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  1591. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  1592. m["updated_at"] = v
  1593. }
  1594. }
  1595. nSlice[i] = m
  1596. }
  1597. }
  1598. newSettings["clients"] = nSlice
  1599. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  1600. inbound.Settings = string(bs)
  1601. }
  1602. }
  1603. }
  1604. }
  1605. // A Shadowsocks-2022 method change resizes the key, but existing client PSKs
  1606. // keep their old length and would be rejected by xray. Regenerate mismatched
  1607. // client keys so the inbound stays connectable.
  1608. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1609. inbound.Settings = normalized
  1610. logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
  1611. }
  1612. // Re-gate Vision flow now that the new stream/encryption is known: if this
  1613. // VLESS inbound just became flow-eligible (e.g. vlessenc was enabled on an
  1614. // XHTTP inbound), restore Vision for clients whose intended flow is Vision
  1615. // but was stripped while the inbound was ineligible.
  1616. if !inbound.DisableFlow {
  1617. if restored, changed := s.restoreVisionFlowForEligibleInbound(tx, inbound.Settings, inbound.StreamSettings, inbound.Protocol); changed {
  1618. inbound.Settings = restored
  1619. }
  1620. } else {
  1621. if stripped, changed := stripClientFlows(inbound.Settings); changed {
  1622. inbound.Settings = stripped
  1623. }
  1624. }
  1625. oldInbound.Total = inbound.Total
  1626. oldInbound.Remark = inbound.Remark
  1627. oldInbound.SubSortIndex = inbound.SubSortIndex
  1628. oldInbound.Enable = inbound.Enable
  1629. oldInbound.ExpiryTime = inbound.ExpiryTime
  1630. oldInbound.TrafficReset = inbound.TrafficReset
  1631. oldInbound.TrafficResetDay = inbound.TrafficResetDay
  1632. oldInbound.Listen = inbound.Listen
  1633. oldInbound.Port = inbound.Port
  1634. oldInbound.Protocol = inbound.Protocol
  1635. oldInbound.DisableFlow = inbound.DisableFlow
  1636. oldInbound.Settings = inbound.Settings
  1637. oldInbound.StreamSettings = inbound.StreamSettings
  1638. oldInbound.Sniffing = inbound.Sniffing
  1639. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  1640. normalizeInboundShareAddress(oldInbound)
  1641. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  1642. inbound.ShareAddr = oldInbound.ShareAddr
  1643. } else {
  1644. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1645. return err
  1646. }
  1647. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  1648. oldInbound.ShareAddr = inbound.ShareAddr
  1649. if err := database.CreateHostFromMtprotoCustomShareAddr(tx, inbound.Id, legacyShareAddr); err != nil {
  1650. return err
  1651. }
  1652. }
  1653. if oldTagWasAuto && inbound.Tag == tag {
  1654. inbound.Tag = ""
  1655. }
  1656. resolvedTag, err := s.resolveInboundTag(inbound, inbound.Id)
  1657. if err != nil {
  1658. return err
  1659. }
  1660. oldInbound.Tag = resolvedTag
  1661. inbound.Tag = oldInbound.Tag
  1662. if oldInbound.NodeID == nil {
  1663. rt, push, _, perr := s.nodePushPlan(oldInbound)
  1664. if perr != nil {
  1665. return perr
  1666. }
  1667. if !push {
  1668. needRestart = true
  1669. } else if oldProtocol == model.MTProto || oldInbound.Protocol == model.MTProto {
  1670. oldSnapshot := *oldInbound
  1671. oldSnapshot.Tag = tag
  1672. oldSnapshot.Protocol = oldProtocol
  1673. payload := oldInbound
  1674. pushable := true
  1675. if inbound.Enable {
  1676. if built, err2 := s.buildInboundForLocalRuntime(tx, oldInbound); err2 == nil {
  1677. payload = built
  1678. } else {
  1679. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1680. pushable = false
  1681. }
  1682. }
  1683. newProtocolIsMtproto := oldInbound.Protocol == model.MTProto
  1684. if pushable {
  1685. postCommitApply = func() {
  1686. if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, payload); err2 == nil {
  1687. logger.Debug("Updated inbound applied on", rt.Name(), ":", oldInbound.Tag)
  1688. } else {
  1689. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1690. if !newProtocolIsMtproto {
  1691. needRestart = true
  1692. }
  1693. }
  1694. }
  1695. }
  1696. } else {
  1697. oldSnapshot := *oldInbound
  1698. oldSnapshot.Tag = tag
  1699. var runtimeInbound *model.Inbound
  1700. if inbound.Enable {
  1701. var err2 error
  1702. runtimeInbound, err2 = s.buildInboundForLocalRuntime(tx, oldInbound)
  1703. if err2 != nil {
  1704. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1705. needRestart = true
  1706. }
  1707. }
  1708. postCommitApply = func() {
  1709. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  1710. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  1711. }
  1712. if runtimeInbound == nil {
  1713. return
  1714. }
  1715. if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  1716. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  1717. } else {
  1718. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1719. needRestart = true
  1720. }
  1721. }
  1722. }
  1723. } else {
  1724. nodeID := *oldInbound.NodeID
  1725. if err := (&NodeService{}).EnsureInboundTagAllowedTx(tx, nodeID, oldInbound.Tag); err != nil {
  1726. return err
  1727. }
  1728. }
  1729. if err := tx.Save(oldInbound).Error; err != nil {
  1730. return err
  1731. }
  1732. newClients, gcErr := s.GetClients(oldInbound)
  1733. if gcErr != nil {
  1734. return gcErr
  1735. }
  1736. if err := s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  1737. return err
  1738. }
  1739. if oldInbound.NodeID != nil {
  1740. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID); err != nil {
  1741. return err
  1742. }
  1743. }
  1744. // (Re)generate the Xray config whenever routing was or is now enabled, so
  1745. // the egress SOCKS bridge is added, moved, or dropped to match the new
  1746. // settings.
  1747. if mtprotoRoutesThroughXray(inbound) || oldRoutedMtproto {
  1748. needRestart = true
  1749. }
  1750. return nil
  1751. })
  1752. if txErr != nil {
  1753. return inbound, false, txErr
  1754. }
  1755. if postCommitApply != nil {
  1756. postCommitApply()
  1757. }
  1758. // After the rename is committed, point any routing rules / loopback outbounds
  1759. // in xrayTemplateConfig at the new tag (oldInbound.Tag now holds the resolved
  1760. // new tag; tag holds the pre-edit one). Done post-commit so a sync failure
  1761. // can't roll back the inbound edit.
  1762. if tag != oldInbound.Tag {
  1763. if routingChanged, syncErr := (&XraySettingService{}).PropagateInboundTagRename(tag, oldInbound.Tag); syncErr != nil {
  1764. logger.Warning("UpdateInbound: sync routing on tag rename failed:", syncErr)
  1765. } else if routingChanged {
  1766. needRestart = true
  1767. }
  1768. }
  1769. return inbound, needRestart, nil
  1770. }
  1771. // A node mirrors this payload into its own DB, so every client must survive:
  1772. // filtering one out makes the node delete it, and the master then mirrors that.
  1773. func (s *InboundService) buildInboundForNodePush(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1774. if inbound == nil {
  1775. return nil, fmt.Errorf("inbound is nil")
  1776. }
  1777. built := *inbound
  1778. settings := map[string]any{}
  1779. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1780. return nil, err
  1781. }
  1782. if !inboundCanHostFallbacks(inbound) {
  1783. return &built, nil
  1784. }
  1785. fallbacks, err := s.fallbackService.BuildFallbacksJSON(tx, inbound.Id)
  1786. if err != nil {
  1787. return nil, err
  1788. }
  1789. if len(fallbacks) == 0 {
  1790. return &built, nil
  1791. }
  1792. generic := make([]any, 0, len(fallbacks))
  1793. for _, f := range fallbacks {
  1794. generic = append(generic, f)
  1795. }
  1796. settings["fallbacks"] = generic
  1797. modifiedSettings, mErr := json.MarshalIndent(settings, "", " ")
  1798. if mErr != nil {
  1799. return nil, mErr
  1800. }
  1801. built.Settings = string(modifiedSettings)
  1802. return &built, nil
  1803. }
  1804. // Strips disabled clients on top of the node payload. Safe only because the
  1805. // target here is an in-memory Xray/mtg config, not another panel's database.
  1806. func (s *InboundService) buildInboundForLocalRuntime(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1807. built, err := s.buildInboundForNodePush(tx, inbound)
  1808. if err != nil {
  1809. return nil, err
  1810. }
  1811. settings := map[string]any{}
  1812. if err := json.Unmarshal([]byte(built.Settings), &settings); err != nil {
  1813. return nil, err
  1814. }
  1815. clients, ok := settings["clients"].([]any)
  1816. if !ok {
  1817. return built, nil
  1818. }
  1819. var clientStats []xray.ClientTraffic
  1820. if err := tx.Model(xray.ClientTraffic{}).
  1821. Where("inbound_id = ?", built.Id).
  1822. Select("email", "enable").
  1823. Find(&clientStats).Error; err != nil {
  1824. return nil, err
  1825. }
  1826. enableMap := make(map[string]bool, len(clientStats))
  1827. for _, clientTraffic := range clientStats {
  1828. enableMap[clientTraffic.Email] = clientTraffic.Enable
  1829. }
  1830. finalClients := make([]any, 0, len(clients))
  1831. for _, client := range clients {
  1832. c, ok := client.(map[string]any)
  1833. if !ok {
  1834. continue
  1835. }
  1836. email, _ := c["email"].(string)
  1837. if enable, exists := enableMap[email]; exists && !enable {
  1838. continue
  1839. }
  1840. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  1841. continue
  1842. }
  1843. finalClients = append(finalClients, c)
  1844. }
  1845. settings["clients"] = finalClients
  1846. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1847. if err != nil {
  1848. return nil, err
  1849. }
  1850. runtimeInbound := *built
  1851. runtimeInbound.Settings = string(modifiedSettings)
  1852. return &runtimeInbound, nil
  1853. }
  1854. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  1855. // list: removes rows for emails that disappeared, inserts rows for newly-added
  1856. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  1857. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  1858. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  1859. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  1860. oldClients, err := s.GetClients(oldInbound)
  1861. if err != nil {
  1862. return err
  1863. }
  1864. newClients, err := s.GetClients(newInbound)
  1865. if err != nil {
  1866. return err
  1867. }
  1868. // Email is the unique key for ClientTraffic rows. Clients without an
  1869. // email have no stats row to sync — skip them on both sides instead of
  1870. // risking a unique-constraint hit or accidental delete of an unrelated row.
  1871. oldEmails := make(map[string]struct{}, len(oldClients))
  1872. for i := range oldClients {
  1873. if oldClients[i].Email == "" {
  1874. continue
  1875. }
  1876. oldEmails[oldClients[i].Email] = struct{}{}
  1877. }
  1878. newEmails := make(map[string]struct{}, len(newClients))
  1879. for i := range newClients {
  1880. if newClients[i].Email == "" {
  1881. continue
  1882. }
  1883. newEmails[newClients[i].Email] = struct{}{}
  1884. }
  1885. // Drop stats rows for removed emails — but not when a sibling inbound
  1886. // still references the email, since the row is the shared accumulator.
  1887. for i := range oldClients {
  1888. email := oldClients[i].Email
  1889. if email == "" {
  1890. continue
  1891. }
  1892. if _, kept := newEmails[email]; kept {
  1893. continue
  1894. }
  1895. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  1896. if err != nil {
  1897. return err
  1898. }
  1899. if stillUsed {
  1900. continue
  1901. }
  1902. if err := s.DelClientStat(tx, email); err != nil {
  1903. return err
  1904. }
  1905. // Keep inbound_client_ips in sync when the inbound edit drops an
  1906. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  1907. if err := s.DelClientIPs(tx, email); err != nil {
  1908. return err
  1909. }
  1910. }
  1911. for i := range newClients {
  1912. email := newClients[i].Email
  1913. if email == "" {
  1914. continue
  1915. }
  1916. if _, existed := oldEmails[email]; existed {
  1917. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  1918. return err
  1919. }
  1920. continue
  1921. }
  1922. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  1923. return err
  1924. }
  1925. }
  1926. return nil
  1927. }
  1928. func (s *InboundService) GetInboundTags() (string, error) {
  1929. db := database.GetDB()
  1930. var inboundTags []string
  1931. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1932. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1933. return "", err
  1934. }
  1935. tags, _ := json.Marshal(inboundTags)
  1936. return string(tags), nil
  1937. }
  1938. func (s *InboundService) GetClientReverseTags() (string, error) {
  1939. db := database.GetDB()
  1940. var inbounds []model.Inbound
  1941. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1942. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1943. return "[]", err
  1944. }
  1945. tagSet := make(map[string]struct{})
  1946. for _, inbound := range inbounds {
  1947. var settings map[string]any
  1948. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1949. continue
  1950. }
  1951. clients, ok := settings["clients"].([]any)
  1952. if !ok {
  1953. continue
  1954. }
  1955. for _, client := range clients {
  1956. clientMap, ok := client.(map[string]any)
  1957. if !ok {
  1958. continue
  1959. }
  1960. reverse, ok := clientMap["reverse"].(map[string]any)
  1961. if !ok {
  1962. continue
  1963. }
  1964. tag, _ := reverse["tag"].(string)
  1965. tag = strings.TrimSpace(tag)
  1966. if tag != "" {
  1967. tagSet[tag] = struct{}{}
  1968. }
  1969. }
  1970. }
  1971. rawTags := make([]string, 0, len(tagSet))
  1972. for tag := range tagSet {
  1973. rawTags = append(rawTags, tag)
  1974. }
  1975. sort.Strings(rawTags)
  1976. result, _ := json.Marshal(rawTags)
  1977. return string(result), nil
  1978. }
  1979. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1980. db := database.GetDB()
  1981. var inbounds []*model.Inbound
  1982. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1983. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1984. return nil, err
  1985. }
  1986. return inbounds, nil
  1987. }