1
0

inbound.go 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413
  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. "sort"
  11. "strings"
  12. "time"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database"
  14. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  15. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  16. "github.com/mhsanaei/3x-ui/v3/internal/mtproto"
  17. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  18. "github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
  19. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  20. "gorm.io/gorm"
  21. "gorm.io/gorm/clause"
  22. )
  23. type InboundService struct {
  24. xrayApi xray.XrayAPI
  25. clientService ClientService
  26. fallbackService FallbackService
  27. }
  28. func normalizeInboundShareAddrStrategy(strategy string) string {
  29. strategy = strings.TrimSpace(strategy)
  30. switch strategy {
  31. case "listen", "custom":
  32. return strategy
  33. default:
  34. return "node"
  35. }
  36. }
  37. func normalizeInboundShareAddress(inbound *model.Inbound) {
  38. if inbound == nil {
  39. return
  40. }
  41. inbound.ShareAddrStrategy = normalizeInboundShareAddrStrategy(inbound.ShareAddrStrategy)
  42. if addr, err := normalizeInboundShareHost(inbound.ShareAddr); err == nil {
  43. inbound.ShareAddr = addr
  44. } else {
  45. inbound.ShareAddr = strings.TrimSpace(inbound.ShareAddr)
  46. }
  47. }
  48. func normalizeInboundShareAddressStrict(inbound *model.Inbound) error {
  49. if inbound == nil {
  50. return nil
  51. }
  52. inbound.ShareAddrStrategy = normalizeInboundShareAddrStrategy(inbound.ShareAddrStrategy)
  53. addr, err := normalizeInboundShareHost(inbound.ShareAddr)
  54. if err != nil {
  55. return common.NewError("shareAddr must be a host or IP without scheme or port")
  56. }
  57. inbound.ShareAddr = addr
  58. return nil
  59. }
  60. func normalizeInboundShareHost(raw string) (string, error) {
  61. addr := strings.TrimSpace(raw)
  62. if addr == "" {
  63. return "", nil
  64. }
  65. if strings.Contains(addr, "://") || strings.HasPrefix(addr, "//") || strings.ContainsAny(addr, "/?#@") {
  66. return "", fmt.Errorf("invalid share address %q", raw)
  67. }
  68. if strings.HasPrefix(addr, "[") {
  69. if !strings.HasSuffix(addr, "]") {
  70. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  71. }
  72. ip := net.ParseIP(addr[1 : len(addr)-1])
  73. if ip == nil || ip.To4() != nil {
  74. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  75. }
  76. return "[" + ip.String() + "]", nil
  77. }
  78. if strings.Contains(addr, ":") {
  79. if _, _, err := net.SplitHostPort(addr); err == nil {
  80. return "", fmt.Errorf("share address must not include port")
  81. }
  82. ip := net.ParseIP(addr)
  83. if ip == nil || ip.To4() != nil {
  84. return "", fmt.Errorf("invalid IPv6 host %q", raw)
  85. }
  86. return "[" + ip.String() + "]", nil
  87. }
  88. host, err := netsafe.NormalizeHost(addr)
  89. if err != nil {
  90. return "", err
  91. }
  92. return host, nil
  93. }
  94. func normalizeInboundShareAddressColumns(tx *gorm.DB) error {
  95. if tx == nil || !tx.Migrator().HasColumn(&model.Inbound{}, "share_addr_strategy") {
  96. return nil
  97. }
  98. strategyExpr := `CASE TRIM(COALESCE(share_addr_strategy, '')) WHEN 'listen' THEN 'listen' WHEN 'custom' THEN 'custom' ELSE 'node' END`
  99. 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 {
  100. return err
  101. }
  102. hasShareAddr := tx.Migrator().HasColumn(&model.Inbound{}, "share_addr")
  103. if hasShareAddr {
  104. 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 {
  105. return err
  106. }
  107. }
  108. if !hasShareAddr {
  109. return nil
  110. }
  111. var rows []struct {
  112. Id int
  113. ShareAddrStrategy string
  114. ShareAddr string
  115. }
  116. if err := tx.Model(&model.Inbound{}).Select("id", "share_addr_strategy", "share_addr").Find(&rows).Error; err != nil {
  117. return err
  118. }
  119. for _, row := range rows {
  120. strategy := normalizeInboundShareAddrStrategy(row.ShareAddrStrategy)
  121. addr, addrErr := normalizeInboundShareHost(row.ShareAddr)
  122. if addrErr != nil {
  123. strategy = "node"
  124. addr = ""
  125. }
  126. updates := map[string]any{}
  127. if strategy != row.ShareAddrStrategy {
  128. updates["share_addr_strategy"] = strategy
  129. }
  130. if addr != row.ShareAddr {
  131. updates["share_addr"] = addr
  132. }
  133. if len(updates) > 0 {
  134. if err := tx.Model(&model.Inbound{}).Where("id = ?", row.Id).Updates(updates).Error; err != nil {
  135. return err
  136. }
  137. }
  138. }
  139. return nil
  140. }
  141. // GetInbounds retrieves all inbounds for a specific user with client stats.
  142. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  143. db := database.GetDB()
  144. var inbounds []*model.Inbound
  145. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  146. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  147. return nil, err
  148. }
  149. s.enrichClientStats(db, inbounds)
  150. s.annotateFallbackParents(db, inbounds)
  151. s.annotateLocalOriginGuid(inbounds)
  152. return inbounds, nil
  153. }
  154. // annotateLocalOriginGuid fills OriginNodeGuid for this panel's OWN inbounds
  155. // (NodeID == nil) with the panel's stable GUID; inbounds synced from a node
  156. // already carry the originating node's GUID. Read-time only (not persisted) so
  157. // the per-inbound online view can scope by GUID uniformly across a chain of
  158. // nodes (#4983).
  159. func (s *InboundService) annotateLocalOriginGuid(inbounds []*model.Inbound) {
  160. if len(inbounds) == 0 {
  161. return
  162. }
  163. guid := s.panelGuid()
  164. if guid == "" {
  165. return
  166. }
  167. for _, ib := range inbounds {
  168. if ib.OriginNodeGuid == "" && ib.NodeID == nil {
  169. ib.OriginNodeGuid = guid
  170. }
  171. }
  172. }
  173. // GetInboundsSlim returns the same list of inbounds as GetInbounds but
  174. // strips every per-client field other than email / enable / comment from
  175. // settings.clients and skips UUID/SubId enrichment on ClientStats. The
  176. // inbounds page only needs those three to roll up client counts and
  177. // render badges, so this trims tens of bytes per client (UUID, password,
  178. // flow, security, totalGB, expiryTime, limitIp, tgId, ...) which adds
  179. // up fast on installs with thousands of clients.
  180. //
  181. // Full client data is still available through GET /panel/api/inbounds/get/:id
  182. // for the edit/info/qr/export/clone flows that need it.
  183. func (s *InboundService) GetInboundsSlim(userId int) ([]*model.Inbound, error) {
  184. db := database.GetDB()
  185. var inbounds []*model.Inbound
  186. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
  187. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  188. return nil, err
  189. }
  190. s.annotateFallbackParents(db, inbounds)
  191. s.annotateLocalOriginGuid(inbounds)
  192. // Top up stats rows owned by sibling inbounds (multi-attached clients)
  193. // so the list's depleted/expiring badges see every client; the UUID/SubId
  194. // enrichment stays skipped. Must run before slimming strips the settings.
  195. s.backfillClientStats(db, inbounds)
  196. // Slim feeds the panel UI only (masters poll the full list), so the badge
  197. // math may see the cross-panel totals a master pushed.
  198. s.overlayInboundsClientStats(db, inbounds)
  199. for _, ib := range inbounds {
  200. ib.Settings = slimSettingsClients(ib.Settings)
  201. }
  202. return inbounds, nil
  203. }
  204. // slimSettingsClients rewrites the inbound settings JSON so settings.clients[]
  205. // keeps only the fields the list view actually reads. Returns the input
  206. // unchanged when the JSON can't be parsed or has no clients array.
  207. func slimSettingsClients(settings string) string {
  208. if settings == "" {
  209. return settings
  210. }
  211. var raw map[string]any
  212. if err := json.Unmarshal([]byte(settings), &raw); err != nil {
  213. return settings
  214. }
  215. clients, ok := raw["clients"].([]any)
  216. if !ok || len(clients) == 0 {
  217. return settings
  218. }
  219. slim := make([]any, 0, len(clients))
  220. for _, entry := range clients {
  221. c, ok := entry.(map[string]any)
  222. if !ok {
  223. continue
  224. }
  225. row := make(map[string]any, 3)
  226. if v, ok := c["email"]; ok {
  227. row["email"] = v
  228. }
  229. if v, ok := c["enable"]; ok {
  230. row["enable"] = v
  231. }
  232. if v, ok := c["comment"]; ok && v != "" {
  233. row["comment"] = v
  234. }
  235. slim = append(slim, row)
  236. }
  237. raw["clients"] = slim
  238. out, err := json.Marshal(raw)
  239. if err != nil {
  240. return settings
  241. }
  242. return string(out)
  243. }
  244. // annotateFallbackParents fills FallbackParent on each inbound that is
  245. // the child side of a fallback rule. One DB round-trip serves the full
  246. // list — the frontend needs this to rewrite the child's client-share
  247. // link so it points at the master's reachable endpoint.
  248. func (s *InboundService) annotateFallbackParents(db *gorm.DB, inbounds []*model.Inbound) {
  249. if len(inbounds) == 0 {
  250. return
  251. }
  252. childIds := make([]int, 0, len(inbounds))
  253. for _, ib := range inbounds {
  254. childIds = append(childIds, ib.Id)
  255. }
  256. var rows []model.InboundFallback
  257. if err := db.Where("child_id IN ?", childIds).
  258. Order("sort_order ASC, id ASC").
  259. Find(&rows).Error; err != nil {
  260. return
  261. }
  262. first := make(map[int]model.InboundFallback, len(rows))
  263. for _, r := range rows {
  264. if _, ok := first[r.ChildId]; !ok {
  265. first[r.ChildId] = r
  266. }
  267. }
  268. for _, ib := range inbounds {
  269. if r, ok := first[ib.Id]; ok {
  270. ib.FallbackParent = &model.FallbackParentInfo{
  271. MasterId: r.MasterId,
  272. Path: r.Path,
  273. }
  274. }
  275. }
  276. }
  277. type InboundOption struct {
  278. Id int `json:"id" example:"1"`
  279. Remark string `json:"remark" example:"VLESS-443"`
  280. Tag string `json:"tag" example:"in-443-tcp"`
  281. Protocol string `json:"protocol" example:"vless"`
  282. Port int `json:"port" example:"443"`
  283. TlsFlowCapable bool `json:"tlsFlowCapable" example:"true"`
  284. SsMethod string `json:"ssMethod"`
  285. // Hosting node; nil for this panel's own inbounds. Lets the clients
  286. // page map a node filter onto inbound IDs (#4997).
  287. NodeId *int `json:"nodeId,omitempty"`
  288. }
  289. func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error) {
  290. db := database.GetDB()
  291. var rows []struct {
  292. Id int `gorm:"column:id"`
  293. Remark string `gorm:"column:remark"`
  294. Tag string `gorm:"column:tag"`
  295. Protocol string `gorm:"column:protocol"`
  296. Port int `gorm:"column:port"`
  297. StreamSettings string `gorm:"column:stream_settings"`
  298. Settings string `gorm:"column:settings"`
  299. NodeId *int `gorm:"column:node_id"`
  300. }
  301. err := db.Table("inbounds").
  302. Select("id, remark, tag, protocol, port, stream_settings, settings, node_id").
  303. Where("user_id = ?", userId).
  304. Order("id ASC").
  305. Scan(&rows).Error
  306. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  307. return nil, err
  308. }
  309. out := make([]InboundOption, 0, len(rows))
  310. for _, r := range rows {
  311. out = append(out, InboundOption{
  312. Id: r.Id,
  313. Remark: r.Remark,
  314. Tag: r.Tag,
  315. Protocol: r.Protocol,
  316. Port: r.Port,
  317. TlsFlowCapable: inboundCanEnableTlsFlow(r.Protocol, r.StreamSettings, r.Settings),
  318. SsMethod: inboundShadowsocksMethod(r.Protocol, r.Settings),
  319. NodeId: r.NodeId,
  320. })
  321. }
  322. return out, nil
  323. }
  324. // GetAllInbounds retrieves all inbounds with client stats.
  325. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  326. db := database.GetDB()
  327. var inbounds []*model.Inbound
  328. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  329. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  330. return nil, err
  331. }
  332. s.enrichClientStats(db, inbounds)
  333. return inbounds, nil
  334. }
  335. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  336. db := database.GetDB()
  337. var inbounds []*model.Inbound
  338. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  339. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  340. return nil, err
  341. }
  342. return inbounds, nil
  343. }
  344. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  345. settings := map[string][]model.Client{}
  346. _ = json.Unmarshal([]byte(inbound.Settings), &settings)
  347. if settings == nil {
  348. return nil, fmt.Errorf("setting is null")
  349. }
  350. clients := settings["clients"]
  351. if clients == nil {
  352. return nil, nil
  353. }
  354. return clients, nil
  355. }
  356. func (s *InboundService) GetAllEmails() ([]string, error) {
  357. db := database.GetDB()
  358. var emails []string
  359. query := fmt.Sprintf(
  360. "SELECT DISTINCT %s %s",
  361. database.JSONFieldText("client.value", "email"),
  362. database.JSONClientsFromInbound(),
  363. )
  364. if err := db.Raw(query).Scan(&emails).Error; err != nil {
  365. return nil, err
  366. }
  367. return emails, nil
  368. }
  369. // getAllEmailSubIDs returns email→subId. An email seen with two different
  370. // non-empty subIds is locked (mapped to "") so neither identity can claim it.
  371. func (s *InboundService) getAllEmailSubIDs() (map[string]string, error) {
  372. db := database.GetDB()
  373. var rows []struct {
  374. Email string
  375. SubID string
  376. }
  377. query := fmt.Sprintf(
  378. "SELECT %s AS email, %s AS sub_id %s",
  379. database.JSONFieldText("client.value", "email"),
  380. database.JSONFieldText("client.value", "subId"),
  381. database.JSONClientsFromInbound(),
  382. )
  383. if err := db.Raw(query).Scan(&rows).Error; err != nil {
  384. return nil, err
  385. }
  386. result := make(map[string]string, len(rows))
  387. for _, r := range rows {
  388. email := strings.ToLower(r.Email)
  389. if email == "" {
  390. continue
  391. }
  392. subID := r.SubID
  393. if existing, ok := result[email]; ok {
  394. if existing != subID {
  395. result[email] = ""
  396. }
  397. continue
  398. }
  399. result[email] = subID
  400. }
  401. return result, nil
  402. }
  403. // normalizeStreamSettings clears StreamSettings for protocols that don't use it.
  404. // Only vmess, vless, trojan, shadowsocks, hysteria, wireguard, and tunnel
  405. // protocols use streamSettings (wireguard for finalmask UDP masks and sockopt on
  406. // its listener; tunnel for sockopt, notably sockopt.tproxy for its TProxy/redirect
  407. // mode).
  408. func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
  409. protocolsWithStream := map[model.Protocol]bool{
  410. model.VMESS: true,
  411. model.VLESS: true,
  412. model.Trojan: true,
  413. model.Shadowsocks: true,
  414. model.Hysteria: true,
  415. model.WireGuard: true,
  416. model.Tunnel: true,
  417. }
  418. if !protocolsWithStream[inbound.Protocol] {
  419. inbound.StreamSettings = ""
  420. }
  421. }
  422. // normalizeMtprotoSecret rebuilds an mtproto inbound's FakeTLS secret so it is
  423. // always valid and matches the configured domain before the row is persisted.
  424. func (s *InboundService) normalizeMtprotoSecret(inbound *model.Inbound) {
  425. if inbound.Protocol != model.MTProto {
  426. return
  427. }
  428. if healed, ok := model.HealMtprotoSecret(inbound.Settings); ok {
  429. inbound.Settings = healed
  430. }
  431. }
  432. // mtprotoRoutesThroughXray reports whether an mtproto inbound is configured to
  433. // egress through the core's router (the loopback SOCKS bridge in §xray.go).
  434. func mtprotoRoutesThroughXray(inbound *model.Inbound) bool {
  435. if inbound == nil || inbound.Protocol != model.MTProto {
  436. return false
  437. }
  438. var parsed struct {
  439. RouteThroughXray bool `json:"routeThroughXray"`
  440. }
  441. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
  442. return false
  443. }
  444. return parsed.RouteThroughXray
  445. }
  446. func settingsRouteXrayPort(parsed map[string]any) int {
  447. switch v := parsed["routeXrayPort"].(type) {
  448. case float64:
  449. return int(v)
  450. case int:
  451. return v
  452. case json.Number:
  453. if n, err := v.Int64(); err == nil {
  454. return int(n)
  455. }
  456. }
  457. return 0
  458. }
  459. func parseRouteXrayPort(settings string) int {
  460. if settings == "" {
  461. return 0
  462. }
  463. var parsed map[string]any
  464. if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
  465. return 0
  466. }
  467. return settingsRouteXrayPort(parsed)
  468. }
  469. // normalizeMtprotoXrayPort guarantees a routed mtproto inbound carries a stable
  470. // loopback egress port in its settings, so the generated Xray SOCKS bridge and
  471. // the mtg sidecar agree on where mtg dials out. The port is backend-owned: it is
  472. // allocated once when routing is first enabled and preserved across edits
  473. // (carried over from oldSettings, which wins over any value the client echoed
  474. // back). When routing is off it — together with the now-inert outbound
  475. // selection — is stripped so a disabled bridge leaves nothing stale behind.
  476. //
  477. // It returns an error when an egress port cannot be allocated or persisted, so
  478. // the caller refuses the save rather than storing a routed-but-portless inbound,
  479. // which would otherwise route no traffic and have its mtg metrics skipped (see
  480. // mtproto_job) — silently losing its accounting.
  481. func (s *InboundService) normalizeMtprotoXrayPort(inbound *model.Inbound, oldSettings string) error {
  482. if inbound.Protocol != model.MTProto {
  483. return nil
  484. }
  485. var parsed map[string]any
  486. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed == nil {
  487. return nil
  488. }
  489. routed, _ := parsed["routeThroughXray"].(bool)
  490. if !routed {
  491. _, hadPort := parsed["routeXrayPort"]
  492. _, hadTag := parsed["outboundTag"]
  493. if !hadPort && !hadTag {
  494. return nil
  495. }
  496. delete(parsed, "routeXrayPort")
  497. delete(parsed, "outboundTag")
  498. if bs, err := json.MarshalIndent(parsed, "", " "); err == nil {
  499. inbound.Settings = string(bs)
  500. } else {
  501. logger.Warning("mtproto: failed to marshal settings after disabling routing:", err)
  502. }
  503. return nil
  504. }
  505. // Prefer the already-stored port (carried across edits), then any value the
  506. // client sent, then allocate a fresh one.
  507. port := parseRouteXrayPort(oldSettings)
  508. if port <= 0 {
  509. port = settingsRouteXrayPort(parsed)
  510. }
  511. if port <= 0 {
  512. allocated, err := mtproto.FreeLocalPort()
  513. if err != nil {
  514. return common.NewError("mtproto: could not allocate an Xray egress port:", err)
  515. }
  516. port = allocated
  517. }
  518. if settingsRouteXrayPort(parsed) == port {
  519. return nil
  520. }
  521. parsed["routeXrayPort"] = port
  522. bs, err := json.MarshalIndent(parsed, "", " ")
  523. if err != nil {
  524. return common.NewError("mtproto: could not persist the Xray egress port:", err)
  525. }
  526. inbound.Settings = string(bs)
  527. return nil
  528. }
  529. // AddInbound creates a new inbound configuration.
  530. // It validates port uniqueness, client email uniqueness, and required fields,
  531. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  532. // Returns the created inbound, whether Xray needs restart, and any error.
  533. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  534. // Normalize streamSettings based on protocol
  535. s.normalizeStreamSettings(inbound)
  536. s.normalizeMtprotoSecret(inbound)
  537. if err := s.normalizeMtprotoXrayPort(inbound, ""); err != nil {
  538. return inbound, false, err
  539. }
  540. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  541. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  542. return inbound, false, err
  543. }
  544. conflict, err := s.checkPortConflict(inbound, 0)
  545. if err != nil {
  546. return inbound, false, err
  547. }
  548. if conflict != nil {
  549. return inbound, false, common.NewError(conflict.String())
  550. }
  551. inbound.Tag, err = s.resolveInboundTag(inbound, 0)
  552. if err != nil {
  553. return inbound, false, err
  554. }
  555. clients, err := s.GetClients(inbound)
  556. if err != nil {
  557. return inbound, false, err
  558. }
  559. existEmail, err := s.clientService.checkEmailsExistForClients(s, clients, nil)
  560. if err != nil {
  561. return inbound, false, err
  562. }
  563. if existEmail != "" {
  564. return inbound, false, common.NewError("Duplicate email:", existEmail)
  565. }
  566. // Ensure created_at and updated_at on clients in settings
  567. if len(clients) > 0 {
  568. var settings map[string]any
  569. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  570. now := time.Now().Unix() * 1000
  571. updatedClients := make([]model.Client, 0, len(clients))
  572. for _, c := range clients {
  573. if c.CreatedAt == 0 {
  574. c.CreatedAt = now
  575. }
  576. c.UpdatedAt = now
  577. updatedClients = append(updatedClients, c)
  578. }
  579. settings["clients"] = updatedClients
  580. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  581. inbound.Settings = string(bs)
  582. } else {
  583. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  584. }
  585. } else if err2 != nil {
  586. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  587. }
  588. }
  589. // Defensively fix any Shadowsocks-2022 client PSK whose length doesn't match
  590. // the inbound method (e.g. an API caller supplied a wrong-size key).
  591. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  592. inbound.Settings = normalized
  593. }
  594. // Secure client ID
  595. for _, client := range clients {
  596. switch inbound.Protocol {
  597. case "trojan":
  598. if client.Password == "" {
  599. return inbound, false, common.NewError("empty client ID")
  600. }
  601. case "shadowsocks":
  602. if client.Email == "" {
  603. return inbound, false, common.NewError("empty client ID")
  604. }
  605. case "hysteria":
  606. if client.Auth == "" {
  607. return inbound, false, common.NewError("empty client ID")
  608. }
  609. default:
  610. if client.ID == "" {
  611. return inbound, false, common.NewError("empty client ID")
  612. }
  613. }
  614. }
  615. db := database.GetDB()
  616. tx := db.Begin()
  617. markDirty := false
  618. defer func() {
  619. if err != nil {
  620. tx.Rollback()
  621. return
  622. }
  623. if markDirty && inbound.NodeID != nil {
  624. if dErr := (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID); dErr != nil {
  625. err = dErr
  626. tx.Rollback()
  627. return
  628. }
  629. }
  630. tx.Commit()
  631. }()
  632. // Omit the ClientStats has-many association: GORM's cascade would INSERT
  633. // those rows with an ON CONFLICT target on the primary key only, which
  634. // collides with the globally-unique client_traffics.email when an imported
  635. // inbound carries clients that another inbound already created (e.g.
  636. // importing two inbounds that share the same clients). We insert the stats
  637. // ourselves below with the same email-conflict guard AddClientStat uses.
  638. err = tx.Omit("ClientStats").Save(inbound).Error
  639. if err != nil {
  640. return inbound, false, err
  641. }
  642. // Imported stats first, so their traffic counters survive; emails that
  643. // already own a (shared) row are skipped instead of tripping the unique
  644. // constraint.
  645. for i := range inbound.ClientStats {
  646. if inbound.ClientStats[i].Email == "" {
  647. continue
  648. }
  649. inbound.ClientStats[i].Id = 0
  650. inbound.ClientStats[i].InboundId = inbound.Id
  651. if err = tx.Clauses(clause.OnConflict{
  652. Columns: []clause.Column{{Name: "email"}},
  653. DoNothing: true,
  654. }).Create(&inbound.ClientStats[i]).Error; err != nil {
  655. return inbound, false, err
  656. }
  657. }
  658. // Then make sure every client has a stats row. AddClientStat is a no-op
  659. // where one exists (including the rows just inserted), and fills the gap
  660. // for clients an import payload didn't carry stats for.
  661. for _, client := range clients {
  662. if err = s.AddClientStat(tx, inbound.Id, &client); err != nil {
  663. return inbound, false, err
  664. }
  665. }
  666. if err = s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  667. return inbound, false, err
  668. }
  669. // Legacy import: an inbound exported from a build that predated the hosts
  670. // table carries its external proxies inline in streamSettings.externalProxy.
  671. // The startup migration that converts those to host rows runs once and is
  672. // gated off afterwards, so it never sees a freshly imported inbound —
  673. // reproduce it here. No-op for inbounds without externalProxy (everything the
  674. // current UI builds), so this only fires on such imports.
  675. if _, err = database.CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  676. return inbound, false, err
  677. }
  678. // Before the deferred commit, so a node in "selected" sync mode cannot
  679. // sweep the new central row in the gap before its tag is allowed.
  680. if inbound.NodeID != nil {
  681. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*inbound.NodeID, inbound.Tag); aErr != nil {
  682. logger.Warning("allow inbound tag on node failed:", aErr)
  683. }
  684. }
  685. needRestart := false
  686. if inbound.Enable {
  687. rt, push, dirty, perr := s.nodePushPlan(inbound)
  688. if perr != nil {
  689. err = perr
  690. return inbound, false, err
  691. }
  692. if dirty {
  693. markDirty = true
  694. }
  695. if push {
  696. if err1 := rt.AddInbound(context.Background(), inbound); err1 == nil {
  697. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  698. } else {
  699. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  700. if inbound.NodeID != nil {
  701. markDirty = true
  702. } else {
  703. needRestart = true
  704. }
  705. }
  706. }
  707. }
  708. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  709. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  710. // in the generated config, so force a regen to wire it in.
  711. if mtprotoRoutesThroughXray(inbound) {
  712. needRestart = true
  713. }
  714. return inbound, needRestart, err
  715. }
  716. func (s *InboundService) DelInbound(id int) (bool, error) {
  717. db := database.GetDB()
  718. needRestart := false
  719. markDirty := false
  720. var ib model.Inbound
  721. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  722. if loadErr == nil {
  723. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  724. if shouldPushToRuntime {
  725. rt, push, dirty, perr := s.nodePushPlan(&ib)
  726. if perr != nil {
  727. logger.Warning("DelInbound: node lookup failed, deleting central row anyway:", perr)
  728. markDirty = true
  729. } else if push {
  730. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  731. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  732. } else {
  733. logger.Warning("DelInbound on", rt.Name(), "failed, deleting central row anyway:", err1)
  734. if ib.NodeID == nil {
  735. needRestart = true
  736. } else {
  737. markDirty = true
  738. }
  739. }
  740. } else if ib.NodeID == nil {
  741. needRestart = true
  742. } else if dirty {
  743. markDirty = true
  744. }
  745. } else {
  746. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  747. }
  748. } else {
  749. logger.Debug("DelInbound: inbound not found, id:", id)
  750. }
  751. if err := s.clientService.DetachInbound(db, id); err != nil {
  752. return false, err
  753. }
  754. // Drop the deleted inbound's tag from any routing rules / loopback outbounds
  755. // in xrayTemplateConfig so they don't point at a tag that no longer exists.
  756. if loadErr == nil && ib.Tag != "" {
  757. if routingChanged, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(ib.Tag); syncErr != nil {
  758. logger.Warning("DelInbound: sync routing on inbound delete failed:", syncErr)
  759. } else if routingChanged {
  760. needRestart = true
  761. }
  762. }
  763. if err := db.Transaction(func(tx *gorm.DB) error {
  764. if err := tx.Delete(model.Inbound{}, id).Error; err != nil {
  765. return err
  766. }
  767. // Hosts have no hard FK; drop the inbound's hosts alongside it.
  768. if err := tx.Where("inbound_id = ?", id).Delete(&model.Host{}).Error; err != nil {
  769. return err
  770. }
  771. if markDirty && ib.NodeID != nil {
  772. return (&NodeService{}).MarkNodeDirtyTx(tx, *ib.NodeID)
  773. }
  774. return nil
  775. }); err != nil {
  776. return needRestart, err
  777. }
  778. if !database.IsPostgres() {
  779. var count int64
  780. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  781. return needRestart, err
  782. }
  783. if count == 0 {
  784. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  785. return needRestart, err
  786. }
  787. }
  788. }
  789. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  790. if mtprotoRoutesThroughXray(&ib) {
  791. needRestart = true
  792. }
  793. return needRestart, nil
  794. }
  795. type BulkDelInboundResult struct {
  796. Deleted int `json:"deleted"`
  797. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  798. }
  799. type BulkDelInboundReport struct {
  800. Id int `json:"id"`
  801. Reason string `json:"reason"`
  802. }
  803. // DelInbounds removes every inbound in the list, reusing the single-delete
  804. // path per id. Failures are recorded in Skipped and processing continues for
  805. // the rest; the aggregated needRestart is returned so the caller restarts
  806. // xray at most once.
  807. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  808. result := BulkDelInboundResult{}
  809. needRestart := false
  810. for _, id := range ids {
  811. r, err := s.DelInbound(id)
  812. if err != nil {
  813. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  814. continue
  815. }
  816. result.Deleted++
  817. if r {
  818. needRestart = true
  819. }
  820. }
  821. return result, needRestart, nil
  822. }
  823. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  824. db := database.GetDB()
  825. inbound := &model.Inbound{}
  826. err := db.Model(model.Inbound{}).First(inbound, id).Error
  827. if err != nil {
  828. return nil, err
  829. }
  830. return inbound, nil
  831. }
  832. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  833. db := database.GetDB()
  834. inbound := &model.Inbound{}
  835. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  836. if err != nil {
  837. return nil, err
  838. }
  839. s.enrichClientStats(db, []*model.Inbound{inbound})
  840. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  841. return inbound, nil
  842. }
  843. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  844. inbound, err := s.GetInbound(id)
  845. if err != nil {
  846. return false, err
  847. }
  848. if inbound.Enable == enable {
  849. return false, nil
  850. }
  851. db := database.GetDB()
  852. if err := db.Transaction(func(tx *gorm.DB) error {
  853. if err := tx.Model(model.Inbound{}).Where("id = ?", id).
  854. Update("enable", enable).Error; err != nil {
  855. return err
  856. }
  857. if inbound.NodeID != nil {
  858. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  859. }
  860. return nil
  861. }); err != nil {
  862. return false, err
  863. }
  864. inbound.Enable = enable
  865. needRestart := false
  866. rt, push, _, perr := s.nodePushPlan(inbound)
  867. if perr != nil {
  868. return false, perr
  869. }
  870. // Remote nodes interpret DelInbound as a real row delete (it hits
  871. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  872. // switch on a remote inbound used to wipe the row entirely (#4402).
  873. // PATCH the remote row via UpdateInbound instead — preserves the
  874. // settings/client history and just flips the enable flag.
  875. if inbound.NodeID != nil {
  876. if push {
  877. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  878. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  879. }
  880. }
  881. return false, nil
  882. }
  883. if !push {
  884. return true, nil
  885. }
  886. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  887. !strings.Contains(err.Error(), "not found") {
  888. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  889. needRestart = true
  890. }
  891. if !enable {
  892. return needRestart, nil
  893. }
  894. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  895. if err != nil {
  896. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  897. return true, nil
  898. }
  899. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  900. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  901. needRestart = true
  902. }
  903. return needRestart, nil
  904. }
  905. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  906. // Normalize streamSettings based on protocol
  907. s.normalizeStreamSettings(inbound)
  908. s.normalizeMtprotoSecret(inbound)
  909. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  910. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  911. if err != nil {
  912. return inbound, false, err
  913. }
  914. if conflict != nil {
  915. return inbound, false, common.NewError(conflict.String())
  916. }
  917. oldInbound, err := s.GetInbound(inbound.Id)
  918. if err != nil {
  919. return inbound, false, err
  920. }
  921. inbound.NodeID = oldInbound.NodeID
  922. // Capture the pre-edit routing state before oldInbound.Settings is replaced
  923. // with the new settings further down, then ensure a routed inbound keeps a
  924. // stable egress port (reusing the one already stored).
  925. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  926. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  927. return inbound, false, err
  928. }
  929. tag := oldInbound.Tag
  930. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  931. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  932. needRestart := false
  933. // Persist the client-stat sync, settings munging, runtime push and inbound
  934. // save as one transaction routed through the serial traffic writer, so it
  935. // never runs concurrently with the @every 5s traffic poll. Both touch
  936. // client_traffics and inbounds in opposite order, which Postgres aborts as a
  937. // deadlock (40P01); serializing removes the contention (runSerializedTx).
  938. //
  939. // The runtime push stays inside the transaction here (unlike the client-edit
  940. // paths that apply it after commit): EnsureInboundTagAllowed must reach the
  941. // node before the central row is committed, or a "selected"-mode node would
  942. // sweep the renamed inbound on its next pull. Inbound edits are rare, so
  943. // holding the writer across the node call is an acceptable trade.
  944. txErr := runSerializedTx(func(tx *gorm.DB) error {
  945. if err := s.updateClientTraffics(tx, oldInbound, inbound); err != nil {
  946. return err
  947. }
  948. // Ensure created_at and updated_at exist in inbound.Settings clients
  949. {
  950. var oldSettings map[string]any
  951. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  952. emailToCreated := map[string]int64{}
  953. emailToUpdated := map[string]int64{}
  954. if oldSettings != nil {
  955. if oc, ok := oldSettings["clients"].([]any); ok {
  956. for _, it := range oc {
  957. if m, ok2 := it.(map[string]any); ok2 {
  958. if email, ok3 := m["email"].(string); ok3 {
  959. switch v := m["created_at"].(type) {
  960. case float64:
  961. emailToCreated[email] = int64(v)
  962. case int64:
  963. emailToCreated[email] = v
  964. }
  965. switch v := m["updated_at"].(type) {
  966. case float64:
  967. emailToUpdated[email] = int64(v)
  968. case int64:
  969. emailToUpdated[email] = v
  970. }
  971. }
  972. }
  973. }
  974. }
  975. }
  976. var newSettings map[string]any
  977. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  978. now := time.Now().Unix() * 1000
  979. if nSlice, ok := newSettings["clients"].([]any); ok {
  980. for i := range nSlice {
  981. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  982. email, _ := m["email"].(string)
  983. if _, ok3 := m["created_at"]; !ok3 {
  984. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  985. m["created_at"] = v
  986. } else {
  987. m["created_at"] = now
  988. }
  989. }
  990. // Preserve client's updated_at if present; do not bump on parent inbound update
  991. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  992. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  993. m["updated_at"] = v
  994. }
  995. }
  996. nSlice[i] = m
  997. }
  998. }
  999. newSettings["clients"] = nSlice
  1000. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  1001. inbound.Settings = string(bs)
  1002. }
  1003. }
  1004. }
  1005. }
  1006. // A Shadowsocks-2022 method change resizes the key, but existing client PSKs
  1007. // keep their old length and would be rejected by xray. Regenerate mismatched
  1008. // client keys so the inbound stays connectable.
  1009. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1010. inbound.Settings = normalized
  1011. logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
  1012. }
  1013. // Re-gate Vision flow now that the new stream/encryption is known: if this
  1014. // VLESS inbound just became flow-eligible (e.g. vlessenc was enabled on an
  1015. // XHTTP inbound), restore Vision for clients whose intended flow is Vision
  1016. // but was stripped while the inbound was ineligible.
  1017. if restored, changed := s.restoreVisionFlowForEligibleInbound(tx, inbound.Settings, inbound.StreamSettings, inbound.Protocol); changed {
  1018. inbound.Settings = restored
  1019. }
  1020. oldInbound.Total = inbound.Total
  1021. oldInbound.Remark = inbound.Remark
  1022. oldInbound.SubSortIndex = inbound.SubSortIndex
  1023. oldInbound.Enable = inbound.Enable
  1024. oldInbound.ExpiryTime = inbound.ExpiryTime
  1025. oldInbound.TrafficReset = inbound.TrafficReset
  1026. oldInbound.Listen = inbound.Listen
  1027. oldInbound.Port = inbound.Port
  1028. oldInbound.Protocol = inbound.Protocol
  1029. oldInbound.Settings = inbound.Settings
  1030. oldInbound.StreamSettings = inbound.StreamSettings
  1031. oldInbound.Sniffing = inbound.Sniffing
  1032. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  1033. normalizeInboundShareAddress(oldInbound)
  1034. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  1035. inbound.ShareAddr = oldInbound.ShareAddr
  1036. } else {
  1037. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1038. return err
  1039. }
  1040. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  1041. oldInbound.ShareAddr = inbound.ShareAddr
  1042. }
  1043. if oldTagWasAuto && inbound.Tag == tag {
  1044. inbound.Tag = ""
  1045. }
  1046. resolvedTag, err := s.resolveInboundTag(inbound, inbound.Id)
  1047. if err != nil {
  1048. return err
  1049. }
  1050. oldInbound.Tag = resolvedTag
  1051. inbound.Tag = oldInbound.Tag
  1052. rt, push, _, perr := s.nodePushPlan(oldInbound)
  1053. if perr != nil {
  1054. return perr
  1055. }
  1056. if oldInbound.NodeID == nil {
  1057. if !push {
  1058. needRestart = true
  1059. } else {
  1060. oldSnapshot := *oldInbound
  1061. oldSnapshot.Tag = tag
  1062. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  1063. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  1064. }
  1065. if inbound.Enable {
  1066. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  1067. if err2 != nil {
  1068. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1069. needRestart = true
  1070. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  1071. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  1072. } else {
  1073. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1074. needRestart = true
  1075. }
  1076. }
  1077. }
  1078. } else if push {
  1079. oldSnapshot := *oldInbound
  1080. oldSnapshot.Tag = tag
  1081. if !inbound.Enable {
  1082. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  1083. logger.Warning("Unable to disable inbound on", rt.Name(), ":", err2)
  1084. }
  1085. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  1086. logger.Warning("Unable to update inbound on", rt.Name(), ":", err2)
  1087. }
  1088. }
  1089. // A rename must allow the new tag before the inbound row is committed, or a
  1090. // node in "selected" sync mode would sweep the renamed central row on the
  1091. // next pull.
  1092. if oldInbound.NodeID != nil {
  1093. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*oldInbound.NodeID, oldInbound.Tag); aErr != nil {
  1094. logger.Warning("allow inbound tag on node failed:", aErr)
  1095. }
  1096. }
  1097. if err := tx.Save(oldInbound).Error; err != nil {
  1098. return err
  1099. }
  1100. newClients, gcErr := s.GetClients(oldInbound)
  1101. if gcErr != nil {
  1102. return gcErr
  1103. }
  1104. if err := s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  1105. return err
  1106. }
  1107. if oldInbound.NodeID != nil {
  1108. if err := (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID); err != nil {
  1109. return err
  1110. }
  1111. }
  1112. // (Re)generate the Xray config whenever routing was or is now enabled, so
  1113. // the egress SOCKS bridge is added, moved, or dropped to match the new
  1114. // settings.
  1115. if mtprotoRoutesThroughXray(inbound) || oldRoutedMtproto {
  1116. needRestart = true
  1117. }
  1118. return nil
  1119. })
  1120. if txErr != nil {
  1121. return inbound, false, txErr
  1122. }
  1123. // After the rename is committed, point any routing rules / loopback outbounds
  1124. // in xrayTemplateConfig at the new tag (oldInbound.Tag now holds the resolved
  1125. // new tag; tag holds the pre-edit one). Done post-commit so a sync failure
  1126. // can't roll back the inbound edit.
  1127. if tag != oldInbound.Tag {
  1128. if routingChanged, syncErr := (&XraySettingService{}).PropagateInboundTagRename(tag, oldInbound.Tag); syncErr != nil {
  1129. logger.Warning("UpdateInbound: sync routing on tag rename failed:", syncErr)
  1130. } else if routingChanged {
  1131. needRestart = true
  1132. }
  1133. }
  1134. return inbound, needRestart, nil
  1135. }
  1136. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1137. if inbound == nil {
  1138. return nil, fmt.Errorf("inbound is nil")
  1139. }
  1140. runtimeInbound := *inbound
  1141. settings := map[string]any{}
  1142. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1143. return nil, err
  1144. }
  1145. clients, ok := settings["clients"].([]any)
  1146. if !ok {
  1147. return &runtimeInbound, nil
  1148. }
  1149. var clientStats []xray.ClientTraffic
  1150. err := tx.Model(xray.ClientTraffic{}).
  1151. Where("inbound_id = ?", inbound.Id).
  1152. Select("email", "enable").
  1153. Find(&clientStats).Error
  1154. if err != nil {
  1155. return nil, err
  1156. }
  1157. enableMap := make(map[string]bool, len(clientStats))
  1158. for _, clientTraffic := range clientStats {
  1159. enableMap[clientTraffic.Email] = clientTraffic.Enable
  1160. }
  1161. finalClients := make([]any, 0, len(clients))
  1162. for _, client := range clients {
  1163. c, ok := client.(map[string]any)
  1164. if !ok {
  1165. continue
  1166. }
  1167. email, _ := c["email"].(string)
  1168. if enable, exists := enableMap[email]; exists && !enable {
  1169. continue
  1170. }
  1171. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  1172. continue
  1173. }
  1174. finalClients = append(finalClients, c)
  1175. }
  1176. settings["clients"] = finalClients
  1177. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1178. if err != nil {
  1179. return nil, err
  1180. }
  1181. runtimeInbound.Settings = string(modifiedSettings)
  1182. return &runtimeInbound, nil
  1183. }
  1184. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  1185. // list: removes rows for emails that disappeared, inserts rows for newly-added
  1186. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  1187. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  1188. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  1189. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  1190. oldClients, err := s.GetClients(oldInbound)
  1191. if err != nil {
  1192. return err
  1193. }
  1194. newClients, err := s.GetClients(newInbound)
  1195. if err != nil {
  1196. return err
  1197. }
  1198. // Email is the unique key for ClientTraffic rows. Clients without an
  1199. // email have no stats row to sync — skip them on both sides instead of
  1200. // risking a unique-constraint hit or accidental delete of an unrelated row.
  1201. oldEmails := make(map[string]struct{}, len(oldClients))
  1202. for i := range oldClients {
  1203. if oldClients[i].Email == "" {
  1204. continue
  1205. }
  1206. oldEmails[oldClients[i].Email] = struct{}{}
  1207. }
  1208. newEmails := make(map[string]struct{}, len(newClients))
  1209. for i := range newClients {
  1210. if newClients[i].Email == "" {
  1211. continue
  1212. }
  1213. newEmails[newClients[i].Email] = struct{}{}
  1214. }
  1215. // Drop stats rows for removed emails — but not when a sibling inbound
  1216. // still references the email, since the row is the shared accumulator.
  1217. for i := range oldClients {
  1218. email := oldClients[i].Email
  1219. if email == "" {
  1220. continue
  1221. }
  1222. if _, kept := newEmails[email]; kept {
  1223. continue
  1224. }
  1225. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  1226. if err != nil {
  1227. return err
  1228. }
  1229. if stillUsed {
  1230. continue
  1231. }
  1232. if err := s.DelClientStat(tx, email); err != nil {
  1233. return err
  1234. }
  1235. // Keep inbound_client_ips in sync when the inbound edit drops an
  1236. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  1237. if err := s.DelClientIPs(tx, email); err != nil {
  1238. return err
  1239. }
  1240. }
  1241. for i := range newClients {
  1242. email := newClients[i].Email
  1243. if email == "" {
  1244. continue
  1245. }
  1246. if _, existed := oldEmails[email]; existed {
  1247. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  1248. return err
  1249. }
  1250. continue
  1251. }
  1252. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  1253. return err
  1254. }
  1255. }
  1256. return nil
  1257. }
  1258. func (s *InboundService) GetInboundTags() (string, error) {
  1259. db := database.GetDB()
  1260. var inboundTags []string
  1261. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1262. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1263. return "", err
  1264. }
  1265. tags, _ := json.Marshal(inboundTags)
  1266. return string(tags), nil
  1267. }
  1268. func (s *InboundService) GetClientReverseTags() (string, error) {
  1269. db := database.GetDB()
  1270. var inbounds []model.Inbound
  1271. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1272. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1273. return "[]", err
  1274. }
  1275. tagSet := make(map[string]struct{})
  1276. for _, inbound := range inbounds {
  1277. var settings map[string]any
  1278. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1279. continue
  1280. }
  1281. clients, ok := settings["clients"].([]any)
  1282. if !ok {
  1283. continue
  1284. }
  1285. for _, client := range clients {
  1286. clientMap, ok := client.(map[string]any)
  1287. if !ok {
  1288. continue
  1289. }
  1290. reverse, ok := clientMap["reverse"].(map[string]any)
  1291. if !ok {
  1292. continue
  1293. }
  1294. tag, _ := reverse["tag"].(string)
  1295. tag = strings.TrimSpace(tag)
  1296. if tag != "" {
  1297. tagSet[tag] = struct{}{}
  1298. }
  1299. }
  1300. }
  1301. rawTags := make([]string, 0, len(tagSet))
  1302. for tag := range tagSet {
  1303. rawTags = append(rawTags, tag)
  1304. }
  1305. sort.Strings(rawTags)
  1306. result, _ := json.Marshal(rawTags)
  1307. return string(result), nil
  1308. }
  1309. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1310. db := database.GetDB()
  1311. var inbounds []*model.Inbound
  1312. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1313. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1314. return nil, err
  1315. }
  1316. return inbounds, nil
  1317. }