inbound.go 13 KB

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