inbound.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "strconv"
  7. "strings"
  8. "github.com/mhsanaei/3x-ui/v3/database/model"
  9. "github.com/mhsanaei/3x-ui/v3/web/middleware"
  10. "github.com/mhsanaei/3x-ui/v3/web/service"
  11. "github.com/mhsanaei/3x-ui/v3/web/session"
  12. "github.com/mhsanaei/3x-ui/v3/web/websocket"
  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. xrayService service.XrayService
  19. fallbackService service.FallbackService
  20. }
  21. // NewInboundController creates a new InboundController and sets up its routes.
  22. func NewInboundController(g *gin.RouterGroup) *InboundController {
  23. a := &InboundController{}
  24. a.initRouter(g)
  25. return a
  26. }
  27. // broadcastInboundsUpdateClientLimit is the threshold past which we skip the
  28. // full-list push over WebSocket and signal the frontend to re-fetch via REST.
  29. // Mirrors the same heuristic used by the periodic traffic job.
  30. const broadcastInboundsUpdateClientLimit = 5000
  31. // broadcastInboundsUpdate fetches and broadcasts the inbound list for userId.
  32. // At scale (10k+ clients) the marshaled JSON exceeds the WS payload ceiling,
  33. // so we send an invalidate signal instead — frontend re-fetches via REST.
  34. // Skipped entirely when no WebSocket clients are connected.
  35. func (a *InboundController) broadcastInboundsUpdate(userId int) {
  36. if !websocket.HasClients() {
  37. return
  38. }
  39. inbounds, err := a.inboundService.GetInbounds(userId)
  40. if err != nil {
  41. return
  42. }
  43. totalClients := 0
  44. for _, ib := range inbounds {
  45. totalClients += len(ib.ClientStats)
  46. }
  47. if totalClients > broadcastInboundsUpdateClientLimit {
  48. websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
  49. return
  50. }
  51. websocket.BroadcastInbounds(inbounds)
  52. }
  53. // initRouter initializes the routes for inbound-related operations.
  54. func (a *InboundController) initRouter(g *gin.RouterGroup) {
  55. g.GET("/list", a.getInbounds)
  56. g.GET("/list/slim", a.getInboundsSlim)
  57. g.GET("/options", a.getInboundOptions)
  58. g.GET("/get/:id", a.getInbound)
  59. g.GET("/:id/fallbacks", a.getFallbacks)
  60. g.POST("/add", a.addInbound)
  61. g.POST("/del/:id", a.delInbound)
  62. g.POST("/update/:id", a.updateInbound)
  63. g.POST("/setEnable/:id", a.setInboundEnable)
  64. g.POST("/:id/resetTraffic", a.resetInboundTraffic)
  65. g.POST("/resetAllTraffics", a.resetAllTraffics)
  66. g.POST("/import", a.importInbound)
  67. g.POST("/:id/fallbacks", a.setFallbacks)
  68. }
  69. // getInbounds retrieves the list of inbounds for the logged-in user.
  70. func (a *InboundController) getInbounds(c *gin.Context) {
  71. user := session.GetLoginUser(c)
  72. inbounds, err := a.inboundService.GetInbounds(user.Id)
  73. if err != nil {
  74. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  75. return
  76. }
  77. jsonObj(c, inbounds, nil)
  78. }
  79. // getInboundsSlim is the list-page variant that strips full client
  80. // payloads from settings.clients[]. Detail-view flows still use /get/:id.
  81. func (a *InboundController) getInboundsSlim(c *gin.Context) {
  82. user := session.GetLoginUser(c)
  83. inbounds, err := a.inboundService.GetInboundsSlim(user.Id)
  84. if err != nil {
  85. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  86. return
  87. }
  88. jsonObj(c, inbounds, nil)
  89. }
  90. // getInboundOptions returns a lightweight projection of the user's inbounds
  91. // (id, remark, protocol, port, tlsFlowCapable) for pickers in the clients UI.
  92. // Avoids shipping per-client settings and traffic stats just to fill a dropdown.
  93. func (a *InboundController) getInboundOptions(c *gin.Context) {
  94. user := session.GetLoginUser(c)
  95. options, err := a.inboundService.GetInboundOptions(user.Id)
  96. if err != nil {
  97. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  98. return
  99. }
  100. jsonObj(c, options, nil)
  101. }
  102. // getInbound retrieves a specific inbound by its ID.
  103. func (a *InboundController) getInbound(c *gin.Context) {
  104. id, err := strconv.Atoi(c.Param("id"))
  105. if err != nil {
  106. jsonMsg(c, I18nWeb(c, "get"), err)
  107. return
  108. }
  109. inbound, err := a.inboundService.GetInbound(id)
  110. if err != nil {
  111. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  112. return
  113. }
  114. jsonObj(c, inbound, nil)
  115. }
  116. // addInbound creates a new inbound configuration.
  117. func (a *InboundController) addInbound(c *gin.Context) {
  118. inbound, ok := middleware.BindAndValidate[model.Inbound](c)
  119. if !ok {
  120. return
  121. }
  122. user := session.GetLoginUser(c)
  123. inbound.UserId = user.Id
  124. // Treat NodeID=0 as "no node" — gin's *int form binding can land on
  125. // 0 when the field is absent or empty, and 0 is never a valid Node
  126. // row id. Without this normalization the runtime layer would try to
  127. // load Node id=0 and surface "record not found".
  128. if inbound.NodeID != nil && *inbound.NodeID == 0 {
  129. inbound.NodeID = nil
  130. }
  131. // When the central panel deploys an inbound to a remote node, it sends
  132. // the Tag pre-computed (so both DBs agree on the identifier). Local
  133. // UI submits don't include a Tag — we compute one from listen+port
  134. // using the original collision-avoiding scheme.
  135. if inbound.Tag == "" {
  136. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  137. inbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
  138. } else {
  139. inbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
  140. }
  141. }
  142. inbound, needRestart, err := a.inboundService.AddInbound(inbound)
  143. if err != nil {
  144. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  145. return
  146. }
  147. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), inbound, nil)
  148. if needRestart {
  149. a.xrayService.SetToNeedRestart()
  150. }
  151. a.broadcastInboundsUpdate(user.Id)
  152. notifyClientsChanged()
  153. }
  154. // delInbound deletes an inbound configuration by its ID.
  155. func (a *InboundController) delInbound(c *gin.Context) {
  156. id, err := strconv.Atoi(c.Param("id"))
  157. if err != nil {
  158. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundDeleteSuccess"), err)
  159. return
  160. }
  161. needRestart, err := a.inboundService.DelInbound(id)
  162. if err != nil {
  163. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  164. return
  165. }
  166. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundDeleteSuccess"), id, nil)
  167. if needRestart {
  168. a.xrayService.SetToNeedRestart()
  169. }
  170. user := session.GetLoginUser(c)
  171. a.broadcastInboundsUpdate(user.Id)
  172. notifyClientsChanged()
  173. }
  174. // updateInbound updates an existing inbound configuration.
  175. func (a *InboundController) updateInbound(c *gin.Context) {
  176. id, err := strconv.Atoi(c.Param("id"))
  177. if err != nil {
  178. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  179. return
  180. }
  181. inbound := &model.Inbound{
  182. Id: id,
  183. }
  184. if !middleware.BindAndValidateInto(c, inbound) {
  185. return
  186. }
  187. // Same NodeID=0 → nil normalisation as addInbound. UpdateInbound
  188. // loads the existing row's NodeID from DB anyway (Phase 1 doesn't
  189. // support migrating an inbound between nodes), but normalising here
  190. // keeps the wire shape consistent.
  191. if inbound.NodeID != nil && *inbound.NodeID == 0 {
  192. inbound.NodeID = nil
  193. }
  194. inbound, needRestart, err := a.inboundService.UpdateInbound(inbound)
  195. if err != nil {
  196. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  197. return
  198. }
  199. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), inbound, nil)
  200. if needRestart {
  201. a.xrayService.SetToNeedRestart()
  202. }
  203. user := session.GetLoginUser(c)
  204. a.broadcastInboundsUpdate(user.Id)
  205. notifyClientsChanged()
  206. }
  207. // setInboundEnable flips only the enable flag of an inbound. This is a
  208. // dedicated endpoint because the regular update path serialises the entire
  209. // settings JSON (every client) — far too heavy for an interactive switch
  210. // on inbounds with thousands of clients. Frontend optimistically updates
  211. // the UI; we just persist + sync xray + nudge other open admin sessions.
  212. func (a *InboundController) setInboundEnable(c *gin.Context) {
  213. id, err := strconv.Atoi(c.Param("id"))
  214. if err != nil {
  215. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  216. return
  217. }
  218. type form struct {
  219. Enable bool `json:"enable" form:"enable"`
  220. }
  221. var f form
  222. if err := c.ShouldBind(&f); err != nil {
  223. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  224. return
  225. }
  226. needRestart, err := a.inboundService.SetInboundEnable(id, f.Enable)
  227. if err != nil {
  228. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  229. return
  230. }
  231. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), nil)
  232. if needRestart {
  233. a.xrayService.SetToNeedRestart()
  234. }
  235. // Cross-admin sync: lightweight invalidate signal (a few hundred bytes)
  236. // instead of fetching + serialising the whole inbound list. Other open
  237. // sessions re-fetch via REST. The toggling admin's own UI already
  238. // updated optimistically.
  239. websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
  240. }
  241. // resetInboundTraffic resets traffic counters for a specific inbound.
  242. func (a *InboundController) resetInboundTraffic(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. err = a.inboundService.ResetInboundTraffic(id)
  249. if err != nil {
  250. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  251. return
  252. } else {
  253. a.xrayService.SetToNeedRestart()
  254. }
  255. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetInboundTrafficSuccess"), nil)
  256. }
  257. // resetAllTraffics resets all traffic counters across all inbounds.
  258. func (a *InboundController) resetAllTraffics(c *gin.Context) {
  259. err := a.inboundService.ResetAllTraffics()
  260. if err != nil {
  261. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  262. return
  263. } else {
  264. a.xrayService.SetToNeedRestart()
  265. }
  266. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetAllTrafficSuccess"), nil)
  267. }
  268. // importInbound imports an inbound configuration from provided data.
  269. func (a *InboundController) importInbound(c *gin.Context) {
  270. inbound := &model.Inbound{}
  271. err := json.Unmarshal([]byte(c.PostForm("data")), inbound)
  272. if err != nil {
  273. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  274. return
  275. }
  276. user := session.GetLoginUser(c)
  277. inbound.Id = 0
  278. inbound.UserId = user.Id
  279. if inbound.NodeID != nil && *inbound.NodeID == 0 {
  280. inbound.NodeID = nil
  281. }
  282. if inbound.Tag == "" {
  283. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  284. inbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
  285. } else {
  286. inbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
  287. }
  288. }
  289. for index := range inbound.ClientStats {
  290. inbound.ClientStats[index].Id = 0
  291. inbound.ClientStats[index].Enable = true
  292. }
  293. inbound, needRestart, err := a.inboundService.AddInbound(inbound)
  294. if err != nil {
  295. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  296. return
  297. }
  298. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), inbound, nil)
  299. if needRestart {
  300. a.xrayService.SetToNeedRestart()
  301. }
  302. a.broadcastInboundsUpdate(user.Id)
  303. notifyClientsChanged()
  304. }
  305. // resolveHost mirrors what sub.SubService.ResolveRequest does for the host
  306. // field: prefers X-Forwarded-Host (first entry of any list, port stripped),
  307. // then X-Real-IP, then the host portion of c.Request.Host. Keeping it in the
  308. // controller layer means the service interface stays HTTP-agnostic — service
  309. // methods receive a plain host string instead of a *gin.Context.
  310. func resolveHost(c *gin.Context) string {
  311. if isTrustedForwardedRequest(c) {
  312. if h := strings.TrimSpace(c.GetHeader("X-Forwarded-Host")); h != "" {
  313. if i := strings.Index(h, ","); i >= 0 {
  314. h = strings.TrimSpace(h[:i])
  315. }
  316. if hp, _, err := net.SplitHostPort(h); err == nil {
  317. return hp
  318. }
  319. return h
  320. }
  321. if h := c.GetHeader("X-Real-IP"); h != "" {
  322. return h
  323. }
  324. }
  325. if h, _, err := net.SplitHostPort(c.Request.Host); err == nil {
  326. return h
  327. }
  328. return c.Request.Host
  329. }
  330. // getFallbacks returns the fallback rules attached to the master inbound.
  331. func (a *InboundController) getFallbacks(c *gin.Context) {
  332. id, err := strconv.Atoi(c.Param("id"))
  333. if err != nil {
  334. jsonMsg(c, I18nWeb(c, "get"), err)
  335. return
  336. }
  337. rows, err := a.fallbackService.GetByMaster(id)
  338. if err != nil {
  339. jsonMsg(c, I18nWeb(c, "get"), err)
  340. return
  341. }
  342. jsonObj(c, rows, nil)
  343. }
  344. // setFallbacks atomically replaces the master inbound's fallback list
  345. // and triggers an Xray restart so the new settings.fallbacks take effect.
  346. func (a *InboundController) setFallbacks(c *gin.Context) {
  347. id, err := strconv.Atoi(c.Param("id"))
  348. if err != nil {
  349. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  350. return
  351. }
  352. type body struct {
  353. Fallbacks []service.FallbackInput `json:"fallbacks"`
  354. }
  355. var b body
  356. if err := c.ShouldBindJSON(&b); err != nil {
  357. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  358. return
  359. }
  360. if err := a.fallbackService.SetByMaster(id, b.Fallbacks); err != nil {
  361. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  362. return
  363. }
  364. a.xrayService.SetToNeedRestart()
  365. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), nil)
  366. }