1
0

inbound.go 16 KB

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