inbound.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. package controller
  2. import (
  3. "encoding/json"
  4. "net"
  5. "strconv"
  6. "strings"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  8. "github.com/mhsanaei/3x-ui/v3/internal/util/wirecodec"
  9. "github.com/mhsanaei/3x-ui/v3/internal/web/middleware"
  10. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  11. "github.com/mhsanaei/3x-ui/v3/internal/web/session"
  12. "github.com/mhsanaei/3x-ui/v3/internal/web/websocket"
  13. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  14. "github.com/gin-gonic/gin"
  15. )
  16. // InboundController handles HTTP requests related to Xray inbounds management.
  17. type InboundController struct {
  18. inboundService service.InboundService
  19. clientService service.ClientService
  20. xrayService service.XrayService
  21. fallbackService service.FallbackService
  22. }
  23. // NewInboundController creates a new InboundController and sets up its routes.
  24. func NewInboundController(g *gin.RouterGroup) *InboundController {
  25. a := &InboundController{}
  26. a.initRouter(g)
  27. return a
  28. }
  29. // broadcastInboundsUpdateClientLimit is the threshold past which we skip the
  30. // full-list push over WebSocket and signal the frontend to re-fetch via REST.
  31. // Mirrors the same heuristic used by the periodic traffic job.
  32. const broadcastInboundsUpdateClientLimit = 5000
  33. // broadcastInboundsUpdate fetches and broadcasts the inbound list for userId.
  34. // At scale (10k+ clients) the marshaled JSON exceeds the WS payload ceiling,
  35. // so we send an invalidate signal instead — frontend re-fetches via REST.
  36. // Skipped entirely when no WebSocket clients are connected.
  37. func (a *InboundController) broadcastInboundsUpdate(userId int) {
  38. if !websocket.HasClients() {
  39. return
  40. }
  41. inbounds, err := a.inboundService.GetInbounds(userId)
  42. if err != nil {
  43. return
  44. }
  45. totalClients := 0
  46. for _, ib := range inbounds {
  47. totalClients += len(ib.ClientStats)
  48. }
  49. if totalClients > broadcastInboundsUpdateClientLimit {
  50. websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
  51. return
  52. }
  53. websocket.BroadcastInbounds(inbounds)
  54. }
  55. // inboundServiceFor tells the service whether this request is a master's
  56. // node-sync push, so the node stores the row instead of re-judging it.
  57. func (a *InboundController) inboundServiceFor(c *gin.Context) *service.InboundService {
  58. svc := a.inboundService
  59. scopeValue, _ := c.Get("api_token_scope")
  60. scope, _ := scopeValue.(string)
  61. // A master enrolled with an admin token (the -getApiToken default) has no
  62. // node-sync scope, so it marks every request it sends instead.
  63. svc.FromNodeSync = model.IsNodeSyncApiScope(scope) || c.GetHeader(wirecodec.MasterPushHeader) != ""
  64. return &svc
  65. }
  66. // initRouter initializes the routes for inbound-related operations.
  67. func (a *InboundController) initRouter(g *gin.RouterGroup) {
  68. g.GET("/list", a.getInbounds)
  69. g.GET("/list/slim", a.getInboundsSlim)
  70. g.GET("/options", a.getInboundOptions)
  71. g.GET("/allLinks", a.getAllInboundLinks)
  72. g.GET("/get/:id", a.getInbound)
  73. g.GET("/:id/fallbacks", a.getFallbacks)
  74. g.POST("/add", a.addInbound)
  75. g.POST("/del/:id", a.delInbound)
  76. g.POST("/bulkDel", a.bulkDelInbounds)
  77. g.POST("/update/:id", a.updateInbound)
  78. g.POST("/setEnable/:id", a.setInboundEnable)
  79. g.POST("/:id/subSortIndex", a.setInboundSubSortIndex)
  80. g.POST("/:id/resetTraffic", a.resetInboundTraffic)
  81. g.POST("/:id/delAllClients", a.delAllInboundClients)
  82. g.POST("/resetAllTraffics", a.resetAllTraffics)
  83. g.POST("/import", a.importInbound)
  84. g.POST("/:id/fallbacks", a.setFallbacks)
  85. g.POST("/pushClientTraffics", a.pushClientTraffics)
  86. }
  87. // getInbounds retrieves the list of inbounds for the logged-in user.
  88. func (a *InboundController) getInbounds(c *gin.Context) {
  89. user := session.GetLoginUser(c)
  90. inbounds, err := a.inboundService.GetInbounds(user.Id)
  91. if err != nil {
  92. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  93. return
  94. }
  95. jsonObj(c, inbounds, nil)
  96. }
  97. // getInboundsSlim is the list-page variant that strips full client
  98. // payloads from settings.clients[]. Detail-view flows still use /get/:id.
  99. func (a *InboundController) getInboundsSlim(c *gin.Context) {
  100. user := session.GetLoginUser(c)
  101. inbounds, err := a.inboundService.GetInboundsSlim(user.Id)
  102. if err != nil {
  103. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  104. return
  105. }
  106. jsonObj(c, inbounds, nil)
  107. }
  108. // getAllInboundLinks returns every inbound's share links across all clients,
  109. // rendered through the same subscription engine the client pages use so the
  110. // remark template (name-only display part) is applied consistently.
  111. func (a *InboundController) getAllInboundLinks(c *gin.Context) {
  112. user := session.GetLoginUser(c)
  113. links, err := a.inboundService.GetAllInboundLinks(resolveHost(c), user.Id)
  114. if err != nil {
  115. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  116. return
  117. }
  118. jsonObj(c, links, nil)
  119. }
  120. // getInboundOptions returns a lightweight projection of the user's inbounds
  121. // (id, remark, protocol, port, tlsFlowCapable) for pickers in the clients UI.
  122. // Avoids shipping per-client settings and traffic stats just to fill a dropdown.
  123. func (a *InboundController) getInboundOptions(c *gin.Context) {
  124. user := session.GetLoginUser(c)
  125. options, err := a.inboundService.GetInboundOptions(user.Id)
  126. if err != nil {
  127. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  128. return
  129. }
  130. jsonObj(c, options, nil)
  131. }
  132. // getInbound retrieves a specific inbound by its ID.
  133. func (a *InboundController) getInbound(c *gin.Context) {
  134. id, err := strconv.Atoi(c.Param("id"))
  135. if err != nil {
  136. jsonMsg(c, I18nWeb(c, "get"), err)
  137. return
  138. }
  139. inbound, err := a.inboundService.GetInboundDetail(id)
  140. if err != nil {
  141. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  142. return
  143. }
  144. jsonObj(c, inbound, nil)
  145. }
  146. // addInbound creates a new inbound configuration.
  147. func (a *InboundController) addInbound(c *gin.Context) {
  148. inbound, ok := middleware.BindAndValidate[model.Inbound](c)
  149. if !ok {
  150. return
  151. }
  152. user := session.GetLoginUser(c)
  153. inbound.UserId = user.Id
  154. // Treat NodeID=0 as "no node" — gin's *int form binding can land on
  155. // 0 when the field is absent or empty, and 0 is never a valid Node
  156. // row id. Without this normalization the runtime layer would try to
  157. // load Node id=0 and surface "record not found".
  158. if inbound.NodeID != nil && *inbound.NodeID == 0 {
  159. inbound.NodeID = nil
  160. }
  161. inbound, needRestart, err := a.inboundServiceFor(c).AddInbound(inbound)
  162. if err != nil {
  163. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  164. return
  165. }
  166. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), inbound, nil)
  167. if needRestart {
  168. a.xrayService.SetToNeedRestart()
  169. }
  170. a.broadcastInboundsUpdate(user.Id)
  171. notifyClientsChanged()
  172. }
  173. // delInbound deletes an inbound configuration by its ID.
  174. func (a *InboundController) delInbound(c *gin.Context) {
  175. id, err := strconv.Atoi(c.Param("id"))
  176. if err != nil {
  177. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundDeleteSuccess"), err)
  178. return
  179. }
  180. needRestart, err := a.inboundService.DelInbound(id)
  181. if err != nil {
  182. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  183. return
  184. }
  185. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundDeleteSuccess"), id, nil)
  186. if needRestart {
  187. a.xrayService.SetToNeedRestart()
  188. }
  189. user := session.GetLoginUser(c)
  190. a.broadcastInboundsUpdate(user.Id)
  191. notifyClientsChanged()
  192. }
  193. type bulkDelInboundsRequest struct {
  194. Ids []int `json:"ids"`
  195. }
  196. // bulkDelInbounds deletes several inbounds in one call. Failures are
  197. // reported per id and the rest still proceed; xray restarts at most once.
  198. func (a *InboundController) bulkDelInbounds(c *gin.Context) {
  199. var req bulkDelInboundsRequest
  200. if err := c.ShouldBindJSON(&req); err != nil {
  201. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  202. return
  203. }
  204. result, needRestart, err := a.inboundService.DelInbounds(req.Ids)
  205. if err != nil {
  206. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  207. return
  208. }
  209. jsonObj(c, result, nil)
  210. if needRestart {
  211. a.xrayService.SetToNeedRestart()
  212. }
  213. user := session.GetLoginUser(c)
  214. a.broadcastInboundsUpdate(user.Id)
  215. notifyClientsChanged()
  216. }
  217. // updateInbound updates an existing inbound configuration.
  218. func (a *InboundController) updateInbound(c *gin.Context) {
  219. id, err := strconv.Atoi(c.Param("id"))
  220. if err != nil {
  221. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  222. return
  223. }
  224. inbound := &model.Inbound{
  225. Id: id,
  226. }
  227. if !middleware.BindAndValidateInto(c, inbound) {
  228. return
  229. }
  230. // Same NodeID=0 → nil normalisation as addInbound. UpdateInbound
  231. // loads the existing row's NodeID from DB anyway (Phase 1 doesn't
  232. // support migrating an inbound between nodes), but normalising here
  233. // keeps the wire shape consistent.
  234. if inbound.NodeID != nil && *inbound.NodeID == 0 {
  235. inbound.NodeID = nil
  236. }
  237. inbound, needRestart, err := a.inboundServiceFor(c).UpdateInbound(inbound)
  238. if err != nil {
  239. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  240. return
  241. }
  242. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), inbound, nil)
  243. if needRestart {
  244. a.xrayService.SetToNeedRestart()
  245. }
  246. user := session.GetLoginUser(c)
  247. a.broadcastInboundsUpdate(user.Id)
  248. notifyClientsChanged()
  249. }
  250. // setInboundSubSortIndex changes only subscription ordering without sending
  251. // the inbound's settings/client payload.
  252. func (a *InboundController) setInboundSubSortIndex(c *gin.Context) {
  253. id, err := strconv.Atoi(c.Param("id"))
  254. if err != nil {
  255. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  256. return
  257. }
  258. type form struct {
  259. SubSortIndex int `json:"subSortIndex" form:"subSortIndex" binding:"required"`
  260. }
  261. var f form
  262. if err := c.ShouldBind(&f); err != nil {
  263. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  264. return
  265. }
  266. if err := a.inboundService.SetInboundSubSortIndex(id, f.SubSortIndex); err != nil {
  267. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  268. return
  269. }
  270. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), nil)
  271. websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
  272. }
  273. func (a *InboundController) setInboundEnable(c *gin.Context) {
  274. id, err := strconv.Atoi(c.Param("id"))
  275. if err != nil {
  276. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  277. return
  278. }
  279. type form struct {
  280. Enable bool `json:"enable" form:"enable"`
  281. }
  282. var f form
  283. if err := c.ShouldBind(&f); err != nil {
  284. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  285. return
  286. }
  287. needRestart, err := a.inboundService.SetInboundEnable(id, f.Enable)
  288. if err != nil {
  289. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  290. return
  291. }
  292. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), nil)
  293. if needRestart {
  294. a.xrayService.SetToNeedRestart()
  295. }
  296. // Cross-admin sync: lightweight invalidate signal (a few hundred bytes)
  297. // instead of fetching + serialising the whole inbound list. Other open
  298. // sessions re-fetch via REST. The toggling admin's own UI already
  299. // updated optimistically.
  300. websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
  301. }
  302. // resetInboundTraffic resets traffic counters for a specific inbound.
  303. func (a *InboundController) resetInboundTraffic(c *gin.Context) {
  304. id, err := strconv.Atoi(c.Param("id"))
  305. if err != nil {
  306. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  307. return
  308. }
  309. err = a.inboundService.ResetInboundTraffic(id)
  310. if err != nil {
  311. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  312. return
  313. } else {
  314. a.xrayService.SetToNeedRestart()
  315. }
  316. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetInboundTrafficSuccess"), nil)
  317. }
  318. // delAllInboundClients removes every client attached to a specific inbound
  319. // while keeping the inbound itself. Internally collects the current email
  320. // list from settings.clients[] and feeds it into ClientService.BulkDelete,
  321. // which handles per-inbound JSON rewriting, runtime user removal, traffic
  322. // row cleanup, and the SyncInbound mapping pass in one optimized cycle.
  323. func (a *InboundController) delAllInboundClients(c *gin.Context) {
  324. id, err := strconv.Atoi(c.Param("id"))
  325. if err != nil {
  326. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  327. return
  328. }
  329. emails, err := a.inboundService.EmailsByInbound(id)
  330. if err != nil {
  331. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  332. return
  333. }
  334. if len(emails) == 0 {
  335. jsonObj(c, service.BulkDeleteResult{}, nil)
  336. return
  337. }
  338. result, needRestart, err := a.clientService.BulkDelete(&a.inboundService, emails, false)
  339. if err != nil {
  340. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  341. return
  342. }
  343. jsonObj(c, result, nil)
  344. if needRestart {
  345. a.xrayService.SetToNeedRestart()
  346. }
  347. user := session.GetLoginUser(c)
  348. a.broadcastInboundsUpdate(user.Id)
  349. notifyClientsChanged()
  350. }
  351. // resetAllTraffics resets all traffic counters across all inbounds.
  352. func (a *InboundController) resetAllTraffics(c *gin.Context) {
  353. err := a.inboundService.ResetAllTraffics()
  354. if err != nil {
  355. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  356. return
  357. } else {
  358. a.xrayService.SetToNeedRestart()
  359. }
  360. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetAllTrafficSuccess"), nil)
  361. }
  362. // pushClientTraffics receives a master panel's aggregated per-client usage
  363. // (see InboundService.AcceptGlobalTraffic for the storage semantics).
  364. func (a *InboundController) pushClientTraffics(c *gin.Context) {
  365. var req struct {
  366. MasterGuid string `json:"masterGuid"`
  367. Traffics []*xray.ClientTraffic `json:"traffics"`
  368. }
  369. if err := c.ShouldBindJSON(&req); err != nil {
  370. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  371. return
  372. }
  373. if err := a.inboundService.AcceptGlobalTraffic(req.MasterGuid, req.Traffics); err != nil {
  374. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  375. return
  376. }
  377. jsonMsg(c, "success", nil)
  378. }
  379. // importInbound imports an inbound configuration from provided data.
  380. func (a *InboundController) importInbound(c *gin.Context) {
  381. inbound := &model.Inbound{}
  382. err := json.Unmarshal([]byte(c.PostForm("data")), inbound)
  383. if err != nil {
  384. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  385. return
  386. }
  387. user := session.GetLoginUser(c)
  388. inbound.Id = 0
  389. inbound.UserId = user.Id
  390. // Node IDs are panel-local and not portable across panels. Drop a node
  391. // reference that is zero or that points to a node which doesn't exist on
  392. // this panel, so a cross-panel export imports as a local inbound instead of
  393. // failing with "record not found" when nodePushPlan looks the node up.
  394. if inbound.NodeID != nil {
  395. if *inbound.NodeID == 0 {
  396. inbound.NodeID = nil
  397. } else if exists, err := (&service.NodeService{}).NodeExists(*inbound.NodeID); err == nil && !exists {
  398. inbound.NodeID = nil
  399. }
  400. }
  401. for index := range inbound.ClientStats {
  402. inbound.ClientStats[index].Id = 0
  403. inbound.ClientStats[index].Enable = true
  404. }
  405. inbound, needRestart, err := a.inboundService.AddInbound(inbound)
  406. if err != nil {
  407. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  408. return
  409. }
  410. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), inbound, nil)
  411. if needRestart {
  412. a.xrayService.SetToNeedRestart()
  413. }
  414. a.broadcastInboundsUpdate(user.Id)
  415. notifyClientsChanged()
  416. }
  417. // resolveHost mirrors SubService.ResolveRequest's host: trusted X-Forwarded-Host,
  418. // else the dialed request Host. X-Real-IP names the visitor, not the panel (#6589).
  419. func resolveHost(c *gin.Context) string {
  420. if isTrustedForwardedRequest(c) {
  421. if h := strings.TrimSpace(c.GetHeader("X-Forwarded-Host")); h != "" {
  422. if i := strings.Index(h, ","); i >= 0 {
  423. h = strings.TrimSpace(h[:i])
  424. }
  425. if hp, _, err := net.SplitHostPort(h); err == nil {
  426. return hp
  427. }
  428. return h
  429. }
  430. }
  431. if h, _, err := net.SplitHostPort(c.Request.Host); err == nil {
  432. return h
  433. }
  434. return c.Request.Host
  435. }
  436. // getFallbacks returns the fallback rules attached to the master inbound.
  437. func (a *InboundController) getFallbacks(c *gin.Context) {
  438. id, err := strconv.Atoi(c.Param("id"))
  439. if err != nil {
  440. jsonMsg(c, I18nWeb(c, "get"), err)
  441. return
  442. }
  443. rows, err := a.fallbackService.GetByMaster(id)
  444. if err != nil {
  445. jsonMsg(c, I18nWeb(c, "get"), err)
  446. return
  447. }
  448. jsonObj(c, rows, nil)
  449. }
  450. // setFallbacks atomically replaces the master inbound's fallback list
  451. // and triggers an Xray restart so the new settings.fallbacks take effect.
  452. func (a *InboundController) setFallbacks(c *gin.Context) {
  453. id, err := strconv.Atoi(c.Param("id"))
  454. if err != nil {
  455. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  456. return
  457. }
  458. type body struct {
  459. Fallbacks []service.FallbackInput `json:"fallbacks"`
  460. }
  461. var b body
  462. if err := c.ShouldBindJSON(&b); err != nil {
  463. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  464. return
  465. }
  466. if err := a.fallbackService.SetByMaster(id, b.Fallbacks); err != nil {
  467. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  468. return
  469. }
  470. a.xrayService.SetToNeedRestart()
  471. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), nil)
  472. }