inbound.go 82 KB

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