inbound.go 16 KB

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