inbound.go 12 KB

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