inbound.go 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412
  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. tx.Commit()
  624. if markDirty && inbound.NodeID != nil {
  625. if dErr := (&NodeService{}).MarkNodeDirty(*inbound.NodeID); dErr != nil {
  626. logger.Warning("mark node dirty failed:", dErr)
  627. }
  628. }
  629. }()
  630. // Omit the ClientStats has-many association: GORM's cascade would INSERT
  631. // those rows with an ON CONFLICT target on the primary key only, which
  632. // collides with the globally-unique client_traffics.email when an imported
  633. // inbound carries clients that another inbound already created (e.g.
  634. // importing two inbounds that share the same clients). We insert the stats
  635. // ourselves below with the same email-conflict guard AddClientStat uses.
  636. err = tx.Omit("ClientStats").Save(inbound).Error
  637. if err != nil {
  638. return inbound, false, err
  639. }
  640. // Imported stats first, so their traffic counters survive; emails that
  641. // already own a (shared) row are skipped instead of tripping the unique
  642. // constraint.
  643. for i := range inbound.ClientStats {
  644. if inbound.ClientStats[i].Email == "" {
  645. continue
  646. }
  647. inbound.ClientStats[i].Id = 0
  648. inbound.ClientStats[i].InboundId = inbound.Id
  649. if err = tx.Clauses(clause.OnConflict{
  650. Columns: []clause.Column{{Name: "email"}},
  651. DoNothing: true,
  652. }).Create(&inbound.ClientStats[i]).Error; err != nil {
  653. return inbound, false, err
  654. }
  655. }
  656. // Then make sure every client has a stats row. AddClientStat is a no-op
  657. // where one exists (including the rows just inserted), and fills the gap
  658. // for clients an import payload didn't carry stats for.
  659. for _, client := range clients {
  660. if err = s.AddClientStat(tx, inbound.Id, &client); err != nil {
  661. return inbound, false, err
  662. }
  663. }
  664. if err = s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  665. return inbound, false, err
  666. }
  667. // Legacy import: an inbound exported from a build that predated the hosts
  668. // table carries its external proxies inline in streamSettings.externalProxy.
  669. // The startup migration that converts those to host rows runs once and is
  670. // gated off afterwards, so it never sees a freshly imported inbound —
  671. // reproduce it here. No-op for inbounds without externalProxy (everything the
  672. // current UI builds), so this only fires on such imports.
  673. if _, err = database.CreateHostsFromExternalProxy(tx, inbound.Id, inbound.StreamSettings); err != nil {
  674. return inbound, false, err
  675. }
  676. // Before the deferred commit, so a node in "selected" sync mode cannot
  677. // sweep the new central row in the gap before its tag is allowed.
  678. if inbound.NodeID != nil {
  679. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*inbound.NodeID, inbound.Tag); aErr != nil {
  680. logger.Warning("allow inbound tag on node failed:", aErr)
  681. }
  682. }
  683. needRestart := false
  684. if inbound.Enable {
  685. rt, push, dirty, perr := s.nodePushPlan(inbound)
  686. if perr != nil {
  687. err = perr
  688. return inbound, false, err
  689. }
  690. if dirty {
  691. markDirty = true
  692. }
  693. if push {
  694. if err1 := rt.AddInbound(context.Background(), inbound); err1 == nil {
  695. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  696. } else {
  697. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  698. if inbound.NodeID != nil {
  699. markDirty = true
  700. } else {
  701. needRestart = true
  702. }
  703. }
  704. }
  705. }
  706. // A routed mtproto inbound is not an Xray inbound itself, so the runtime
  707. // push above only (re)starts the mtg sidecar. The egress SOCKS bridge lives
  708. // in the generated config, so force a regen to wire it in.
  709. if mtprotoRoutesThroughXray(inbound) {
  710. needRestart = true
  711. }
  712. return inbound, needRestart, err
  713. }
  714. func (s *InboundService) DelInbound(id int) (bool, error) {
  715. db := database.GetDB()
  716. needRestart := false
  717. markDirty := false
  718. var ib model.Inbound
  719. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  720. if loadErr == nil {
  721. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  722. if shouldPushToRuntime {
  723. rt, push, dirty, perr := s.nodePushPlan(&ib)
  724. if perr != nil {
  725. logger.Warning("DelInbound: node lookup failed, deleting central row anyway:", perr)
  726. markDirty = true
  727. } else if push {
  728. if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  729. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  730. } else {
  731. logger.Warning("DelInbound on", rt.Name(), "failed, deleting central row anyway:", err1)
  732. if ib.NodeID == nil {
  733. needRestart = true
  734. } else {
  735. markDirty = true
  736. }
  737. }
  738. } else if ib.NodeID == nil {
  739. needRestart = true
  740. } else if dirty {
  741. markDirty = true
  742. }
  743. } else {
  744. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  745. }
  746. } else {
  747. logger.Debug("DelInbound: inbound not found, id:", id)
  748. }
  749. if err := s.clientService.DetachInbound(db, id); err != nil {
  750. return false, err
  751. }
  752. // Drop the deleted inbound's tag from any routing rules / loopback outbounds
  753. // in xrayTemplateConfig so they don't point at a tag that no longer exists.
  754. if loadErr == nil && ib.Tag != "" {
  755. if routingChanged, syncErr := (&XraySettingService{}).RemoveInboundTagReferences(ib.Tag); syncErr != nil {
  756. logger.Warning("DelInbound: sync routing on inbound delete failed:", syncErr)
  757. } else if routingChanged {
  758. needRestart = true
  759. }
  760. }
  761. if err := db.Delete(model.Inbound{}, id).Error; err != nil {
  762. return needRestart, err
  763. }
  764. // Hosts have no hard FK; drop the inbound's hosts alongside it.
  765. if err := db.Where("inbound_id = ?", id).Delete(&model.Host{}).Error; err != nil {
  766. return needRestart, err
  767. }
  768. if markDirty && ib.NodeID != nil {
  769. if dErr := (&NodeService{}).MarkNodeDirty(*ib.NodeID); dErr != nil {
  770. logger.Warning("mark node dirty failed:", dErr)
  771. }
  772. }
  773. if !database.IsPostgres() {
  774. var count int64
  775. if err := db.Model(&model.Inbound{}).Count(&count).Error; err != nil {
  776. return needRestart, err
  777. }
  778. if count == 0 {
  779. if err := db.Exec("DELETE FROM sqlite_sequence WHERE name = ?", "inbounds").Error; err != nil {
  780. return needRestart, err
  781. }
  782. }
  783. }
  784. // Drop the egress SOCKS bridge a routed mtproto inbound left in the config.
  785. if mtprotoRoutesThroughXray(&ib) {
  786. needRestart = true
  787. }
  788. return needRestart, nil
  789. }
  790. type BulkDelInboundResult struct {
  791. Deleted int `json:"deleted"`
  792. Skipped []BulkDelInboundReport `json:"skipped,omitempty"`
  793. }
  794. type BulkDelInboundReport struct {
  795. Id int `json:"id"`
  796. Reason string `json:"reason"`
  797. }
  798. // DelInbounds removes every inbound in the list, reusing the single-delete
  799. // path per id. Failures are recorded in Skipped and processing continues for
  800. // the rest; the aggregated needRestart is returned so the caller restarts
  801. // xray at most once.
  802. func (s *InboundService) DelInbounds(ids []int) (BulkDelInboundResult, bool, error) {
  803. result := BulkDelInboundResult{}
  804. needRestart := false
  805. for _, id := range ids {
  806. r, err := s.DelInbound(id)
  807. if err != nil {
  808. result.Skipped = append(result.Skipped, BulkDelInboundReport{Id: id, Reason: err.Error()})
  809. continue
  810. }
  811. result.Deleted++
  812. if r {
  813. needRestart = true
  814. }
  815. }
  816. return result, needRestart, nil
  817. }
  818. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  819. db := database.GetDB()
  820. inbound := &model.Inbound{}
  821. err := db.Model(model.Inbound{}).First(inbound, id).Error
  822. if err != nil {
  823. return nil, err
  824. }
  825. return inbound, nil
  826. }
  827. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  828. db := database.GetDB()
  829. inbound := &model.Inbound{}
  830. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  831. if err != nil {
  832. return nil, err
  833. }
  834. s.enrichClientStats(db, []*model.Inbound{inbound})
  835. s.overlayInboundsClientStats(db, []*model.Inbound{inbound})
  836. return inbound, nil
  837. }
  838. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  839. inbound, err := s.GetInbound(id)
  840. if err != nil {
  841. return false, err
  842. }
  843. if inbound.Enable == enable {
  844. return false, nil
  845. }
  846. db := database.GetDB()
  847. if err := db.Model(model.Inbound{}).Where("id = ?", id).
  848. Update("enable", enable).Error; err != nil {
  849. return false, err
  850. }
  851. inbound.Enable = enable
  852. needRestart := false
  853. rt, push, dirty, perr := s.nodePushPlan(inbound)
  854. if perr != nil {
  855. return false, perr
  856. }
  857. // Remote nodes interpret DelInbound as a real row delete (it hits
  858. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  859. // switch on a remote inbound used to wipe the row entirely (#4402).
  860. // PATCH the remote row via UpdateInbound instead — preserves the
  861. // settings/client history and just flips the enable flag.
  862. if inbound.NodeID != nil {
  863. if push {
  864. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  865. logger.Warning("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  866. dirty = true
  867. }
  868. }
  869. if dirty {
  870. if dErr := (&NodeService{}).MarkNodeDirty(*inbound.NodeID); dErr != nil {
  871. logger.Warning("mark node dirty failed:", dErr)
  872. }
  873. }
  874. return false, nil
  875. }
  876. if !push {
  877. return true, nil
  878. }
  879. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  880. !strings.Contains(err.Error(), "not found") {
  881. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  882. needRestart = true
  883. }
  884. if !enable {
  885. return needRestart, nil
  886. }
  887. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  888. if err != nil {
  889. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  890. return true, nil
  891. }
  892. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  893. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  894. needRestart = true
  895. }
  896. return needRestart, nil
  897. }
  898. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  899. // Normalize streamSettings based on protocol
  900. s.normalizeStreamSettings(inbound)
  901. s.normalizeMtprotoSecret(inbound)
  902. inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
  903. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  904. if err != nil {
  905. return inbound, false, err
  906. }
  907. if conflict != nil {
  908. return inbound, false, common.NewError(conflict.String())
  909. }
  910. oldInbound, err := s.GetInbound(inbound.Id)
  911. if err != nil {
  912. return inbound, false, err
  913. }
  914. inbound.NodeID = oldInbound.NodeID
  915. // Capture the pre-edit routing state before oldInbound.Settings is replaced
  916. // with the new settings further down, then ensure a routed inbound keeps a
  917. // stable egress port (reusing the one already stored).
  918. oldRoutedMtproto := mtprotoRoutesThroughXray(oldInbound)
  919. if err := s.normalizeMtprotoXrayPort(inbound, oldInbound.Settings); err != nil {
  920. return inbound, false, err
  921. }
  922. tag := oldInbound.Tag
  923. oldBits := inboundTransports(oldInbound.Protocol, oldInbound.StreamSettings, oldInbound.Settings)
  924. oldTagWasAuto := isAutoGeneratedTag(tag, oldInbound.Port, oldInbound.NodeID, oldBits)
  925. needRestart := false
  926. markDirty := false
  927. // Persist the client-stat sync, settings munging, runtime push and inbound
  928. // save as one transaction routed through the serial traffic writer, so it
  929. // never runs concurrently with the @every 5s traffic poll. Both touch
  930. // client_traffics and inbounds in opposite order, which Postgres aborts as a
  931. // deadlock (40P01); serializing removes the contention (runSerializedTx).
  932. //
  933. // The runtime push stays inside the transaction here (unlike the client-edit
  934. // paths that apply it after commit): EnsureInboundTagAllowed must reach the
  935. // node before the central row is committed, or a "selected"-mode node would
  936. // sweep the renamed inbound on its next pull. Inbound edits are rare, so
  937. // holding the writer across the node call is an acceptable trade.
  938. txErr := runSerializedTx(func(tx *gorm.DB) error {
  939. if err := s.updateClientTraffics(tx, oldInbound, inbound); err != nil {
  940. return err
  941. }
  942. // Ensure created_at and updated_at exist in inbound.Settings clients
  943. {
  944. var oldSettings map[string]any
  945. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  946. emailToCreated := map[string]int64{}
  947. emailToUpdated := map[string]int64{}
  948. if oldSettings != nil {
  949. if oc, ok := oldSettings["clients"].([]any); ok {
  950. for _, it := range oc {
  951. if m, ok2 := it.(map[string]any); ok2 {
  952. if email, ok3 := m["email"].(string); ok3 {
  953. switch v := m["created_at"].(type) {
  954. case float64:
  955. emailToCreated[email] = int64(v)
  956. case int64:
  957. emailToCreated[email] = v
  958. }
  959. switch v := m["updated_at"].(type) {
  960. case float64:
  961. emailToUpdated[email] = int64(v)
  962. case int64:
  963. emailToUpdated[email] = v
  964. }
  965. }
  966. }
  967. }
  968. }
  969. }
  970. var newSettings map[string]any
  971. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  972. now := time.Now().Unix() * 1000
  973. if nSlice, ok := newSettings["clients"].([]any); ok {
  974. for i := range nSlice {
  975. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  976. email, _ := m["email"].(string)
  977. if _, ok3 := m["created_at"]; !ok3 {
  978. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  979. m["created_at"] = v
  980. } else {
  981. m["created_at"] = now
  982. }
  983. }
  984. // Preserve client's updated_at if present; do not bump on parent inbound update
  985. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  986. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  987. m["updated_at"] = v
  988. }
  989. }
  990. nSlice[i] = m
  991. }
  992. }
  993. newSettings["clients"] = nSlice
  994. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  995. inbound.Settings = string(bs)
  996. }
  997. }
  998. }
  999. }
  1000. // A Shadowsocks-2022 method change resizes the key, but existing client PSKs
  1001. // keep their old length and would be rejected by xray. Regenerate mismatched
  1002. // client keys so the inbound stays connectable.
  1003. if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed {
  1004. inbound.Settings = normalized
  1005. logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)")
  1006. }
  1007. // Re-gate Vision flow now that the new stream/encryption is known: if this
  1008. // VLESS inbound just became flow-eligible (e.g. vlessenc was enabled on an
  1009. // XHTTP inbound), restore Vision for clients whose intended flow is Vision
  1010. // but was stripped while the inbound was ineligible.
  1011. if restored, changed := s.restoreVisionFlowForEligibleInbound(tx, inbound.Settings, inbound.StreamSettings, inbound.Protocol); changed {
  1012. inbound.Settings = restored
  1013. }
  1014. oldInbound.Total = inbound.Total
  1015. oldInbound.Remark = inbound.Remark
  1016. oldInbound.SubSortIndex = inbound.SubSortIndex
  1017. oldInbound.Enable = inbound.Enable
  1018. oldInbound.ExpiryTime = inbound.ExpiryTime
  1019. oldInbound.TrafficReset = inbound.TrafficReset
  1020. oldInbound.Listen = inbound.Listen
  1021. oldInbound.Port = inbound.Port
  1022. oldInbound.Protocol = inbound.Protocol
  1023. oldInbound.Settings = inbound.Settings
  1024. oldInbound.StreamSettings = inbound.StreamSettings
  1025. oldInbound.Sniffing = inbound.Sniffing
  1026. if strings.TrimSpace(inbound.ShareAddrStrategy) == "" {
  1027. normalizeInboundShareAddress(oldInbound)
  1028. inbound.ShareAddrStrategy = oldInbound.ShareAddrStrategy
  1029. inbound.ShareAddr = oldInbound.ShareAddr
  1030. } else {
  1031. if err := normalizeInboundShareAddressStrict(inbound); err != nil {
  1032. return err
  1033. }
  1034. oldInbound.ShareAddrStrategy = inbound.ShareAddrStrategy
  1035. oldInbound.ShareAddr = inbound.ShareAddr
  1036. }
  1037. if oldTagWasAuto && inbound.Tag == tag {
  1038. inbound.Tag = ""
  1039. }
  1040. resolvedTag, err := s.resolveInboundTag(inbound, inbound.Id)
  1041. if err != nil {
  1042. return err
  1043. }
  1044. oldInbound.Tag = resolvedTag
  1045. inbound.Tag = oldInbound.Tag
  1046. rt, push, dirty, perr := s.nodePushPlan(oldInbound)
  1047. if perr != nil {
  1048. return perr
  1049. }
  1050. if dirty {
  1051. markDirty = true
  1052. }
  1053. if oldInbound.NodeID == nil {
  1054. if !push {
  1055. needRestart = true
  1056. } else {
  1057. oldSnapshot := *oldInbound
  1058. oldSnapshot.Tag = tag
  1059. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  1060. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  1061. }
  1062. if inbound.Enable {
  1063. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  1064. if err2 != nil {
  1065. logger.Debug("Unable to prepare runtime inbound config:", err2)
  1066. needRestart = true
  1067. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  1068. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  1069. } else {
  1070. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  1071. needRestart = true
  1072. }
  1073. }
  1074. }
  1075. } else if push {
  1076. oldSnapshot := *oldInbound
  1077. oldSnapshot.Tag = tag
  1078. if !inbound.Enable {
  1079. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  1080. logger.Warning("Unable to disable inbound on", rt.Name(), ":", err2)
  1081. markDirty = true
  1082. }
  1083. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  1084. logger.Warning("Unable to update inbound on", rt.Name(), ":", err2)
  1085. markDirty = true
  1086. }
  1087. }
  1088. // A rename must allow the new tag before the inbound row is committed, or a
  1089. // node in "selected" sync mode would sweep the renamed central row on the
  1090. // next pull.
  1091. if oldInbound.NodeID != nil {
  1092. if aErr := (&NodeService{}).EnsureInboundTagAllowed(*oldInbound.NodeID, oldInbound.Tag); aErr != nil {
  1093. logger.Warning("allow inbound tag on node failed:", aErr)
  1094. }
  1095. }
  1096. if err := tx.Save(oldInbound).Error; err != nil {
  1097. return err
  1098. }
  1099. newClients, gcErr := s.GetClients(oldInbound)
  1100. if gcErr != nil {
  1101. return gcErr
  1102. }
  1103. if err := s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  1104. return err
  1105. }
  1106. // (Re)generate the Xray config whenever routing was or is now enabled, so
  1107. // the egress SOCKS bridge is added, moved, or dropped to match the new
  1108. // settings.
  1109. if mtprotoRoutesThroughXray(inbound) || oldRoutedMtproto {
  1110. needRestart = true
  1111. }
  1112. return nil
  1113. })
  1114. if txErr != nil {
  1115. return inbound, false, txErr
  1116. }
  1117. // After the rename is committed, point any routing rules / loopback outbounds
  1118. // in xrayTemplateConfig at the new tag (oldInbound.Tag now holds the resolved
  1119. // new tag; tag holds the pre-edit one). Done post-commit so a sync failure
  1120. // can't roll back the inbound edit.
  1121. if tag != oldInbound.Tag {
  1122. if routingChanged, syncErr := (&XraySettingService{}).PropagateInboundTagRename(tag, oldInbound.Tag); syncErr != nil {
  1123. logger.Warning("UpdateInbound: sync routing on tag rename failed:", syncErr)
  1124. } else if routingChanged {
  1125. needRestart = true
  1126. }
  1127. }
  1128. if markDirty && oldInbound.NodeID != nil {
  1129. if dErr := (&NodeService{}).MarkNodeDirty(*oldInbound.NodeID); dErr != nil {
  1130. logger.Warning("mark node dirty failed:", dErr)
  1131. }
  1132. }
  1133. return inbound, needRestart, nil
  1134. }
  1135. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  1136. if inbound == nil {
  1137. return nil, fmt.Errorf("inbound is nil")
  1138. }
  1139. runtimeInbound := *inbound
  1140. settings := map[string]any{}
  1141. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1142. return nil, err
  1143. }
  1144. clients, ok := settings["clients"].([]any)
  1145. if !ok {
  1146. return &runtimeInbound, nil
  1147. }
  1148. var clientStats []xray.ClientTraffic
  1149. err := tx.Model(xray.ClientTraffic{}).
  1150. Where("inbound_id = ?", inbound.Id).
  1151. Select("email", "enable").
  1152. Find(&clientStats).Error
  1153. if err != nil {
  1154. return nil, err
  1155. }
  1156. enableMap := make(map[string]bool, len(clientStats))
  1157. for _, clientTraffic := range clientStats {
  1158. enableMap[clientTraffic.Email] = clientTraffic.Enable
  1159. }
  1160. finalClients := make([]any, 0, len(clients))
  1161. for _, client := range clients {
  1162. c, ok := client.(map[string]any)
  1163. if !ok {
  1164. continue
  1165. }
  1166. email, _ := c["email"].(string)
  1167. if enable, exists := enableMap[email]; exists && !enable {
  1168. continue
  1169. }
  1170. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  1171. continue
  1172. }
  1173. finalClients = append(finalClients, c)
  1174. }
  1175. settings["clients"] = finalClients
  1176. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1177. if err != nil {
  1178. return nil, err
  1179. }
  1180. runtimeInbound.Settings = string(modifiedSettings)
  1181. return &runtimeInbound, nil
  1182. }
  1183. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  1184. // list: removes rows for emails that disappeared, inserts rows for newly-added
  1185. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  1186. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  1187. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  1188. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  1189. oldClients, err := s.GetClients(oldInbound)
  1190. if err != nil {
  1191. return err
  1192. }
  1193. newClients, err := s.GetClients(newInbound)
  1194. if err != nil {
  1195. return err
  1196. }
  1197. // Email is the unique key for ClientTraffic rows. Clients without an
  1198. // email have no stats row to sync — skip them on both sides instead of
  1199. // risking a unique-constraint hit or accidental delete of an unrelated row.
  1200. oldEmails := make(map[string]struct{}, len(oldClients))
  1201. for i := range oldClients {
  1202. if oldClients[i].Email == "" {
  1203. continue
  1204. }
  1205. oldEmails[oldClients[i].Email] = struct{}{}
  1206. }
  1207. newEmails := make(map[string]struct{}, len(newClients))
  1208. for i := range newClients {
  1209. if newClients[i].Email == "" {
  1210. continue
  1211. }
  1212. newEmails[newClients[i].Email] = struct{}{}
  1213. }
  1214. // Drop stats rows for removed emails — but not when a sibling inbound
  1215. // still references the email, since the row is the shared accumulator.
  1216. for i := range oldClients {
  1217. email := oldClients[i].Email
  1218. if email == "" {
  1219. continue
  1220. }
  1221. if _, kept := newEmails[email]; kept {
  1222. continue
  1223. }
  1224. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  1225. if err != nil {
  1226. return err
  1227. }
  1228. if stillUsed {
  1229. continue
  1230. }
  1231. if err := s.DelClientStat(tx, email); err != nil {
  1232. return err
  1233. }
  1234. // Keep inbound_client_ips in sync when the inbound edit drops an
  1235. // email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
  1236. if err := s.DelClientIPs(tx, email); err != nil {
  1237. return err
  1238. }
  1239. }
  1240. for i := range newClients {
  1241. email := newClients[i].Email
  1242. if email == "" {
  1243. continue
  1244. }
  1245. if _, existed := oldEmails[email]; existed {
  1246. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  1247. return err
  1248. }
  1249. continue
  1250. }
  1251. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  1252. return err
  1253. }
  1254. }
  1255. return nil
  1256. }
  1257. func (s *InboundService) GetInboundTags() (string, error) {
  1258. db := database.GetDB()
  1259. var inboundTags []string
  1260. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1261. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1262. return "", err
  1263. }
  1264. tags, _ := json.Marshal(inboundTags)
  1265. return string(tags), nil
  1266. }
  1267. func (s *InboundService) GetClientReverseTags() (string, error) {
  1268. db := database.GetDB()
  1269. var inbounds []model.Inbound
  1270. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1271. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1272. return "[]", err
  1273. }
  1274. tagSet := make(map[string]struct{})
  1275. for _, inbound := range inbounds {
  1276. var settings map[string]any
  1277. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1278. continue
  1279. }
  1280. clients, ok := settings["clients"].([]any)
  1281. if !ok {
  1282. continue
  1283. }
  1284. for _, client := range clients {
  1285. clientMap, ok := client.(map[string]any)
  1286. if !ok {
  1287. continue
  1288. }
  1289. reverse, ok := clientMap["reverse"].(map[string]any)
  1290. if !ok {
  1291. continue
  1292. }
  1293. tag, _ := reverse["tag"].(string)
  1294. tag = strings.TrimSpace(tag)
  1295. if tag != "" {
  1296. tagSet[tag] = struct{}{}
  1297. }
  1298. }
  1299. }
  1300. rawTags := make([]string, 0, len(tagSet))
  1301. for tag := range tagSet {
  1302. rawTags = append(rawTags, tag)
  1303. }
  1304. sort.Strings(rawTags)
  1305. result, _ := json.Marshal(rawTags)
  1306. return string(result), nil
  1307. }
  1308. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1309. db := database.GetDB()
  1310. var inbounds []*model.Inbound
  1311. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1312. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  1313. return nil, err
  1314. }
  1315. return inbounds, nil
  1316. }