inbound.go 15 KB

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