1
0

inbound.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. }
  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. }
  173. // updateInbound updates an existing inbound configuration.
  174. func (a *InboundController) updateInbound(c *gin.Context) {
  175. id, err := strconv.Atoi(c.Param("id"))
  176. if err != nil {
  177. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  178. return
  179. }
  180. inbound := &model.Inbound{
  181. Id: id,
  182. }
  183. err = c.ShouldBind(inbound)
  184. if err != nil {
  185. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  186. return
  187. }
  188. // Same NodeID=0 → nil normalisation as addInbound. UpdateInbound
  189. // loads the existing row's NodeID from DB anyway (Phase 1 doesn't
  190. // support migrating an inbound between nodes), but normalising here
  191. // keeps the wire shape consistent.
  192. if inbound.NodeID != nil && *inbound.NodeID == 0 {
  193. inbound.NodeID = nil
  194. }
  195. inbound, needRestart, err := a.inboundService.UpdateInbound(inbound)
  196. if err != nil {
  197. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  198. return
  199. }
  200. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), inbound, nil)
  201. if needRestart {
  202. a.xrayService.SetToNeedRestart()
  203. }
  204. user := session.GetLoginUser(c)
  205. a.broadcastInboundsUpdate(user.Id)
  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.Tag == "" {
  280. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  281. inbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
  282. } else {
  283. inbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
  284. }
  285. }
  286. for index := range inbound.ClientStats {
  287. inbound.ClientStats[index].Id = 0
  288. inbound.ClientStats[index].Enable = true
  289. }
  290. needRestart := false
  291. inbound, needRestart, err = a.inboundService.AddInbound(inbound)
  292. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), inbound, err)
  293. if err == nil && needRestart {
  294. a.xrayService.SetToNeedRestart()
  295. }
  296. }
  297. // resolveHost mirrors what sub.SubService.ResolveRequest does for the host
  298. // field: prefers X-Forwarded-Host (first entry of any list, port stripped),
  299. // then X-Real-IP, then the host portion of c.Request.Host. Keeping it in the
  300. // controller layer means the service interface stays HTTP-agnostic — service
  301. // methods receive a plain host string instead of a *gin.Context.
  302. func resolveHost(c *gin.Context) string {
  303. if isTrustedForwardedRequest(c) {
  304. if h := strings.TrimSpace(c.GetHeader("X-Forwarded-Host")); h != "" {
  305. if i := strings.Index(h, ","); i >= 0 {
  306. h = strings.TrimSpace(h[:i])
  307. }
  308. if hp, _, err := net.SplitHostPort(h); err == nil {
  309. return hp
  310. }
  311. return h
  312. }
  313. if h := c.GetHeader("X-Real-IP"); h != "" {
  314. return h
  315. }
  316. }
  317. if h, _, err := net.SplitHostPort(c.Request.Host); err == nil {
  318. return h
  319. }
  320. return c.Request.Host
  321. }
  322. // getFallbacks returns the fallback rules attached to the master inbound.
  323. func (a *InboundController) getFallbacks(c *gin.Context) {
  324. id, err := strconv.Atoi(c.Param("id"))
  325. if err != nil {
  326. jsonMsg(c, I18nWeb(c, "get"), err)
  327. return
  328. }
  329. rows, err := a.fallbackService.GetByMaster(id)
  330. if err != nil {
  331. jsonMsg(c, I18nWeb(c, "get"), err)
  332. return
  333. }
  334. jsonObj(c, rows, nil)
  335. }
  336. // setFallbacks atomically replaces the master inbound's fallback list
  337. // and triggers an Xray restart so the new settings.fallbacks take effect.
  338. func (a *InboundController) setFallbacks(c *gin.Context) {
  339. id, err := strconv.Atoi(c.Param("id"))
  340. if err != nil {
  341. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  342. return
  343. }
  344. type body struct {
  345. Fallbacks []service.FallbackInput `json:"fallbacks"`
  346. }
  347. var b body
  348. if err := c.ShouldBindJSON(&b); err != nil {
  349. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  350. return
  351. }
  352. if err := a.fallbackService.SetByMaster(id, b.Fallbacks); err != nil {
  353. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  354. return
  355. }
  356. a.xrayService.SetToNeedRestart()
  357. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), nil)
  358. }