inbound.go 71 KB

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