inbound.go 64 KB

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