inbound.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strconv"
  6. "time"
  7. "github.com/mhsanaei/3x-ui/v2/database/model"
  8. "github.com/mhsanaei/3x-ui/v2/web/service"
  9. "github.com/mhsanaei/3x-ui/v2/web/session"
  10. "github.com/mhsanaei/3x-ui/v2/web/websocket"
  11. "github.com/gin-gonic/gin"
  12. )
  13. // InboundController handles HTTP requests related to Xray inbounds management.
  14. type InboundController struct {
  15. inboundService service.InboundService
  16. xrayService service.XrayService
  17. }
  18. // NewInboundController creates a new InboundController and sets up its routes.
  19. func NewInboundController(g *gin.RouterGroup) *InboundController {
  20. a := &InboundController{}
  21. a.initRouter(g)
  22. return a
  23. }
  24. // broadcastInboundsUpdateClientLimit is the threshold past which we skip the
  25. // full-list push over WebSocket and signal the frontend to re-fetch via REST.
  26. // Mirrors the same heuristic used by the periodic traffic job.
  27. const broadcastInboundsUpdateClientLimit = 5000
  28. // broadcastInboundsUpdate fetches and broadcasts the inbound list for userId.
  29. // At scale (10k+ clients) the marshaled JSON exceeds the WS payload ceiling,
  30. // so we send an invalidate signal instead — frontend re-fetches via REST.
  31. // Skipped entirely when no WebSocket clients are connected.
  32. func (a *InboundController) broadcastInboundsUpdate(userId int) {
  33. if !websocket.HasClients() {
  34. return
  35. }
  36. inbounds, err := a.inboundService.GetInbounds(userId)
  37. if err != nil {
  38. return
  39. }
  40. totalClients := 0
  41. for _, ib := range inbounds {
  42. totalClients += len(ib.ClientStats)
  43. }
  44. if totalClients > broadcastInboundsUpdateClientLimit {
  45. websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
  46. return
  47. }
  48. websocket.BroadcastInbounds(inbounds)
  49. }
  50. // initRouter initializes the routes for inbound-related operations.
  51. func (a *InboundController) initRouter(g *gin.RouterGroup) {
  52. g.GET("/list", a.getInbounds)
  53. g.GET("/get/:id", a.getInbound)
  54. g.GET("/getClientTraffics/:email", a.getClientTraffics)
  55. g.GET("/getClientTrafficsById/:id", a.getClientTrafficsById)
  56. g.POST("/add", a.addInbound)
  57. g.POST("/del/:id", a.delInbound)
  58. g.POST("/update/:id", a.updateInbound)
  59. g.POST("/setEnable/:id", a.setInboundEnable)
  60. g.POST("/clientIps/:email", a.getClientIps)
  61. g.POST("/clearClientIps/:email", a.clearClientIps)
  62. g.POST("/addClient", a.addInboundClient)
  63. g.POST("/:id/copyClients", a.copyInboundClients)
  64. g.POST("/:id/delClient/:clientId", a.delInboundClient)
  65. g.POST("/updateClient/:clientId", a.updateInboundClient)
  66. g.POST("/:id/resetClientTraffic/:email", a.resetClientTraffic)
  67. g.POST("/resetAllTraffics", a.resetAllTraffics)
  68. g.POST("/resetAllClientTraffics/:id", a.resetAllClientTraffics)
  69. g.POST("/delDepletedClients/:id", a.delDepletedClients)
  70. g.POST("/import", a.importInbound)
  71. g.POST("/onlines", a.onlines)
  72. g.POST("/lastOnline", a.lastOnline)
  73. g.POST("/updateClientTraffic/:email", a.updateClientTraffic)
  74. g.POST("/:id/delClientByEmail/:email", a.delInboundClientByEmail)
  75. }
  76. type CopyInboundClientsRequest struct {
  77. SourceInboundID int `form:"sourceInboundId" json:"sourceInboundId"`
  78. ClientEmails []string `form:"clientEmails" json:"clientEmails"`
  79. Flow string `form:"flow" json:"flow"`
  80. }
  81. // getInbounds retrieves the list of inbounds for the logged-in user.
  82. func (a *InboundController) getInbounds(c *gin.Context) {
  83. user := session.GetLoginUser(c)
  84. inbounds, err := a.inboundService.GetInbounds(user.Id)
  85. if err != nil {
  86. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  87. return
  88. }
  89. jsonObj(c, inbounds, nil)
  90. }
  91. // getInbound retrieves a specific inbound by its ID.
  92. func (a *InboundController) getInbound(c *gin.Context) {
  93. id, err := strconv.Atoi(c.Param("id"))
  94. if err != nil {
  95. jsonMsg(c, I18nWeb(c, "get"), err)
  96. return
  97. }
  98. inbound, err := a.inboundService.GetInbound(id)
  99. if err != nil {
  100. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
  101. return
  102. }
  103. jsonObj(c, inbound, nil)
  104. }
  105. // getClientTraffics retrieves client traffic information by email.
  106. func (a *InboundController) getClientTraffics(c *gin.Context) {
  107. email := c.Param("email")
  108. clientTraffics, err := a.inboundService.GetClientTrafficByEmail(email)
  109. if err != nil {
  110. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.trafficGetError"), err)
  111. return
  112. }
  113. jsonObj(c, clientTraffics, nil)
  114. }
  115. // getClientTrafficsById retrieves client traffic information by inbound ID.
  116. func (a *InboundController) getClientTrafficsById(c *gin.Context) {
  117. id := c.Param("id")
  118. clientTraffics, err := a.inboundService.GetClientTrafficByID(id)
  119. if err != nil {
  120. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.trafficGetError"), err)
  121. return
  122. }
  123. jsonObj(c, clientTraffics, nil)
  124. }
  125. // addInbound creates a new inbound configuration.
  126. func (a *InboundController) addInbound(c *gin.Context) {
  127. inbound := &model.Inbound{}
  128. err := c.ShouldBind(inbound)
  129. if err != nil {
  130. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), err)
  131. return
  132. }
  133. user := session.GetLoginUser(c)
  134. inbound.UserId = user.Id
  135. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  136. inbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
  137. } else {
  138. inbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
  139. }
  140. inbound, needRestart, err := a.inboundService.AddInbound(inbound)
  141. if err != nil {
  142. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  143. return
  144. }
  145. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), inbound, nil)
  146. if needRestart {
  147. a.xrayService.SetToNeedRestart()
  148. }
  149. a.broadcastInboundsUpdate(user.Id)
  150. }
  151. // delInbound deletes an inbound configuration by its ID.
  152. func (a *InboundController) delInbound(c *gin.Context) {
  153. id, err := strconv.Atoi(c.Param("id"))
  154. if err != nil {
  155. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundDeleteSuccess"), err)
  156. return
  157. }
  158. needRestart, err := a.inboundService.DelInbound(id)
  159. if err != nil {
  160. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  161. return
  162. }
  163. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundDeleteSuccess"), id, nil)
  164. if needRestart {
  165. a.xrayService.SetToNeedRestart()
  166. }
  167. user := session.GetLoginUser(c)
  168. a.broadcastInboundsUpdate(user.Id)
  169. }
  170. // updateInbound updates an existing inbound configuration.
  171. func (a *InboundController) updateInbound(c *gin.Context) {
  172. id, err := strconv.Atoi(c.Param("id"))
  173. if err != nil {
  174. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  175. return
  176. }
  177. inbound := &model.Inbound{
  178. Id: id,
  179. }
  180. err = c.ShouldBind(inbound)
  181. if err != nil {
  182. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  183. return
  184. }
  185. inbound, needRestart, err := a.inboundService.UpdateInbound(inbound)
  186. if err != nil {
  187. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  188. return
  189. }
  190. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), inbound, nil)
  191. if needRestart {
  192. a.xrayService.SetToNeedRestart()
  193. }
  194. user := session.GetLoginUser(c)
  195. a.broadcastInboundsUpdate(user.Id)
  196. }
  197. // setInboundEnable flips only the enable flag of an inbound. This is a
  198. // dedicated endpoint because the regular update path serialises the entire
  199. // settings JSON (every client) — far too heavy for an interactive switch
  200. // on inbounds with thousands of clients. Frontend optimistically updates
  201. // the UI; we just persist + sync xray + nudge other open admin sessions.
  202. func (a *InboundController) setInboundEnable(c *gin.Context) {
  203. id, err := strconv.Atoi(c.Param("id"))
  204. if err != nil {
  205. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  206. return
  207. }
  208. type form struct {
  209. Enable bool `json:"enable" form:"enable"`
  210. }
  211. var f form
  212. if err := c.ShouldBind(&f); err != nil {
  213. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  214. return
  215. }
  216. needRestart, err := a.inboundService.SetInboundEnable(id, f.Enable)
  217. if err != nil {
  218. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  219. return
  220. }
  221. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), nil)
  222. if needRestart {
  223. a.xrayService.SetToNeedRestart()
  224. }
  225. // Cross-admin sync: lightweight invalidate signal (a few hundred bytes)
  226. // instead of fetching + serialising the whole inbound list. Other open
  227. // sessions re-fetch via REST. The toggling admin's own UI already
  228. // updated optimistically.
  229. websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
  230. }
  231. // getClientIps retrieves the IP addresses associated with a client by email.
  232. func (a *InboundController) getClientIps(c *gin.Context) {
  233. email := c.Param("email")
  234. ips, err := a.inboundService.GetInboundClientIps(email)
  235. if err != nil || ips == "" {
  236. jsonObj(c, "No IP Record", nil)
  237. return
  238. }
  239. // Prefer returning a normalized string list for consistent UI rendering
  240. type ipWithTimestamp struct {
  241. IP string `json:"ip"`
  242. Timestamp int64 `json:"timestamp"`
  243. }
  244. var ipsWithTime []ipWithTimestamp
  245. if err := json.Unmarshal([]byte(ips), &ipsWithTime); err == nil && len(ipsWithTime) > 0 {
  246. formatted := make([]string, 0, len(ipsWithTime))
  247. for _, item := range ipsWithTime {
  248. if item.IP == "" {
  249. continue
  250. }
  251. if item.Timestamp > 0 {
  252. ts := time.Unix(item.Timestamp, 0).Local().Format("2006-01-02 15:04:05")
  253. formatted = append(formatted, fmt.Sprintf("%s (%s)", item.IP, ts))
  254. continue
  255. }
  256. formatted = append(formatted, item.IP)
  257. }
  258. jsonObj(c, formatted, nil)
  259. return
  260. }
  261. var oldIps []string
  262. if err := json.Unmarshal([]byte(ips), &oldIps); err == nil && len(oldIps) > 0 {
  263. jsonObj(c, oldIps, nil)
  264. return
  265. }
  266. // If parsing fails, return as string
  267. jsonObj(c, ips, nil)
  268. }
  269. // clearClientIps clears the IP addresses for a client by email.
  270. func (a *InboundController) clearClientIps(c *gin.Context) {
  271. email := c.Param("email")
  272. err := a.inboundService.ClearClientIps(email)
  273. if err != nil {
  274. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.updateSuccess"), err)
  275. return
  276. }
  277. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.logCleanSuccess"), nil)
  278. }
  279. // addInboundClient adds a new client to an existing inbound.
  280. func (a *InboundController) addInboundClient(c *gin.Context) {
  281. data := &model.Inbound{}
  282. err := c.ShouldBind(data)
  283. if err != nil {
  284. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  285. return
  286. }
  287. needRestart, err := a.inboundService.AddInboundClient(data)
  288. if err != nil {
  289. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  290. return
  291. }
  292. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), nil)
  293. if needRestart {
  294. a.xrayService.SetToNeedRestart()
  295. }
  296. }
  297. // copyInboundClients copies clients from source inbound to target inbound.
  298. func (a *InboundController) copyInboundClients(c *gin.Context) {
  299. targetID, err := strconv.Atoi(c.Param("id"))
  300. if err != nil {
  301. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  302. return
  303. }
  304. req := &CopyInboundClientsRequest{}
  305. err = c.ShouldBind(req)
  306. if err != nil {
  307. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  308. return
  309. }
  310. if req.SourceInboundID <= 0 {
  311. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), fmt.Errorf("invalid source inbound id"))
  312. return
  313. }
  314. result, needRestart, err := a.inboundService.CopyInboundClients(targetID, req.SourceInboundID, req.ClientEmails, req.Flow)
  315. if err != nil {
  316. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  317. return
  318. }
  319. jsonObj(c, result, nil)
  320. if needRestart {
  321. a.xrayService.SetToNeedRestart()
  322. }
  323. }
  324. // delInboundClient deletes a client from an inbound by inbound ID and client ID.
  325. func (a *InboundController) delInboundClient(c *gin.Context) {
  326. id, err := strconv.Atoi(c.Param("id"))
  327. if err != nil {
  328. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  329. return
  330. }
  331. clientId := c.Param("clientId")
  332. needRestart, err := a.inboundService.DelInboundClient(id, clientId)
  333. if err != nil {
  334. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  335. return
  336. }
  337. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), nil)
  338. if needRestart {
  339. a.xrayService.SetToNeedRestart()
  340. }
  341. }
  342. // updateInboundClient updates a client's configuration in an inbound.
  343. func (a *InboundController) updateInboundClient(c *gin.Context) {
  344. clientId := c.Param("clientId")
  345. inbound := &model.Inbound{}
  346. err := c.ShouldBind(inbound)
  347. if err != nil {
  348. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  349. return
  350. }
  351. needRestart, err := a.inboundService.UpdateInboundClient(inbound, clientId)
  352. if err != nil {
  353. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  354. return
  355. }
  356. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientUpdateSuccess"), nil)
  357. if needRestart {
  358. a.xrayService.SetToNeedRestart()
  359. }
  360. }
  361. // resetClientTraffic resets the traffic counter for a specific client in an inbound.
  362. func (a *InboundController) resetClientTraffic(c *gin.Context) {
  363. id, err := strconv.Atoi(c.Param("id"))
  364. if err != nil {
  365. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  366. return
  367. }
  368. email := c.Param("email")
  369. needRestart, err := a.inboundService.ResetClientTraffic(id, email)
  370. if err != nil {
  371. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  372. return
  373. }
  374. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetInboundClientTrafficSuccess"), nil)
  375. if needRestart {
  376. a.xrayService.SetToNeedRestart()
  377. }
  378. }
  379. // resetAllTraffics resets all traffic counters across all inbounds.
  380. func (a *InboundController) resetAllTraffics(c *gin.Context) {
  381. err := a.inboundService.ResetAllTraffics()
  382. if err != nil {
  383. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  384. return
  385. } else {
  386. a.xrayService.SetToNeedRestart()
  387. }
  388. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetAllTrafficSuccess"), nil)
  389. }
  390. // resetAllClientTraffics resets traffic counters for all clients in a specific inbound.
  391. func (a *InboundController) resetAllClientTraffics(c *gin.Context) {
  392. id, err := strconv.Atoi(c.Param("id"))
  393. if err != nil {
  394. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  395. return
  396. }
  397. err = a.inboundService.ResetAllClientTraffics(id)
  398. if err != nil {
  399. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  400. return
  401. } else {
  402. a.xrayService.SetToNeedRestart()
  403. }
  404. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.resetAllClientTrafficSuccess"), nil)
  405. }
  406. // importInbound imports an inbound configuration from provided data.
  407. func (a *InboundController) importInbound(c *gin.Context) {
  408. inbound := &model.Inbound{}
  409. err := json.Unmarshal([]byte(c.PostForm("data")), inbound)
  410. if err != nil {
  411. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  412. return
  413. }
  414. user := session.GetLoginUser(c)
  415. inbound.Id = 0
  416. inbound.UserId = user.Id
  417. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  418. inbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
  419. } else {
  420. inbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
  421. }
  422. for index := range inbound.ClientStats {
  423. inbound.ClientStats[index].Id = 0
  424. inbound.ClientStats[index].Enable = true
  425. }
  426. needRestart := false
  427. inbound, needRestart, err = a.inboundService.AddInbound(inbound)
  428. jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundCreateSuccess"), inbound, err)
  429. if err == nil && needRestart {
  430. a.xrayService.SetToNeedRestart()
  431. }
  432. }
  433. // delDepletedClients deletes clients in an inbound who have exhausted their traffic limits.
  434. func (a *InboundController) delDepletedClients(c *gin.Context) {
  435. id, err := strconv.Atoi(c.Param("id"))
  436. if err != nil {
  437. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  438. return
  439. }
  440. err = a.inboundService.DelDepletedClients(id)
  441. if err != nil {
  442. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  443. return
  444. }
  445. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.delDepletedClientsSuccess"), nil)
  446. }
  447. // onlines retrieves the list of currently online clients.
  448. func (a *InboundController) onlines(c *gin.Context) {
  449. jsonObj(c, a.inboundService.GetOnlineClients(), nil)
  450. }
  451. // lastOnline retrieves the last online timestamps for clients.
  452. func (a *InboundController) lastOnline(c *gin.Context) {
  453. data, err := a.inboundService.GetClientsLastOnline()
  454. jsonObj(c, data, err)
  455. }
  456. // updateClientTraffic updates the traffic statistics for a client by email.
  457. func (a *InboundController) updateClientTraffic(c *gin.Context) {
  458. email := c.Param("email")
  459. // Define the request structure for traffic update
  460. type TrafficUpdateRequest struct {
  461. Upload int64 `json:"upload"`
  462. Download int64 `json:"download"`
  463. }
  464. var request TrafficUpdateRequest
  465. err := c.ShouldBindJSON(&request)
  466. if err != nil {
  467. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundUpdateSuccess"), err)
  468. return
  469. }
  470. err = a.inboundService.UpdateClientTrafficByEmail(email, request.Upload, request.Download)
  471. if err != nil {
  472. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  473. return
  474. }
  475. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientUpdateSuccess"), nil)
  476. }
  477. // delInboundClientByEmail deletes a client from an inbound by email address.
  478. func (a *InboundController) delInboundClientByEmail(c *gin.Context) {
  479. inboundId, err := strconv.Atoi(c.Param("id"))
  480. if err != nil {
  481. jsonMsg(c, "Invalid inbound ID", err)
  482. return
  483. }
  484. email := c.Param("email")
  485. needRestart, err := a.inboundService.DelInboundClientByEmail(inboundId, email)
  486. if err != nil {
  487. jsonMsg(c, "Failed to delete client by email", err)
  488. return
  489. }
  490. jsonMsg(c, "Client deleted successfully", nil)
  491. if needRestart {
  492. a.xrayService.SetToNeedRestart()
  493. }
  494. }