inbound.go 72 KB

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