inbound.go 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469
  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/database"
  18. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  19. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  20. "github.com/mhsanaei/3x-ui/v3/internal/mtproto"
  21. "github.com/mhsanaei/3x-ui/v3/internal/tuic"
  22. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  23. "github.com/mhsanaei/3x-ui/v3/internal/util/maskcompat"
  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. inst, ok := tuic.InstanceFromInbound(&model.Inbound{Protocol: model.TUIC, Settings: settings})
  493. if !ok {
  494. return nil
  495. }
  496. return &tuic.TuicServerSettings{
  497. Certificate: inst.Certificate,
  498. CongestionControl: inst.CongestionControl,
  499. ALPN: inst.ALPN,
  500. UDPRelayMode: inst.UDPRelayMode,
  501. ZeroRTTHandshake: inst.ZeroRTTHandshake,
  502. LogLevel: inst.LogLevel,
  503. MaxIdleTime: inst.MaxIdleTime,
  504. AuthenticationTimeout: inst.AuthenticationTimeout,
  505. MaxUdpRelayPacketSize: inst.MaxUdpRelayPacketSize,
  506. SNI: inst.SNI,
  507. }
  508. }
  509. // inboundMtprotoDomain returns the inbound-level FakeTLS default domain, used by
  510. // the clients UI to seed a new mtproto client's secret with the right fronting
  511. // hostname.
  512. func inboundMtprotoDomain(protocol string, settings string) string {
  513. if protocol != string(model.MTProto) || strings.TrimSpace(settings) == "" {
  514. return ""
  515. }
  516. var parsed struct {
  517. FakeTLSDomain string `json:"fakeTlsDomain"`
  518. }
  519. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  520. return ""
  521. }
  522. return strings.TrimSpace(parsed.FakeTLSDomain)
  523. }
  524. // GetAllInbounds retrieves all inbounds with client stats.
  525. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  526. db := database.GetDB()
  527. var inbounds []*model.Inbound
  528. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  529. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  530. return nil, err
  531. }
  532. s.enrichClientStats(db, inbounds)
  533. return inbounds, nil
  534. }
  535. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  536. db := database.GetDB()
  537. var inbounds []*model.Inbound
  538. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  539. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  540. return nil, err
  541. }
  542. return inbounds, nil
  543. }
  544. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  545. return ParseInboundSettingsClients(inbound.Settings)
  546. }
  547. // GetClientsBySubId returns the inbound's clients with the given subscription
  548. // id, resolved from the normalized clients tables (the same source the running
  549. // Xray users are built from) instead of parsing the settings JSON blob.
  550. func (s *InboundService) GetClientsBySubId(inboundId int, subId string) ([]model.Client, error) {
  551. return s.clientService.ListForInboundBySubId(nil, inboundId, subId)
  552. }
  553. // ListClientsForInbound returns every client attached to the inbound from the
  554. // normalized clients tables — the same source the running Xray config uses —
  555. // instead of parsing the embedded settings JSON, which can hold a stale UUID
  556. // after a client identity change (#6436).
  557. func (s *InboundService) ListClientsForInbound(inboundId int) ([]model.Client, error) {
  558. return s.clientService.ListForInbound(nil, inboundId)
  559. }
  560. func (s *InboundService) GetAllEmails() ([]string, error) {
  561. db := database.GetDB()
  562. var emails []string
  563. query := fmt.Sprintf(
  564. "SELECT DISTINCT %s %s",
  565. database.JSONFieldText("client.value", "email"),
  566. database.JSONClientsFromInbound(),
  567. )
  568. if err := db.Raw(query).Scan(&emails).Error; err != nil {
  569. return nil, err
  570. }
  571. return emails, nil
  572. }
  573. // emailSubIDsForClients returns lower(email)→subId for just the emails being
  574. // checked. One clients row owns an email's identity, so the answer no longer
  575. // needs a scan of every inbound's settings JSON (#6252).
  576. func (s *InboundService) emailSubIDsForClients(clients []model.Client) (map[string]string, error) {
  577. want := make(map[string]struct{}, len(clients))
  578. for i := range clients {
  579. if email := strings.ToLower(strings.TrimSpace(clients[i].Email)); email != "" {
  580. want[email] = struct{}{}
  581. }
  582. }
  583. result := make(map[string]string, len(want))
  584. if len(want) == 0 {
  585. return result, nil
  586. }
  587. lowered := make([]string, 0, len(want))
  588. for email := range want {
  589. lowered = append(lowered, email)
  590. }
  591. db := database.GetDB()
  592. for _, batch := range chunkStrings(lowered, sqlInChunk) {
  593. var rows []struct {
  594. Email string
  595. SubID string `gorm:"column:sub_id"`
  596. }
  597. err := db.Model(&model.ClientRecord{}).
  598. Select("email, sub_id").
  599. Where("LOWER(email) IN ?", batch).
  600. Scan(&rows).Error
  601. if err != nil {
  602. return nil, err
  603. }
  604. for _, r := range rows {
  605. result[strings.ToLower(r.Email)] = r.SubID
  606. }
  607. }
  608. return result, nil
  609. }
  610. // normalizeStreamSettings clears StreamSettings for protocols that don't use it.
  611. // Only vmess, vless, trojan, shadowsocks, hysteria, wireguard, and tunnel
  612. // protocols use streamSettings (wireguard for finalmask UDP masks and sockopt on
  613. // its listener; tunnel for sockopt, notably sockopt.tproxy for its TProxy/redirect
  614. // mode). Streams keyed on "method" — xray-core v26.7.11's preferred alias for
  615. // "network" — are canonicalized to "network", which every panel reader (link
  616. // generation, port-conflict detection, flow eligibility) keys on.
  617. func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
  618. protocolsWithStream := map[model.Protocol]bool{
  619. model.VMESS: true,
  620. model.VLESS: true,
  621. model.Trojan: true,
  622. model.Shadowsocks: true,
  623. model.Hysteria: true,
  624. model.WireGuard: true,
  625. model.Tunnel: true,
  626. model.MASQUE: true,
  627. }
  628. if !protocolsWithStream[inbound.Protocol] {
  629. inbound.StreamSettings = ""
  630. return
  631. }
  632. inbound.StreamSettings = canonicalizeStreamNetworkKey(inbound.StreamSettings)
  633. inbound.StreamSettings = canonicalizeLegacyXdnsMasks(inbound.StreamSettings)
  634. }
  635. // canonicalizeLegacyXdnsMasks stores an xdns mask posted in a pre-26.10.10 shape in
  636. // the names/addrs lists the core reads, as GetXrayConfig would heal it anyway.
  637. func canonicalizeLegacyXdnsMasks(streamSettings string) string {
  638. if streamSettings == "" {
  639. return streamSettings
  640. }
  641. var stream map[string]any
  642. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  643. return streamSettings
  644. }
  645. if !maskcompat.UpgradeLegacyXdns(stream["finalmask"]) {
  646. return streamSettings
  647. }
  648. out, err := json.MarshalIndent(stream, "", " ")
  649. if err != nil {
  650. return streamSettings
  651. }
  652. return string(out)
  653. }
  654. // canonicalizeStreamNetworkKey rewrites a streamSettings JSON that names its
  655. // transport under "method" to the panel-canonical "network" key. When both
  656. // keys are present, "method" wins — matching xray-core's own precedence.
  657. func canonicalizeStreamNetworkKey(streamSettings string) string {
  658. if streamSettings == "" {
  659. return streamSettings
  660. }
  661. var stream map[string]any
  662. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  663. return streamSettings
  664. }
  665. method, ok := stream["method"].(string)
  666. if !ok || method == "" {
  667. return streamSettings
  668. }
  669. stream["network"] = method
  670. delete(stream, "method")
  671. out, err := json.MarshalIndent(stream, "", " ")
  672. if err != nil {
  673. return streamSettings
  674. }
  675. return string(out)
  676. }
  677. // validateInboundTLSCertificates rejects incomplete TLS credentials before a save
  678. // can restart Xray. File paths belong to the node, so only presence is checked.
  679. func validateInboundTLSCertificates(streamSettings string) error {
  680. if strings.TrimSpace(streamSettings) == "" {
  681. return nil
  682. }
  683. var stream struct {
  684. Security string `json:"security"`
  685. TLSSettings json.RawMessage `json:"tlsSettings"`
  686. }
  687. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  688. return common.NewError("Invalid inbound stream settings: ", err)
  689. }
  690. if !strings.EqualFold(stream.Security, "tls") {
  691. return nil
  692. }
  693. var settings struct {
  694. Certificates []struct {
  695. CertificateFile string `json:"certificateFile"`
  696. KeyFile string `json:"keyFile"`
  697. Certificate []string `json:"certificate"`
  698. Key []string `json:"key"`
  699. Usage string `json:"usage"`
  700. } `json:"certificates"`
  701. }
  702. if len(stream.TLSSettings) > 0 {
  703. if err := json.Unmarshal(stream.TLSSettings, &settings); err != nil {
  704. return common.NewError("Invalid inbound TLS settings: ", err)
  705. }
  706. }
  707. hasServerCertificate := false
  708. for i, cert := range settings.Certificates {
  709. // Match Xray's file-over-inline precedence for each credential.
  710. certificate := cert.CertificateFile
  711. if certificate == "" {
  712. certificate = strings.Join(cert.Certificate, "\n")
  713. }
  714. if strings.TrimSpace(certificate) == "" {
  715. return common.NewErrorf("TLS certificate %d is missing. Configure a certificate file path or certificate content before saving the inbound.", i+1)
  716. }
  717. if strings.EqualFold(cert.Usage, "verify") {
  718. continue
  719. }
  720. key := cert.KeyFile
  721. if key == "" {
  722. key = strings.Join(cert.Key, "\n")
  723. }
  724. if strings.TrimSpace(key) == "" {
  725. 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)
  726. }
  727. hasServerCertificate = true
  728. }
  729. if !hasServerCertificate {
  730. return common.NewError("TLS requires a server certificate and private key. Configure an encipherment or issue certificate before saving the inbound.")
  731. }
  732. return nil
  733. }
  734. // finalMaskRealityTcpMasks returns the stream's finalmask.tcp masks when the
  735. // stream uses REALITY security, or nil otherwise. A non-empty result means
  736. // this stream carries the finalmask+REALITY combination that panics
  737. // Xray-core (see https://github.com/XTLS/Xray-core/issues/6453): finalmask
  738. // wraps the connection before REALITY's handshake ever sees it, and
  739. // reality.Server() does an unchecked type assertion assuming a raw
  740. // *net.TCPConn, which panics once finalmask is in front of it.
  741. //
  742. // Only finalmask.tcp matters here — TcpmaskManager (the thing that wraps the
  743. // listener ahead of REALITY's handshake, in xray-core's own
  744. // transport/internet/memory_settings.go) is only constructed when tcp masks
  745. // are present; a finalmask.udp-only config never touches the TCP accept path
  746. // REALITY runs on, so it doesn't reproduce this panic and shouldn't be
  747. // rejected.
  748. func finalMaskRealityTcpMasks(stream map[string]any) []any {
  749. if stream["security"] != "reality" {
  750. return nil
  751. }
  752. finalmask, ok := stream["finalmask"].(map[string]any)
  753. if !ok {
  754. return nil
  755. }
  756. tcp, _ := finalmask["tcp"].([]any)
  757. return tcp
  758. }
  759. // validateFinalMaskRealityCombo rejects finalmask.tcp configured together
  760. // with REALITY security at save time. Upstream has confirmed this
  761. // combination will be documented as unsupported rather than made graceful,
  762. // so the panel must not let it be saved.
  763. func validateFinalMaskRealityCombo(streamSettings string) error {
  764. if streamSettings == "" {
  765. return nil
  766. }
  767. var stream map[string]any
  768. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  769. return nil
  770. }
  771. if len(finalMaskRealityTcpMasks(stream)) == 0 {
  772. return nil
  773. }
  774. 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.")
  775. }
  776. var xmcProfileUsernamePattern = regexp.MustCompile(`^[A-Za-z0-9_]{3,16}$`)
  777. // xmcMaskProfilesComplete reports whether an xmc finalmask carries the signed
  778. // Minecraft session profiles xray-core has required since v26.7.28 (#6487).
  779. // The core replaced the old `usernames` string list with `profiles` objects
  780. // and removed the "default to Dream when empty" fallback, so a mask still on
  781. // the legacy shape — or one whose profiles are incomplete — now fails
  782. // conf.XMC.Build() and takes the entire config down with it rather than
  783. // degrading that one inbound.
  784. //
  785. // The texture fields are a signed blob only Mojang's session server can issue
  786. // (resolve the UUID by username, then fetch the profile with unsigned=false),
  787. // so the panel cannot synthesize a valid profile from a legacy username; an
  788. // incomplete mask can only be reported or dropped.
  789. func xmcMaskProfilesComplete(mask map[string]any) bool {
  790. settings, ok := mask["settings"].(map[string]any)
  791. if !ok {
  792. return false
  793. }
  794. profiles, _ := settings["profiles"].([]any)
  795. if len(profiles) == 0 {
  796. return false
  797. }
  798. for _, entry := range profiles {
  799. profile, ok := entry.(map[string]any)
  800. if !ok {
  801. return false
  802. }
  803. username, _ := profile["username"].(string)
  804. if !xmcProfileUsernamePattern.MatchString(username) {
  805. return false
  806. }
  807. id, _ := profile["uuid"].(string)
  808. if _, err := uuid.Parse(id); err != nil {
  809. return false
  810. }
  811. if value, _ := profile["texturesValue"].(string); value == "" {
  812. return false
  813. }
  814. if signature, _ := profile["texturesSignature"].(string); signature == "" {
  815. return false
  816. }
  817. }
  818. return true
  819. }
  820. // isIncompleteXmcMask reports whether a finalmask.tcp entry is an xmc mask
  821. // xray-core would refuse to build.
  822. func isIncompleteXmcMask(entry any) bool {
  823. mask, ok := entry.(map[string]any)
  824. if !ok {
  825. return false
  826. }
  827. if maskType, _ := mask["type"].(string); maskType != "xmc" {
  828. return false
  829. }
  830. return !xmcMaskProfilesComplete(mask)
  831. }
  832. // incompleteXmcMaskCount counts the stream's xmc finalmask entries that
  833. // xray-core would refuse to build.
  834. func incompleteXmcMaskCount(stream map[string]any) int {
  835. finalmask, ok := stream["finalmask"].(map[string]any)
  836. if !ok {
  837. return 0
  838. }
  839. tcp, _ := finalmask["tcp"].([]any)
  840. count := 0
  841. for _, entry := range tcp {
  842. if isIncompleteXmcMask(entry) {
  843. count++
  844. }
  845. }
  846. return count
  847. }
  848. // stripIncompleteXmcMasks removes every xmc finalmask entry xray-core would
  849. // refuse to build, returning how many were dropped, and clears the finalmask
  850. // object once nothing is left in it.
  851. //
  852. // AddInbound and UpdateInbound reject an incomplete mask at save time, but a
  853. // row that never went through those paths — an upgrade from a panel predating
  854. // v26.7.28, node sync, a restored backup, a direct DB edit — would otherwise
  855. // fail the whole config build and keep every other inbound offline too.
  856. // Dropping only the offending mask degrades that one inbound instead, which
  857. // the accompanying warning tells the admin to reconfigure.
  858. func stripIncompleteXmcMasks(stream map[string]any) int {
  859. finalmask, ok := stream["finalmask"].(map[string]any)
  860. if !ok {
  861. return 0
  862. }
  863. tcp, _ := finalmask["tcp"].([]any)
  864. if len(tcp) == 0 {
  865. return 0
  866. }
  867. kept := make([]any, 0, len(tcp))
  868. dropped := 0
  869. for _, entry := range tcp {
  870. if isIncompleteXmcMask(entry) {
  871. dropped++
  872. continue
  873. }
  874. kept = append(kept, entry)
  875. }
  876. if dropped == 0 {
  877. return 0
  878. }
  879. if len(kept) == 0 {
  880. delete(finalmask, "tcp")
  881. } else {
  882. finalmask["tcp"] = kept
  883. }
  884. if len(finalmask) == 0 {
  885. delete(stream, "finalmask")
  886. }
  887. return dropped
  888. }
  889. // dropEmptyRandPackets removes the leftover empty "packet" from finalmask
  890. // items that also carry a rand, and reports how many it cleared.
  891. //
  892. // xray-core treats even an empty array as a packet, and every item kind is
  893. // exclusive: noise refuses "len(item.Packet) > 0 && item.Rand.To > 0" and
  894. // header-custom refuses "exactly one item kind must be set". Either error
  895. // fails the whole config build, so one such item keeps every inbound offline.
  896. // The panel's mask editor wrote that pair whenever an item was switched to the
  897. // rand-driven array kind, so stored rows carry it; clearing an empty packet
  898. // changes nothing about the mask the admin configured.
  899. func dropEmptyRandPackets(node any) int {
  900. switch value := node.(type) {
  901. case map[string]any:
  902. cleared := 0
  903. if packet, ok := value["packet"].([]any); ok && len(packet) == 0 && randIsSet(value["rand"]) {
  904. delete(value, "packet")
  905. cleared++
  906. }
  907. for _, child := range value {
  908. cleared += dropEmptyRandPackets(child)
  909. }
  910. return cleared
  911. case []any:
  912. cleared := 0
  913. for _, child := range value {
  914. cleared += dropEmptyRandPackets(child)
  915. }
  916. return cleared
  917. default:
  918. return 0
  919. }
  920. }
  921. // randIsSet reports whether a finalmask item's rand selects a random packet.
  922. // It is a number on header-custom items and a dash-range string on noise ones.
  923. func randIsSet(value any) bool {
  924. switch rand := value.(type) {
  925. case float64:
  926. return rand > 0
  927. case string:
  928. return rand != "" && rand != "0" && rand != "0-0"
  929. default:
  930. return false
  931. }
  932. }
  933. // validateFinalMaskXmcProfiles rejects an xmc finalmask without complete
  934. // profiles at save time, so the admin gets a targeted error instead of a core
  935. // that refuses to start (or, after GetXrayConfig heals it, an inbound quietly
  936. // serving without the obfuscation they configured).
  937. func validateFinalMaskXmcProfiles(streamSettings string) error {
  938. if streamSettings == "" {
  939. return nil
  940. }
  941. var stream map[string]any
  942. if err := json.Unmarshal([]byte(streamSettings), &stream); err != nil {
  943. return nil
  944. }
  945. if incompleteXmcMaskCount(stream) == 0 {
  946. return nil
  947. }
  948. 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.")
  949. }
  950. // validateFinalMaskSalamander refuses at save a salamander password the core loads and then refuses
  951. // when the listener opens, which stops every other inbound with it.
  952. func validateFinalMaskSalamander(streamSettings string) error {
  953. var stream map[string]any
  954. if json.Unmarshal([]byte(streamSettings), &stream) != nil {
  955. return nil
  956. }
  957. return maskcompat.CheckSalamanderPasswords(stream["finalmask"])
  958. }
  959. // validateXDriveStorage refuses at save the XDRIVE storage xray-core refuses when an inbound starts
  960. // listening (stopping every inbound) or an outbound dials.
  961. func validateXDriveStorage(streamSettings string) error {
  962. var stream struct {
  963. Network string `json:"network"`
  964. XDriveSettings struct {
  965. Service string `json:"service"`
  966. RemoteFolder string `json:"remoteFolder"`
  967. Secrets []string `json:"secrets"`
  968. Template json.RawMessage `json:"template"`
  969. } `json:"xdriveSettings"`
  970. }
  971. if json.Unmarshal([]byte(streamSettings), &stream) != nil || stream.Network != "xdrive" {
  972. return nil
  973. }
  974. xd := stream.XDriveSettings
  975. hasFolder := strings.TrimSpace(xd.RemoteFolder) != ""
  976. switch xd.Service {
  977. case "local":
  978. if !hasFolder {
  979. return common.NewError(`XDRIVE needs a "remoteFolder": the local folder both ends share.`)
  980. }
  981. case "Google Drive":
  982. if !hasFolder {
  983. return common.NewError(`XDRIVE needs a "remoteFolder": the id of the shared Google Drive folder.`)
  984. }
  985. if len(xd.Secrets) != 3 || slices.ContainsFunc(xd.Secrets, func(s string) bool { return strings.TrimSpace(s) == "" }) {
  986. return common.NewError("Google Drive needs 3 secrets, in order: ClientID, ClientSecret, RefreshToken.")
  987. }
  988. case "template":
  989. if len(xd.Template) == 0 || string(xd.Template) == "null" {
  990. return common.NewError(`XDRIVE service "template" needs a "template" object describing the storage API.`)
  991. }
  992. return validateXDriveTemplate(xd.Template)
  993. default:
  994. return common.NewError(fmt.Sprintf("unsupported XDRIVE service %q: use local, Google Drive or template.", xd.Service))
  995. }
  996. return nil
  997. }
  998. // validateXDriveTemplate applies the checks of xray-core's newTemplateStorage
  999. // (transport/internet/xdrive/template.go), which only run once the listener starts.
  1000. func validateXDriveTemplate(raw json.RawMessage) error {
  1001. type op struct {
  1002. URL string `json:"url"`
  1003. NamesRegex string `json:"namesRegex"`
  1004. }
  1005. var tmpl struct {
  1006. Put op `json:"put"`
  1007. Get op `json:"get"`
  1008. Delete op `json:"delete"`
  1009. List op `json:"list"`
  1010. }
  1011. if err := json.Unmarshal(raw, &tmpl); err != nil {
  1012. return common.NewError("XDRIVE template is not a valid storage template:", err)
  1013. }
  1014. if tmpl.Put.URL == "" || tmpl.Get.URL == "" || tmpl.List.URL == "" || tmpl.Delete.URL == "" {
  1015. return common.NewError("XDRIVE template needs put, get, list and delete operations, each with a url.")
  1016. }
  1017. if tmpl.List.NamesRegex == "" {
  1018. return common.NewError("XDRIVE template list needs a namesRegex.")
  1019. }
  1020. names, err := regexp.Compile(tmpl.List.NamesRegex)
  1021. if err != nil {
  1022. return common.NewError("XDRIVE template namesRegex does not compile:", err)
  1023. }
  1024. if names.NumSubexp() < 1 {
  1025. return common.NewError("XDRIVE template namesRegex needs one capture group for the object name.")
  1026. }
  1027. return nil
  1028. }
  1029. // validateFinalMaskJSONSalamander checks a stored whole finalmask: a host's, or the subscription's.
  1030. func validateFinalMaskJSONSalamander(finalmask string) error {
  1031. var fm map[string]any
  1032. if json.Unmarshal([]byte(finalmask), &fm) != nil {
  1033. return nil
  1034. }
  1035. return maskcompat.CheckSalamanderPasswords(fm)
  1036. }
  1037. // normalizeMtprotoSecret rebuilds every mtproto client's FakeTLS secret so it is
  1038. // always valid before the row is persisted, and drops the vestigial inbound-level
  1039. // secret and adTag: MTProto is multi-client, so mtg and every share link read
  1040. // only the per-client values. Leaving an inbound-level secret behind is what
  1041. // produced stale links that failed with "incorrect client random".
  1042. func (s *InboundService) normalizeMtprotoSecret(inbound *model.Inbound) {
  1043. if inbound.Protocol != model.MTProto {
  1044. return
  1045. }
  1046. if stripped, ok := model.StripMtprotoInboundSecret(inbound.Settings); ok {
  1047. inbound.Settings = stripped
  1048. }
  1049. if stripped, ok := model.StripMtprotoInboundAdTag(inbound.Settings); ok {
  1050. inbound.Settings = stripped
  1051. }
  1052. if healed, ok := model.HealMtprotoClientSecrets(inbound.Settings); ok {
  1053. inbound.Settings = healed
  1054. }
  1055. }
  1056. // mtprotoRoutesThroughXray reports whether an mtproto inbound is configured to
  1057. // egress through the core's router (the loopback SOCKS bridge in §xray.go).
  1058. func mtprotoRoutesThroughXray(inbound *model.Inbound) bool {
  1059. if inbound == nil || inbound.Protocol != model.MTProto {
  1060. return false
  1061. }
  1062. var parsed struct {
  1063. RouteThroughXray bool `json:"routeThroughXray"`
  1064. }
  1065. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
  1066. return false
  1067. }
  1068. return parsed.RouteThroughXray
  1069. }
  1070. func settingsRouteXrayPort(parsed map[string]any) int {
  1071. switch v := parsed["routeXrayPort"].(type) {
  1072. case float64:
  1073. return int(v)
  1074. case int:
  1075. return v
  1076. case json.Number:
  1077. if n, err := v.Int64(); err == nil {
  1078. return int(n)
  1079. }
  1080. }
  1081. return 0
  1082. }
  1083. func parseRouteXrayPort(settings string) int {
  1084. if settings == "" {
  1085. return 0
  1086. }
  1087. var parsed map[string]any
  1088. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  1089. return 0
  1090. }
  1091. return settingsRouteXrayPort(parsed)
  1092. }
  1093. // normalizeMtprotoXrayPort guarantees a routed mtproto inbound carries a stable
  1094. // loopback egress port in its settings, so the generated Xray SOCKS bridge and
  1095. // the mtg sidecar agree on where mtg dials out. The port is backend-owned: it is
  1096. // allocated once when routing is first enabled and preserved across edits
  1097. // (carried over from oldSettings, which wins over any value the client echoed
  1098. // back). When routing is off it — together with the now-inert outbound
  1099. // selection — is stripped so a disabled bridge leaves nothing stale behind.
  1100. //
  1101. // It returns an error when an egress port cannot be allocated or persisted, so
  1102. // the caller refuses the save rather than storing a routed-but-portless inbound,
  1103. // which would otherwise route no traffic and have its mtg metrics skipped (see
  1104. // mtproto_job) — silently losing its accounting.
  1105. func (s *InboundService) normalizeMtprotoXrayPort(inbound *model.Inbound, oldSettings string) error {
  1106. if inbound.Protocol != model.MTProto {
  1107. return nil
  1108. }
  1109. var parsed map[string]any
  1110. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed == nil {
  1111. return nil
  1112. }
  1113. routed, _ := parsed["routeThroughXray"].(bool)
  1114. if !routed {
  1115. _, hadPort := parsed["routeXrayPort"]
  1116. _, hadTag := parsed["outboundTag"]
  1117. if !hadPort && !hadTag {
  1118. return nil
  1119. }
  1120. delete(parsed, "routeXrayPort")
  1121. delete(parsed, "outboundTag")
  1122. if bs, err := json.MarshalIndent(parsed, "", " "); err == nil {
  1123. inbound.Settings = string(bs)
  1124. } else {
  1125. logger.Warning("mtproto: failed to marshal settings after disabling routing:", err)
  1126. }
  1127. return nil
  1128. }
  1129. // Prefer the already-stored port (carried across edits), then any value the
  1130. // client sent, then allocate a fresh one.
  1131. port := parseRouteXrayPort(oldSettings)
  1132. if inbound.NodeID != nil {
  1133. // The port is free or taken on the node's host, not here: the node's own
  1134. // panel allocates it, and node sync brings its choice back as oldSettings.
  1135. if port <= 0 {
  1136. delete(parsed, "routeXrayPort")
  1137. } else {
  1138. parsed["routeXrayPort"] = port
  1139. }
  1140. bs, err := json.MarshalIndent(parsed, "", " ")
  1141. if err != nil {
  1142. return common.NewError("mtproto: could not persist the Xray egress port:", err)
  1143. }
  1144. inbound.Settings = string(bs)
  1145. return nil
  1146. }
  1147. if port <= 0 {
  1148. port = settingsRouteXrayPort(parsed)
  1149. }
  1150. if port <= 0 {
  1151. allocated, err := mtproto.FreeLocalPort()
  1152. if err != nil {
  1153. return common.NewError("mtproto: could not allocate an Xray egress port:", err)
  1154. }
  1155. port = allocated
  1156. }
  1157. if settingsRouteXrayPort(parsed) == port {
  1158. return nil
  1159. }
  1160. parsed["routeXrayPort"] = port
  1161. bs, err := json.MarshalIndent(parsed, "", " ")
  1162. if err != nil {
  1163. return common.NewError("mtproto: could not persist the Xray egress port:", err)
  1164. }
  1165. inbound.Settings = string(bs)
  1166. return nil
  1167. }
  1168. // AddInbound creates a new inbound configuration.
  1169. // It validates port uniqueness, client email uniqueness, and required fields,
  1170. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  1171. // Returns the created inbound, whether Xray needs restart, and any error.
  1172. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  1173. inbound.Id = 0
  1174. if err := normalizeTuicSettings(inbound); err != nil {
  1175. return inbound, false, err
  1176. }
  1177. legacyShareAddr := legacyMtprotoShareAddr(inbound)
  1178. inbound.TrafficResetDay = normalizeTrafficResetDay(inbound.TrafficResetDay)
  1179. // Normalize streamSettings based on protocol
  1180. s.normalizeStreamSettings(inbound)
  1181. if !s.FromNodeSync {
  1182. if err := validateInboundTLSCertificates(inbound.StreamSettings); err != nil {
  1183. return inbound, false, err
  1184. }
  1185. }
  1186. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  1187. return inbound, false, err
  1188. }
  1189. if err := validateFinalMaskXmcProfiles(inbound.StreamSettings); err != nil {
  1190. return inbound, false, err
  1191. }
  1192. if err := validateFinalMaskSalamander(inbound.StreamSettings); err != nil {
  1193. return inbound, false, err
  1194. }
  1195. if err := validateXDriveStorage(inbound.StreamSettings); err != nil {
  1196. return inbound, false, err
  1197. }
  1198. if err := validateShadowsocks2022Inbound(inbound.Protocol, inbound.Settings); err != nil {
  1199. return inbound, false, err
  1200. }
  1201. s.normalizeMtprotoSecret(inbound)
  1202. if err := s.normalizeMtprotoXrayPort(inbound, ""); err != nil {
  1203. return inbound, false, err
  1204. }
  1205. if err := s.normalizeAmneziaWGSettings(inbound, ""); err != nil {
  1206. return inbound, false, err
  1207. }
  1208. if inbound.NodeID != nil {
  1209. if err := checkNodeCanHostProtocol(database.GetDB(), *inbound.NodeID, inbound.Protocol); err != nil {
  1210. return inbound, false, err
  1211. }
  1212. }
  1213. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  1214. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1215. return inbound, false, err
  1216. }
  1217. tag, err := s.resolveInboundTag(inbound, 0)
  1218. if err != nil {
  1219. return inbound, false, err
  1220. }
  1221. inbound.Tag = tag
  1222. normalizeLegacyClientSettings(inbound)
  1223. clients, err := s.GetClients(inbound)
  1224. if err != nil {
  1225. return inbound, false, err
  1226. }
  1227. if err := validateClientsRenewal(clients); err != nil {
  1228. return inbound, false, err
  1229. }
  1230. for _, traffic := range inbound.ClientStats {
  1231. if err := validateClientRenewal(model.Client{Reset: traffic.Reset, ResetDay: traffic.ResetDay, ResetWeekday: traffic.ResetWeekday}); err != nil {
  1232. return inbound, false, err
  1233. }
  1234. }
  1235. existEmail, err := s.clientService.checkEmailsExistForClients(s, clients)
  1236. if err != nil {
  1237. return inbound, false, err
  1238. }
  1239. if existEmail != "" {
  1240. return inbound, false, common.NewError("Duplicate email:", existEmail)
  1241. }
  1242. if inbound.DisableFlow {
  1243. if stripped, changed := stripClientFlows(inbound.Settings); changed {
  1244. inbound.Settings = stripped
  1245. }
  1246. for i := range clients {
  1247. clients[i].Flow = ""
  1248. }
  1249. }
  1250. // Ensure created_at and updated_at on clients in settings
  1251. if len(clients) > 0 {
  1252. var settings map[string]any
  1253. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  1254. now := time.Now().Unix() * 1000
  1255. updatedClients := make([]model.Client, 0, len(clients))
  1256. for _, c := range clients {
  1257. if c.CreatedAt == 0 {
  1258. c.CreatedAt = now
  1259. }
  1260. c.UpdatedAt = now
  1261. updatedClients = append(updatedClients, c)
  1262. }
  1263. settings["clients"] = updatedClients
  1264. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  1265. inbound.Settings = string(bs)
  1266. } else {
  1267. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  1268. }
  1269. } else if err2 != nil {
  1270. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  1271. }
  1272. }
  1273. // Defensively fix any Shadowsocks-2022 client PSK whose length doesn't match
  1274. // the inbound method (e.g. an API caller supplied a wrong-size key).
  1275. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1276. inbound.Settings = normalized
  1277. }
  1278. // Secure client ID
  1279. for _, client := range clients {
  1280. switch inbound.Protocol {
  1281. case "trojan", "masque":
  1282. if client.Password == "" {
  1283. return inbound, false, common.NewError("empty client ID")
  1284. }
  1285. case "shadowsocks":
  1286. if client.Email == "" {
  1287. return inbound, false, common.NewError("empty client ID")
  1288. }
  1289. case "hysteria":
  1290. if client.Auth == "" {
  1291. return inbound, false, common.NewError("empty client ID")
  1292. }
  1293. case "wireguard", "amneziawg":
  1294. if client.PublicKey == "" {
  1295. return inbound, false, common.NewError("wireguard client requires a key")
  1296. }
  1297. case "mtproto":
  1298. if client.Secret == "" {
  1299. return inbound, false, common.NewError("mtproto client requires a secret")
  1300. }
  1301. if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
  1302. return inbound, false, common.NewError("mtproto client ad tag must be 32 hex characters")
  1303. }
  1304. case "tuic":
  1305. if client.ID == "" {
  1306. return inbound, false, common.NewError("empty client ID")
  1307. }
  1308. if client.Password == "" {
  1309. return inbound, false, common.NewError("tuic client requires a password")
  1310. }
  1311. if client.Email == "" {
  1312. return inbound, false, common.NewError("empty client email")
  1313. }
  1314. default:
  1315. if client.ID == "" {
  1316. return inbound, false, common.NewError("empty client ID")
  1317. }
  1318. }
  1319. }
  1320. needRestart := false
  1321. var postCommitApply func()
  1322. err = runSerializedTx(func(tx *gorm.DB) error {
  1323. conflict, cErr := checkPortConflictTx(tx, inbound, 0)
  1324. if cErr != nil {
  1325. return cErr
  1326. }
  1327. if conflict != nil {
  1328. return common.NewError(conflict.String())
  1329. }
  1330. markDirty := false
  1331. if err := tx.Omit("ClientStats").Save(inbound).Error; err != nil {
  1332. return err
  1333. }
  1334. // The relay port is derived from the id, only known after Save, and only a
  1335. // local row owns one: checkPortConflictTx ran no relay check with ignoreId==0.
  1336. if inbound.NodeID == nil && inbound.Protocol == model.AmneziaWG {
  1337. if self := amneziawgnetSocksSelfConflict(inbound, inbound.Id); self != "" {
  1338. return common.NewError(self)
  1339. }
  1340. conflict, cErr := checkAmneziawgnetSocksRelayCollision(tx, inbound.Id)
  1341. if cErr != nil {
  1342. return cErr
  1343. }
  1344. if conflict != nil {
  1345. return common.NewError(conflict.String())
  1346. }
  1347. conflict, cErr = checkAmneziawgnetSocksReverseConflict(tx, inbound.Id)
  1348. if cErr != nil {
  1349. return cErr
  1350. }
  1351. if conflict != nil {
  1352. return common.NewError(conflict.String())
  1353. }
  1354. // The clients' forward specs were validated while this row had no id,
  1355. // so the ports it now derives were never in the guard's context.
  1356. if aErr := s.checkAmneziaWGForwardedPorts(tx, inbound.Settings); aErr != nil {
  1357. return aErr
  1358. }
  1359. }
  1360. if inbound.NodeID == nil && inbound.Protocol == model.TUIC {
  1361. if self := tuicSocksSelfConflict(inbound, inbound.Id); self != "" {
  1362. return common.NewError(self)
  1363. }
  1364. conflict, cErr := checkTuicSocksRelayCollision(tx, inbound.Id)
  1365. if cErr != nil {
  1366. return cErr
  1367. }
  1368. if conflict != nil {
  1369. return common.NewError(conflict.String())
  1370. }
  1371. conflict, cErr = checkTuicSocksReverseConflict(tx, inbound.Id)
  1372. if cErr != nil {
  1373. return cErr
  1374. }
  1375. if conflict != nil {
  1376. return common.NewError(conflict.String())
  1377. }
  1378. }
  1379. // Emails seeded here (import's ClientStats, e.g. the controller's forced
  1380. // Enable=true on every imported stat row) are authoritative for this call
  1381. // and must not be clobbered by the AddClientStat loop below, which derives
  1382. // its enable/total/expiry/reset from Settings.clients[] instead — a second,
  1383. // possibly-stale source for the same columns on a plain (non-import) create.
  1384. statEmails := make(map[string]bool, len(inbound.ClientStats))
  1385. for i := range inbound.ClientStats {
  1386. if inbound.ClientStats[i].Email == "" {
  1387. continue
  1388. }
  1389. statEmails[inbound.ClientStats[i].Email] = true
  1390. inbound.ClientStats[i].Id = 0
  1391. inbound.ClientStats[i].InboundId = inbound.Id
  1392. if err := tx.Clauses(clause.OnConflict{
  1393. Columns: []clause.Column{{Name: "email"}},
  1394. DoNothing: true,
  1395. }).Create(&inbound.ClientStats[i]).Error; err != nil {
  1396. return err
  1397. }
  1398. }
  1399. for _, client := range clients {
  1400. if statEmails[client.Email] {
  1401. continue
  1402. }
  1403. if err := s.AddClientStat(tx, inbound.Id, &client); err != nil {
  1404. return err
  1405. }
  1406. }
  1407. if err := s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  1408. return err
  1409. }
  1410. if _, err := database.CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  1411. return err
  1412. }
  1413. if err := database.CreateHostFromMtprotoCustomShareAddr(tx, inbound.Id, legacyShareAddr); err != nil {
  1414. return err
  1415. }
  1416. if inbound.NodeID != nil {
  1417. nodeID := *inbound.NodeID
  1418. if err := (&NodeService{}).EnsureInboundTagAllowedTx(tx, nodeID, inbound.Tag); err != nil {
  1419. return err
  1420. }
  1421. }
  1422. if inbound.Enable {
  1423. if inbound.NodeID != nil {
  1424. markDirty = true
  1425. } else {
  1426. rt, push, _, perr := s.nodePushPlan(inbound)
  1427. if perr != nil {
  1428. return perr
  1429. }
  1430. if push {
  1431. payload := inbound
  1432. pushable := true
  1433. if inbound.Protocol == model.MTProto || inbound.Protocol == model.TUIC {
  1434. if built, bErr := s.buildInboundForLocalRuntime(tx, inbound); bErr == nil {
  1435. payload = built
  1436. } else {
  1437. logger.Debug("Unable to prepare runtime inbound config:", bErr)
  1438. pushable = false
  1439. }
  1440. }
  1441. if pushable {
  1442. postCommitApply = func() {
  1443. if err1 := rt.AddInbound(context.Background(), payload); err1 == nil {
  1444. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  1445. } else {
  1446. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  1447. if inbound.Protocol != model.MTProto && inbound.Protocol != model.TUIC {
  1448. needRestart = true
  1449. }
  1450. }
  1451. }
  1452. }
  1453. }
  1454. }
  1455. }
  1456. if markDirty && inbound.NodeID != nil {
  1457. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1458. }
  1459. return nil
  1460. })
  1461. if err != nil {
  1462. return inbound, false, err
  1463. }
  1464. if postCommitApply != nil {
  1465. postCommitApply()
  1466. }
  1467. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  1468. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  1469. // in the generated config, so force a regen to wire it in.
  1470. if mtprotoRoutesThroughXray(inbound) {
  1471. needRestart = true
  1472. }
  1473. return inbound, needRestart, err
  1474. }
  1475. func (s *InboundService) DelInbound(id int) (bool, error) {
  1476. needRestart, nodePush, err := s.delInbound(id)
  1477. if nodePush != nil {
  1478. nodePush()
  1479. }
  1480. return needRestart, err
  1481. }
  1482. // delInbound deletes the central row and returns the node push instead of running
  1483. // it, so a bulk delete can fan the pushes out once every row is gone.
  1484. func (s *InboundService) delInbound(id int) (bool, func(), error) {
  1485. db := database.GetDB()
  1486. needRestart := false
  1487. var postCommitApply, nodePush func()
  1488. var ib model.Inbound
  1489. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  1490. if loadErr == nil {
  1491. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  1492. if shouldPushToRuntime {
  1493. if ib.NodeID != nil {
  1494. rt, push, _, perr := s.nodePushPlan(&ib)
  1495. if perr != nil {
  1496. logger.Warning("DelInbound: node runtime lookup failed, deleting central row anyway:", perr)
  1497. } else if push {
  1498. nodePush = func() {
  1499. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  1500. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  1501. } else {
  1502. logger.Warning("DelInbound on", rt.Name(), "failed after commit:", err1)
  1503. }
  1504. }
  1505. }
  1506. } else {
  1507. rt, push, _, perr := s.nodePushPlan(&ib)
  1508. if perr != nil {
  1509. logger.Warning("DelInbound: runtime lookup failed, deleting central row anyway:", perr)
  1510. } else if push {
  1511. postCommitApply = func() {
  1512. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  1513. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  1514. } else {
  1515. logger.Warning("DelInbound on", rt.Name(), "failed after commit:", err1)
  1516. needRestart = true
  1517. }
  1518. }
  1519. } else {
  1520. needRestart = true
  1521. }
  1522. }
  1523. } else {
  1524. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  1525. }
  1526. } else {
  1527. logger.Debug("DelInbound: inbound not found, id:", id)
  1528. }
  1529. if err := db.Transaction(func(tx *gorm.DB) error {
  1530. if err := s.clientService.DetachInbound(tx, id); err != nil {
  1531. return err
  1532. }
  1533. if err := tx.Delete(model.Inbound{}, id).Error; err != nil {
  1534. return err
  1535. }
  1536. if err := tx.Where("inbound_id = ?", id).Delete(&model.Host{}).Error; err != nil {
  1537. return err
  1538. }
  1539. // Drop the deleted inbound from any sub-balancer that selects it; a
  1540. // dangling id would emit a member no subscriber can resolve (#5648).
  1541. var balancers []model.SubBalancer
  1542. if err := tx.Find(&balancers).Error; err != nil {
  1543. return err
  1544. }
  1545. for i := range balancers {
  1546. before := balancers[i].InboundIds
  1547. balancers[i].InboundIds = slices.DeleteFunc(before, func(b int) bool { return b == id })
  1548. if len(balancers[i].InboundIds) == len(before) {
  1549. continue
  1550. }
  1551. if err := tx.Save(&balancers[i]).Error; err != nil {
  1552. return err
  1553. }
  1554. }
  1555. if loadErr == nil && ib.NodeID != nil {
  1556. return (&NodeService{}).MarkNodeDirtyTx(tx, *ib.NodeID)
  1557. }
  1558. return nil
  1559. }); err != nil {
  1560. return needRestart, nil, err
  1561. }
  1562. if postCommitApply != nil {
  1563. postCommitApply()
  1564. }
  1565. if loadErr == nil && ib.Tag != "" {
  1566. if routingChanged, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(ib.Tag); syncErr != nil {
  1567. logger.Warning("DelInbound: sync routing on inbound delete failed:", syncErr)
  1568. } else if routingChanged {
  1569. needRestart = true
  1570. }
  1571. }
  1572. if !database.IsPostgres() {
  1573. var count int64
  1574. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  1575. return needRestart, nodePush, err
  1576. }
  1577. if count == 0 {
  1578. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  1579. return needRestart, nodePush, err
  1580. }
  1581. }
  1582. }
  1583. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  1584. if mtprotoRoutesThroughXray(&ib) {
  1585. needRestart = true
  1586. }
  1587. return needRestart, nodePush, nil
  1588. }
  1589. type BulkDelInboundResult struct {
  1590. Deleted int `json:"deleted"`
  1591. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  1592. }
  1593. type BulkDelInboundReport struct {
  1594. Id int `json:"id"`
  1595. Reason string `json:"reason"`
  1596. }
  1597. // DelInbounds removes every inbound in the list, reusing the single-delete
  1598. // path per id. Failures are recorded in Skipped and processing continues for
  1599. // the rest; the aggregated needRestart is returned so the caller restarts
  1600. // xray at most once.
  1601. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  1602. result := BulkDelInboundResult{}
  1603. needRestart := false
  1604. var pushIDs []int
  1605. var nodePushes []func()
  1606. for _, id := range ids {
  1607. r, nodePush, err := s.delInbound(id)
  1608. if nodePush != nil {
  1609. pushIDs = append(pushIDs, id)
  1610. nodePushes = append(nodePushes, nodePush)
  1611. }
  1612. if err != nil {
  1613. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  1614. continue
  1615. }
  1616. result.Deleted++
  1617. if r {
  1618. needRestart = true
  1619. }
  1620. }
  1621. // Rows go one at a time for the shared routing rewrite; only node pushes fan out.
  1622. fanoutInboundResults(pushIDs, nodeFanoutConcurrency, func(i int) struct{} {
  1623. nodePushes[i]()
  1624. return struct{}{}
  1625. })
  1626. return result, needRestart, nil
  1627. }
  1628. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  1629. db := database.GetDB()
  1630. inbound := &model.Inbound{}
  1631. err := db.Model(model.Inbound{}).First(inbound, id).Error
  1632. if err != nil {
  1633. return nil, err
  1634. }
  1635. return inbound, nil
  1636. }
  1637. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  1638. db := database.GetDB()
  1639. inbound := &model.Inbound{}
  1640. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  1641. if err != nil {
  1642. return nil, err
  1643. }
  1644. s.enrichClientStats(db, []*model.Inbound{inbound})
  1645. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  1646. return inbound, nil
  1647. }
  1648. // SetInboundSubSortIndex changes only the subscription sort order, so a
  1649. // reorder cannot carry a stale settings/client payload over another edit.
  1650. func (s *InboundService) SetInboundSubSortIndex(id int, index int) error {
  1651. index = normalizeSubSortIndex(index)
  1652. inbound, err := s.GetInbound(id)
  1653. if err != nil {
  1654. return err
  1655. }
  1656. if inbound.SubSortIndex == index {
  1657. return nil
  1658. }
  1659. db := database.GetDB()
  1660. if err := db.Transaction(func(tx *gorm.DB) error {
  1661. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  1662. Update("sub_sort_index", index).Error; err != nil {
  1663. return err
  1664. }
  1665. if inbound.NodeID != nil {
  1666. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1667. }
  1668. return nil
  1669. }); err != nil {
  1670. return err
  1671. }
  1672. inbound.SubSortIndex = index
  1673. if inbound.NodeID == nil {
  1674. return nil
  1675. }
  1676. rt, push, _, perr := s.nodePushPlan(inbound)
  1677. if perr != nil {
  1678. return perr
  1679. }
  1680. if push {
  1681. narrow, ok := rt.(interface {
  1682. SetInboundSubSortIndex(context.Context, *model.Inbound, int) error
  1683. })
  1684. if !ok {
  1685. return fmt.Errorf("runtime %s does not support narrow subscription ordering updates", rt.Name())
  1686. }
  1687. if err := narrow.SetInboundSubSortIndex(context.Background(), inbound, index); err != nil {
  1688. logger.Warning("SetInboundSubSortIndex: remote metadata update on", rt.Name(), "failed:", err)
  1689. }
  1690. }
  1691. return nil
  1692. }
  1693. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  1694. inbound, err := s.GetInbound(id)
  1695. if err != nil {
  1696. return false, err
  1697. }
  1698. if inbound.Enable == enable {
  1699. return false, nil
  1700. }
  1701. db := database.GetDB()
  1702. // Enabling puts this row's ports into the running config, and the guards ran
  1703. // only if it was saved: a restored or hand-edited row reaches it unchecked.
  1704. if enable && inbound.NodeID == nil {
  1705. conflict, err := checkPortConflictTx(db, inbound, inbound.Id)
  1706. if err != nil {
  1707. return false, err
  1708. }
  1709. if conflict != nil {
  1710. return false, common.NewError(conflict.String())
  1711. }
  1712. }
  1713. if err := db.Transaction(func(tx *gorm.DB) error {
  1714. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  1715. Update("enable", enable).Error; err != nil {
  1716. return err
  1717. }
  1718. if inbound.NodeID != nil {
  1719. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  1720. }
  1721. return nil
  1722. }); err != nil {
  1723. return false, err
  1724. }
  1725. inbound.Enable = enable
  1726. needRestart := false
  1727. rt, push, _, perr := s.nodePushPlan(inbound)
  1728. if perr != nil {
  1729. return false, perr
  1730. }
  1731. // Remote nodes interpret DelInbound as a real row delete (it hits
  1732. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  1733. // switch on a remote inbound used to wipe the row entirely (#4402).
  1734. // PATCH the remote row via UpdateInbound instead — preserves the
  1735. // settings/client history and just flips the enable flag.
  1736. if inbound.NodeID != nil {
  1737. if push {
  1738. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  1739. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  1740. }
  1741. }
  1742. return false, nil
  1743. }
  1744. if mtprotoRoutesThroughXray(inbound) {
  1745. needRestart = true
  1746. }
  1747. if !push {
  1748. return true, nil
  1749. }
  1750. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  1751. !strings.Contains(err.Error(), "not found") {
  1752. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  1753. needRestart = true
  1754. }
  1755. if !enable {
  1756. return needRestart, nil
  1757. }
  1758. runtimeInbound, err := s.buildInboundForLocalRuntime(db, inbound)
  1759. if err != nil {
  1760. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  1761. return true, nil
  1762. }
  1763. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  1764. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  1765. needRestart = true
  1766. }
  1767. return needRestart, nil
  1768. }
  1769. func (s *InboundService) validateUpdatedInboundClients(inbound *model.Inbound) error {
  1770. clients, err := s.GetClients(inbound)
  1771. if err != nil {
  1772. return err
  1773. }
  1774. if err := validateClientsRenewal(clients); err != nil {
  1775. return err
  1776. }
  1777. for _, client := range clients {
  1778. switch inbound.Protocol {
  1779. case model.Hysteria:
  1780. if client.Auth == "" {
  1781. return common.NewError("empty client ID")
  1782. }
  1783. case model.MASQUE:
  1784. if client.Password == "" {
  1785. return common.NewError("empty client ID")
  1786. }
  1787. case model.TUIC:
  1788. if client.ID == "" {
  1789. return common.NewError("empty client ID")
  1790. }
  1791. if client.Password == "" {
  1792. return common.NewError("tuic client requires a password")
  1793. }
  1794. if client.Email == "" {
  1795. return common.NewError("empty client email")
  1796. }
  1797. }
  1798. }
  1799. return nil
  1800. }
  1801. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  1802. legacyShareAddr := legacyMtprotoShareAddr(inbound)
  1803. inbound.TrafficResetDay = normalizeTrafficResetDay(inbound.TrafficResetDay)
  1804. // Normalize streamSettings based on protocol
  1805. s.normalizeStreamSettings(inbound)
  1806. if err := validateFinalMaskRealityCombo(inbound.StreamSettings); err != nil {
  1807. return inbound, false, err
  1808. }
  1809. if err := validateFinalMaskXmcProfiles(inbound.StreamSettings); err != nil {
  1810. return inbound, false, err
  1811. }
  1812. if err := validateFinalMaskSalamander(inbound.StreamSettings); err != nil {
  1813. return inbound, false, err
  1814. }
  1815. if err := validateXDriveStorage(inbound.StreamSettings); err != nil {
  1816. return inbound, false, err
  1817. }
  1818. if err := validateShadowsocks2022Inbound(inbound.Protocol, inbound.Settings); err != nil {
  1819. return inbound, false, err
  1820. }
  1821. s.normalizeMtprotoSecret(inbound)
  1822. oldInbound, err := s.GetInbound(inbound.Id)
  1823. if err != nil {
  1824. return inbound, false, err
  1825. }
  1826. // Restore the stored NodeID before any host-scoped check so a node inbound
  1827. // stays scoped to its own node (the payload's nodeId is unreliable, often absent).
  1828. inbound.NodeID = oldInbound.NodeID
  1829. if err := normalizeTuicSettings(inbound); err != nil {
  1830. return inbound, false, err
  1831. }
  1832. if err := s.normalizeAmneziaWGSettings(inbound, oldInbound.Settings); err != nil {
  1833. return inbound, false, err
  1834. }
  1835. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  1836. // Grandfather a row that was already stored incomplete so it stays editable;
  1837. // only a save that breaks a previously valid TLS block is refused.
  1838. if !s.FromNodeSync {
  1839. if err := validateInboundTLSCertificates(inbound.StreamSettings); err != nil {
  1840. if validateInboundTLSCertificates(oldInbound.StreamSettings) == nil {
  1841. return inbound, false, err
  1842. }
  1843. }
  1844. }
  1845. // The node assignment is the stored one, so only a protocol change can
  1846. // introduce one; a row adopted from a node keeps the protocol it arrived with.
  1847. if inbound.NodeID != nil && inbound.Protocol != oldInbound.Protocol {
  1848. if err := checkNodeCanHostProtocol(database.GetDB(), *inbound.NodeID, inbound.Protocol); err != nil {
  1849. return inbound, false, err
  1850. }
  1851. }
  1852. // Capture the pre-edit protocol and routing state before oldInbound is
  1853. // overwritten with the new values further down, then ensure a routed
  1854. // inbound keeps a stable egress port (reusing the one already stored).
  1855. oldProtocol := oldInbound.Protocol
  1856. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  1857. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  1858. return inbound, false, err
  1859. }
  1860. tag := oldInbound.Tag
  1861. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  1862. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  1863. needRestart := false
  1864. var postCommitApply func()
  1865. txErr := runSerializedTx(func(tx *gorm.DB) error {
  1866. // Re-read inside the writer: a traffic tick since the read above moved the
  1867. // counters and may have renewed or disabled clients.
  1868. stored := &model.Inbound{}
  1869. if err := tx.First(stored, inbound.Id).Error; err != nil {
  1870. return err
  1871. }
  1872. oldInbound = stored
  1873. // The form posts back the clients and enable it loaded; both have their
  1874. // own endpoints, so only a master's push may change them here.
  1875. if !s.FromNodeSync {
  1876. inbound.Settings = keepStoredClients(inbound.Settings, stored.Settings)
  1877. inbound.Enable = stored.Enable
  1878. }
  1879. // On the clients actually saved: a protocol switch keeps the stored ones.
  1880. if err := s.validateUpdatedInboundClients(inbound); err != nil {
  1881. return err
  1882. }
  1883. conflict, cErr := checkPortConflictTx(tx, inbound, inbound.Id)
  1884. if cErr != nil {
  1885. return cErr
  1886. }
  1887. if conflict != nil {
  1888. return common.NewError(conflict.String())
  1889. }
  1890. if err := s.updateClientTraffics(tx, oldInbound, inbound); err != nil {
  1891. return err
  1892. }
  1893. // Ensure created_at and updated_at exist in inbound.Settings clients
  1894. {
  1895. var oldSettings map[string]any
  1896. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1897. emailToCreated := map[string]int64{}
  1898. emailToUpdated := map[string]int64{}
  1899. if oldSettings != nil {
  1900. if oc, ok := oldSettings["clients"].([]any); ok {
  1901. for _, it := range oc {
  1902. if m, ok2 := it.(map[string]any); ok2 {
  1903. if email, ok3 := m["email"].(string); ok3 {
  1904. switch v := m["created_at"].(type) {
  1905. case float64:
  1906. emailToCreated[email] = int64(v)
  1907. case int64:
  1908. emailToCreated[email] = v
  1909. }
  1910. switch v := m["updated_at"].(type) {
  1911. case float64:
  1912. emailToUpdated[email] = int64(v)
  1913. case int64:
  1914. emailToUpdated[email] = v
  1915. }
  1916. }
  1917. }
  1918. }
  1919. }
  1920. }
  1921. var newSettings map[string]any
  1922. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  1923. now := time.Now().Unix() * 1000
  1924. if nSlice, ok := newSettings["clients"].([]any); ok {
  1925. for i := range nSlice {
  1926. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  1927. email, _ := m["email"].(string)
  1928. if _, ok3 := m["created_at"]; !ok3 {
  1929. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  1930. m["created_at"] = v
  1931. } else {
  1932. m["created_at"] = now
  1933. }
  1934. }
  1935. // Preserve client's updated_at if present; do not bump on parent inbound update
  1936. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  1937. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  1938. m["updated_at"] = v
  1939. }
  1940. }
  1941. nSlice[i] = m
  1942. }
  1943. }
  1944. newSettings["clients"] = nSlice
  1945. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  1946. inbound.Settings = string(bs)
  1947. }
  1948. }
  1949. }
  1950. }
  1951. // A Shadowsocks-2022 method change resizes the key, but existing client PSKs
  1952. // keep their old length and would be rejected by xray. Regenerate mismatched
  1953. // client keys so the inbound stays connectable.
  1954. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1955. inbound.Settings = normalized
  1956. logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
  1957. }
  1958. // Re-gate Vision flow now that the new stream/encryption is known: if this
  1959. // VLESS inbound just became flow-eligible (e.g. vlessenc was enabled on an
  1960. // XHTTP inbound), restore Vision for clients whose intended flow is Vision
  1961. // but was stripped while the inbound was ineligible.
  1962. if !inbound.DisableFlow {
  1963. if restored, changed := s.restoreVisionFlowForEligibleInbound(tx, inbound.Settings, inbound.StreamSettings, inbound.Protocol); changed {
  1964. inbound.Settings = restored
  1965. }
  1966. } else {
  1967. if stripped, changed := stripClientFlows(inbound.Settings); changed {
  1968. inbound.Settings = stripped
  1969. }
  1970. }
  1971. oldInbound.Total = inbound.Total
  1972. oldInbound.Remark = inbound.Remark
  1973. oldInbound.SubSortIndex = inbound.SubSortIndex
  1974. oldInbound.ExcludeFromSub = inbound.ExcludeFromSub
  1975. oldInbound.Enable = inbound.Enable
  1976. oldInbound.ExpiryTime = inbound.ExpiryTime
  1977. oldInbound.TrafficReset = inbound.TrafficReset
  1978. oldInbound.TrafficResetDay = inbound.TrafficResetDay
  1979. oldInbound.Listen = inbound.Listen
  1980. oldInbound.Port = inbound.Port
  1981. oldInbound.Protocol = inbound.Protocol
  1982. oldInbound.DisableFlow = inbound.DisableFlow
  1983. oldInbound.Settings = inbound.Settings
  1984. oldInbound.StreamSettings = inbound.StreamSettings
  1985. oldInbound.Sniffing = inbound.Sniffing
  1986. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  1987. normalizeInboundShareAddress(oldInbound)
  1988. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  1989. inbound.ShareAddr = oldInbound.ShareAddr
  1990. } else {
  1991. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1992. return err
  1993. }
  1994. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  1995. oldInbound.ShareAddr = inbound.ShareAddr
  1996. if err := database.CreateHostFromMtprotoCustomShareAddr(tx, inbound.Id, legacyShareAddr); err != nil {
  1997. return err
  1998. }
  1999. }
  2000. if oldTagWasAuto && inbound.Tag == tag {
  2001. inbound.Tag = ""
  2002. }
  2003. resolvedTag, err := s.resolveInboundTag(inbound, inbound.Id)
  2004. if err != nil {
  2005. return err
  2006. }
  2007. oldInbound.Tag = resolvedTag
  2008. inbound.Tag = oldInbound.Tag
  2009. if oldInbound.NodeID == nil {
  2010. rt, push, _, perr := s.nodePushPlan(oldInbound)
  2011. if perr != nil {
  2012. return perr
  2013. }
  2014. if !push {
  2015. needRestart = true
  2016. } else if oldProtocol == model.MTProto || oldInbound.Protocol == model.MTProto || oldProtocol == model.TUIC || oldInbound.Protocol == model.TUIC {
  2017. oldSnapshot := *oldInbound
  2018. oldSnapshot.Tag = tag
  2019. oldSnapshot.Protocol = oldProtocol
  2020. payload := oldInbound
  2021. pushable := true
  2022. if inbound.Enable {
  2023. if built, err2 := s.buildInboundForLocalRuntime(tx, oldInbound); err2 == nil {
  2024. payload = built
  2025. } else {
  2026. logger.Debug("Unable to prepare runtime inbound config:", err2)
  2027. pushable = false
  2028. }
  2029. }
  2030. newProtocolIsSidecar := oldInbound.Protocol == model.MTProto || oldInbound.Protocol == model.TUIC
  2031. if pushable {
  2032. postCommitApply = func() {
  2033. if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, payload); err2 == nil {
  2034. logger.Debug("Updated inbound applied on", rt.Name(), ":", oldInbound.Tag)
  2035. } else {
  2036. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  2037. if !newProtocolIsSidecar {
  2038. needRestart = true
  2039. }
  2040. }
  2041. }
  2042. }
  2043. } else {
  2044. oldSnapshot := *oldInbound
  2045. oldSnapshot.Tag = tag
  2046. var runtimeInbound *model.Inbound
  2047. if inbound.Enable {
  2048. var err2 error
  2049. runtimeInbound, err2 = s.buildInboundForLocalRuntime(tx, oldInbound)
  2050. if err2 != nil {
  2051. logger.Debug("Unable to prepare runtime inbound config:", err2)
  2052. needRestart = true
  2053. }
  2054. }
  2055. postCommitApply = func() {
  2056. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  2057. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  2058. }
  2059. if runtimeInbound == nil {
  2060. return
  2061. }
  2062. if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  2063. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  2064. } else {
  2065. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  2066. needRestart = true
  2067. }
  2068. }
  2069. }
  2070. } else {
  2071. nodeID := *oldInbound.NodeID
  2072. if err := (&NodeService{}).EnsureInboundTagAllowedTx(tx, nodeID, oldInbound.Tag); err != nil {
  2073. return err
  2074. }
  2075. }
  2076. if err := tx.Save(oldInbound).Error; err != nil {
  2077. return err
  2078. }
  2079. newClients, gcErr := s.GetClients(oldInbound)
  2080. if gcErr != nil {
  2081. return gcErr
  2082. }
  2083. if err := s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  2084. return err
  2085. }
  2086. if oldInbound.NodeID != nil {
  2087. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID); err != nil {
  2088. return err
  2089. }
  2090. }
  2091. // (Re)generate the Xray config whenever routing was or is now enabled, so
  2092. // the egress SOCKS bridge is added, moved, or dropped to match the new
  2093. // settings.
  2094. if mtprotoRoutesThroughXray(inbound) || oldRoutedMtproto {
  2095. needRestart = true
  2096. }
  2097. return nil
  2098. })
  2099. if txErr != nil {
  2100. return inbound, false, txErr
  2101. }
  2102. if postCommitApply != nil {
  2103. postCommitApply()
  2104. }
  2105. // After the rename is committed, point any routing rules / loopback outbounds
  2106. // in xrayTemplateConfig at the new tag (oldInbound.Tag now holds the resolved
  2107. // new tag; tag holds the pre-edit one). Done post-commit so a sync failure
  2108. // can't roll back the inbound edit.
  2109. if tag != oldInbound.Tag {
  2110. if routingChanged, syncErr := (&XraySettingService{}).PropagateInboundTagRename(tag, oldInbound.Tag); syncErr != nil {
  2111. logger.Warning("UpdateInbound: sync routing on tag rename failed:", syncErr)
  2112. } else if routingChanged {
  2113. needRestart = true
  2114. }
  2115. }
  2116. return inbound, needRestart, nil
  2117. }
  2118. // A node mirrors this payload into its own DB, so every client must survive:
  2119. // filtering one out makes the node delete it, and the master then mirrors that.
  2120. func (s *InboundService) buildInboundForNodePush(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  2121. if inbound == nil {
  2122. return nil, fmt.Errorf("inbound is nil")
  2123. }
  2124. built := *inbound
  2125. settings := map[string]any{}
  2126. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2127. return nil, err
  2128. }
  2129. if !inboundCanHostFallbacks(inbound) {
  2130. return &built, nil
  2131. }
  2132. fallbacks, err := s.fallbackService.BuildFallbacksJSON(tx, inbound.Id)
  2133. if err != nil {
  2134. return nil, err
  2135. }
  2136. if len(fallbacks) == 0 {
  2137. return &built, nil
  2138. }
  2139. generic := make([]any, 0, len(fallbacks))
  2140. for _, f := range fallbacks {
  2141. generic = append(generic, f)
  2142. }
  2143. settings["fallbacks"] = generic
  2144. modifiedSettings, mErr := json.MarshalIndent(settings, "", " ")
  2145. if mErr != nil {
  2146. return nil, mErr
  2147. }
  2148. built.Settings = string(modifiedSettings)
  2149. return &built, nil
  2150. }
  2151. // Strips disabled clients on top of the node payload. Safe only because the
  2152. // target here is an in-memory Xray/mtg config, not another panel's database.
  2153. func (s *InboundService) buildInboundForLocalRuntime(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  2154. built, err := s.buildInboundForNodePush(tx, inbound)
  2155. if err != nil {
  2156. return nil, err
  2157. }
  2158. settings := map[string]any{}
  2159. if err := json.Unmarshal([]byte(built.Settings), &settings); err != nil {
  2160. return nil, err
  2161. }
  2162. clients, ok := settings["clients"].([]any)
  2163. if !ok {
  2164. return built, nil
  2165. }
  2166. emails := make([]string, 0, len(clients))
  2167. for _, client := range clients {
  2168. if c, ok := client.(map[string]any); ok {
  2169. email, _ := c["email"].(string)
  2170. emails = append(emails, email)
  2171. }
  2172. }
  2173. disabled, err := trafficDisabledEmails(tx, emails)
  2174. if err != nil {
  2175. return nil, err
  2176. }
  2177. trafficIDs := make(map[string]int)
  2178. if inbound.Protocol == model.TUIC {
  2179. var rows []xray.ClientTraffic
  2180. if err := tx.Select("id", "email").Where("email IN ?", emails).Find(&rows).Error; err != nil {
  2181. return nil, err
  2182. }
  2183. for _, row := range rows {
  2184. trafficIDs[row.Email] = row.Id
  2185. }
  2186. }
  2187. finalClients := make([]any, 0, len(clients))
  2188. for _, client := range clients {
  2189. c, ok := client.(map[string]any)
  2190. if !ok {
  2191. continue
  2192. }
  2193. email, _ := c["email"].(string)
  2194. if _, off := disabled[email]; off {
  2195. continue
  2196. }
  2197. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  2198. continue
  2199. }
  2200. if inbound.Protocol == model.TUIC {
  2201. delete(c, "traffic_id")
  2202. if id := trafficIDs[email]; id > 0 {
  2203. c["traffic_id"] = id
  2204. }
  2205. }
  2206. finalClients = append(finalClients, c)
  2207. }
  2208. settings["clients"] = finalClients
  2209. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2210. if err != nil {
  2211. return nil, err
  2212. }
  2213. runtimeInbound := *built
  2214. runtimeInbound.Settings = string(modifiedSettings)
  2215. return &runtimeInbound, nil
  2216. }
  2217. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  2218. // list: removes rows for emails that disappeared, inserts rows for newly-added
  2219. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  2220. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  2221. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  2222. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  2223. oldClients, err := s.GetClients(oldInbound)
  2224. if err != nil {
  2225. return err
  2226. }
  2227. newClients, err := s.GetClients(newInbound)
  2228. if err != nil {
  2229. return err
  2230. }
  2231. // Email is the unique key for ClientTraffic rows. Clients without an
  2232. // email have no stats row to sync — skip them on both sides instead of
  2233. // risking a unique-constraint hit or accidental delete of an unrelated row.
  2234. oldEmails := make(map[string]struct{}, len(oldClients))
  2235. for i := range oldClients {
  2236. if oldClients[i].Email == "" {
  2237. continue
  2238. }
  2239. oldEmails[oldClients[i].Email] = struct{}{}
  2240. }
  2241. newEmails := make(map[string]struct{}, len(newClients))
  2242. for i := range newClients {
  2243. if newClients[i].Email == "" {
  2244. continue
  2245. }
  2246. newEmails[newClients[i].Email] = struct{}{}
  2247. }
  2248. // Drop stats rows for removed emails — but not when a sibling inbound
  2249. // still references the email, since the row is the shared accumulator.
  2250. for i := range oldClients {
  2251. email := oldClients[i].Email
  2252. if email == "" {
  2253. continue
  2254. }
  2255. if _, kept := newEmails[email]; kept {
  2256. continue
  2257. }
  2258. stillUsed, err := s.emailUsedByOtherInbounds(tx, email, oldInbound.Id)
  2259. if err != nil {
  2260. return err
  2261. }
  2262. if stillUsed {
  2263. continue
  2264. }
  2265. if err := s.DelClientStat(tx, email); err != nil {
  2266. return err
  2267. }
  2268. // Keep inbound_client_ips in sync when the inbound edit drops an
  2269. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  2270. if err := s.DelClientIPs(tx, email); err != nil {
  2271. return err
  2272. }
  2273. }
  2274. for i := range newClients {
  2275. email := newClients[i].Email
  2276. if email == "" {
  2277. continue
  2278. }
  2279. if _, existed := oldEmails[email]; existed {
  2280. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  2281. return err
  2282. }
  2283. continue
  2284. }
  2285. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  2286. return err
  2287. }
  2288. }
  2289. return nil
  2290. }
  2291. func (s *InboundService) GetInboundTags() (string, error) {
  2292. db := database.GetDB()
  2293. var inboundTags []string
  2294. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  2295. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  2296. return "", err
  2297. }
  2298. tags, _ := json.Marshal(inboundTags)
  2299. return string(tags), nil
  2300. }
  2301. func (s *InboundService) GetClientReverseTags() (string, error) {
  2302. db := database.GetDB()
  2303. var inbounds []model.Inbound
  2304. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  2305. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  2306. return "[]", err
  2307. }
  2308. tagSet := make(map[string]struct{})
  2309. for _, inbound := range inbounds {
  2310. var settings map[string]any
  2311. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2312. continue
  2313. }
  2314. clients, ok := settings["clients"].([]any)
  2315. if !ok {
  2316. continue
  2317. }
  2318. for _, client := range clients {
  2319. clientMap, ok := client.(map[string]any)
  2320. if !ok {
  2321. continue
  2322. }
  2323. reverse, ok := clientMap["reverse"].(map[string]any)
  2324. if !ok {
  2325. continue
  2326. }
  2327. tag, _ := reverse["tag"].(string)
  2328. tag = strings.TrimSpace(tag)
  2329. if tag != "" {
  2330. tagSet[tag] = struct{}{}
  2331. }
  2332. }
  2333. }
  2334. rawTags := make([]string, 0, len(tagSet))
  2335. for tag := range tagSet {
  2336. rawTags = append(rawTags, tag)
  2337. }
  2338. sort.Strings(rawTags)
  2339. result, _ := json.Marshal(rawTags)
  2340. return string(result), nil
  2341. }
  2342. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  2343. db := database.GetDB()
  2344. var inbounds []*model.Inbound
  2345. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  2346. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  2347. return nil, err
  2348. }
  2349. return inbounds, nil
  2350. }