inbound.go 46 KB

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