1
0

inbound.go 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122
  1. // Package service provides business logic services for the 3x-ui web panel,
  2. // including inbound/outbound management, user administration, settings, and Xray integration.
  3. package service
  4. import (
  5. "encoding/json"
  6. "fmt"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/google/uuid"
  12. "github.com/mhsanaei/3x-ui/v2/database"
  13. "github.com/mhsanaei/3x-ui/v2/database/model"
  14. "github.com/mhsanaei/3x-ui/v2/logger"
  15. "github.com/mhsanaei/3x-ui/v2/util/common"
  16. "github.com/mhsanaei/3x-ui/v2/xray"
  17. "gorm.io/gorm"
  18. )
  19. // InboundService provides business logic for managing Xray inbound configurations.
  20. // It handles CRUD operations for inbounds, client management, traffic monitoring,
  21. // and integration with the Xray API for real-time updates.
  22. type InboundService struct {
  23. xrayApi xray.XrayAPI
  24. }
  25. type CopyClientsResult struct {
  26. Added []string `json:"added"`
  27. Skipped []string `json:"skipped"`
  28. Errors []string `json:"errors"`
  29. }
  30. // GetInbounds retrieves all inbounds for a specific user.
  31. // Returns a slice of inbound models with their associated client statistics.
  32. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  33. db := database.GetDB()
  34. var inbounds []*model.Inbound
  35. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Find(&inbounds).Error
  36. if err != nil && err != gorm.ErrRecordNotFound {
  37. return nil, err
  38. }
  39. // Enrich client stats with UUID/SubId from inbound settings
  40. for _, inbound := range inbounds {
  41. clients, _ := s.GetClients(inbound)
  42. if len(clients) == 0 || len(inbound.ClientStats) == 0 {
  43. continue
  44. }
  45. // Build a map email -> client
  46. cMap := make(map[string]model.Client, len(clients))
  47. for _, c := range clients {
  48. cMap[strings.ToLower(c.Email)] = c
  49. }
  50. for i := range inbound.ClientStats {
  51. email := strings.ToLower(inbound.ClientStats[i].Email)
  52. if c, ok := cMap[email]; ok {
  53. inbound.ClientStats[i].UUID = c.ID
  54. inbound.ClientStats[i].SubId = c.SubID
  55. }
  56. }
  57. }
  58. return inbounds, nil
  59. }
  60. // GetAllInbounds retrieves all inbounds from the database.
  61. // Returns a slice of all inbound models with their associated client statistics.
  62. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  63. db := database.GetDB()
  64. var inbounds []*model.Inbound
  65. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  66. if err != nil && err != gorm.ErrRecordNotFound {
  67. return nil, err
  68. }
  69. // Enrich client stats with UUID/SubId from inbound settings
  70. for _, inbound := range inbounds {
  71. clients, _ := s.GetClients(inbound)
  72. if len(clients) == 0 || len(inbound.ClientStats) == 0 {
  73. continue
  74. }
  75. cMap := make(map[string]model.Client, len(clients))
  76. for _, c := range clients {
  77. cMap[strings.ToLower(c.Email)] = c
  78. }
  79. for i := range inbound.ClientStats {
  80. email := strings.ToLower(inbound.ClientStats[i].Email)
  81. if c, ok := cMap[email]; ok {
  82. inbound.ClientStats[i].UUID = c.ID
  83. inbound.ClientStats[i].SubId = c.SubID
  84. }
  85. }
  86. }
  87. return inbounds, nil
  88. }
  89. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  90. db := database.GetDB()
  91. var inbounds []*model.Inbound
  92. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  93. if err != nil && err != gorm.ErrRecordNotFound {
  94. return nil, err
  95. }
  96. return inbounds, nil
  97. }
  98. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  99. settings := map[string][]model.Client{}
  100. json.Unmarshal([]byte(inbound.Settings), &settings)
  101. if settings == nil {
  102. return nil, fmt.Errorf("setting is null")
  103. }
  104. clients := settings["clients"]
  105. if clients == nil {
  106. return nil, nil
  107. }
  108. return clients, nil
  109. }
  110. func (s *InboundService) getAllEmails() ([]string, error) {
  111. db := database.GetDB()
  112. var emails []string
  113. err := db.Raw(`
  114. SELECT JSON_EXTRACT(client.value, '$.email')
  115. FROM inbounds,
  116. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  117. `).Scan(&emails).Error
  118. if err != nil {
  119. return nil, err
  120. }
  121. return emails, nil
  122. }
  123. func (s *InboundService) contains(slice []string, str string) bool {
  124. lowerStr := strings.ToLower(str)
  125. for _, s := range slice {
  126. if strings.ToLower(s) == lowerStr {
  127. return true
  128. }
  129. }
  130. return false
  131. }
  132. func (s *InboundService) checkEmailsExistForClients(clients []model.Client) (string, error) {
  133. allEmails, err := s.getAllEmails()
  134. if err != nil {
  135. return "", err
  136. }
  137. var emails []string
  138. for _, client := range clients {
  139. if client.Email != "" {
  140. if s.contains(emails, client.Email) {
  141. return client.Email, nil
  142. }
  143. if s.contains(allEmails, client.Email) {
  144. return client.Email, nil
  145. }
  146. emails = append(emails, client.Email)
  147. }
  148. }
  149. return "", nil
  150. }
  151. func (s *InboundService) checkEmailExistForInbound(inbound *model.Inbound) (string, error) {
  152. clients, err := s.GetClients(inbound)
  153. if err != nil {
  154. return "", err
  155. }
  156. allEmails, err := s.getAllEmails()
  157. if err != nil {
  158. return "", err
  159. }
  160. var emails []string
  161. for _, client := range clients {
  162. if client.Email != "" {
  163. if s.contains(emails, client.Email) {
  164. return client.Email, nil
  165. }
  166. if s.contains(allEmails, client.Email) {
  167. return client.Email, nil
  168. }
  169. emails = append(emails, client.Email)
  170. }
  171. }
  172. return "", nil
  173. }
  174. // AddInbound creates a new inbound configuration.
  175. // It validates port uniqueness, client email uniqueness, and required fields,
  176. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  177. // Returns the created inbound, whether Xray needs restart, and any error.
  178. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  179. exist, err := s.checkPortConflict(inbound, 0)
  180. if err != nil {
  181. return inbound, false, err
  182. }
  183. if exist {
  184. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  185. }
  186. // pick a tag that won't collide with an existing row. for the common
  187. // case this is the same "inbound-<port>" string the controller already
  188. // set; only when this port already has another inbound on a different
  189. // transport (now possible after the transport-aware port check) does
  190. // this disambiguate with a -tcp/-udp suffix. see #4103.
  191. inbound.Tag, err = s.generateInboundTag(inbound, 0)
  192. if err != nil {
  193. return inbound, false, err
  194. }
  195. existEmail, err := s.checkEmailExistForInbound(inbound)
  196. if err != nil {
  197. return inbound, false, err
  198. }
  199. if existEmail != "" {
  200. return inbound, false, common.NewError("Duplicate email:", existEmail)
  201. }
  202. clients, err := s.GetClients(inbound)
  203. if err != nil {
  204. return inbound, false, err
  205. }
  206. // Ensure created_at and updated_at on clients in settings
  207. if len(clients) > 0 {
  208. var settings map[string]any
  209. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  210. now := time.Now().Unix() * 1000
  211. updatedClients := make([]model.Client, 0, len(clients))
  212. for _, c := range clients {
  213. if c.CreatedAt == 0 {
  214. c.CreatedAt = now
  215. }
  216. c.UpdatedAt = now
  217. updatedClients = append(updatedClients, c)
  218. }
  219. settings["clients"] = updatedClients
  220. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  221. inbound.Settings = string(bs)
  222. } else {
  223. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  224. }
  225. } else if err2 != nil {
  226. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  227. }
  228. }
  229. // Secure client ID
  230. for _, client := range clients {
  231. switch inbound.Protocol {
  232. case "trojan":
  233. if client.Password == "" {
  234. return inbound, false, common.NewError("empty client ID")
  235. }
  236. case "shadowsocks":
  237. if client.Email == "" {
  238. return inbound, false, common.NewError("empty client ID")
  239. }
  240. case "hysteria", "hysteria2":
  241. if client.Auth == "" {
  242. return inbound, false, common.NewError("empty client ID")
  243. }
  244. default:
  245. if client.ID == "" {
  246. return inbound, false, common.NewError("empty client ID")
  247. }
  248. }
  249. }
  250. db := database.GetDB()
  251. tx := db.Begin()
  252. defer func() {
  253. if err == nil {
  254. tx.Commit()
  255. } else {
  256. tx.Rollback()
  257. }
  258. }()
  259. err = tx.Save(inbound).Error
  260. if err == nil {
  261. if len(inbound.ClientStats) == 0 {
  262. for _, client := range clients {
  263. s.AddClientStat(tx, inbound.Id, &client)
  264. }
  265. }
  266. } else {
  267. return inbound, false, err
  268. }
  269. needRestart := false
  270. if inbound.Enable {
  271. s.xrayApi.Init(p.GetAPIPort())
  272. inboundJson, err1 := json.MarshalIndent(inbound.GenXrayInboundConfig(), "", " ")
  273. if err1 != nil {
  274. logger.Debug("Unable to marshal inbound config:", err1)
  275. }
  276. err1 = s.xrayApi.AddInbound(inboundJson)
  277. if err1 == nil {
  278. logger.Debug("New inbound added by api:", inbound.Tag)
  279. } else {
  280. logger.Debug("Unable to add inbound by api:", err1)
  281. needRestart = true
  282. }
  283. s.xrayApi.Close()
  284. }
  285. return inbound, needRestart, err
  286. }
  287. // DelInbound deletes an inbound configuration by ID.
  288. // It removes the inbound from the database and the running Xray instance if active.
  289. // Returns whether Xray needs restart and any error.
  290. func (s *InboundService) DelInbound(id int) (bool, error) {
  291. db := database.GetDB()
  292. var tag string
  293. needRestart := false
  294. result := db.Model(model.Inbound{}).Select("tag").Where("id = ? and enable = ?", id, true).First(&tag)
  295. if result.Error == nil {
  296. s.xrayApi.Init(p.GetAPIPort())
  297. err1 := s.xrayApi.DelInbound(tag)
  298. if err1 == nil {
  299. logger.Debug("Inbound deleted by api:", tag)
  300. } else {
  301. logger.Debug("Unable to delete inbound by api:", err1)
  302. needRestart = true
  303. }
  304. s.xrayApi.Close()
  305. } else {
  306. logger.Debug("No enabled inbound founded to removing by api", tag)
  307. }
  308. // Delete client traffics of inbounds
  309. err := db.Where("inbound_id = ?", id).Delete(xray.ClientTraffic{}).Error
  310. if err != nil {
  311. return false, err
  312. }
  313. inbound, err := s.GetInbound(id)
  314. if err != nil {
  315. return false, err
  316. }
  317. clients, err := s.GetClients(inbound)
  318. if err != nil {
  319. return false, err
  320. }
  321. // Bulk-delete client IPs for every email in this inbound. The previous
  322. // per-client loop fired one DELETE per row — at 7k+ clients that meant
  323. // thousands of synchronous SQL roundtrips and a multi-second freeze.
  324. // Chunked to stay under SQLite's bind-variable limit on huge inbounds.
  325. if len(clients) > 0 {
  326. emails := make([]string, 0, len(clients))
  327. for i := range clients {
  328. if clients[i].Email != "" {
  329. emails = append(emails, clients[i].Email)
  330. }
  331. }
  332. for _, batch := range chunkStrings(uniqueNonEmptyStrings(emails), sqliteMaxVars) {
  333. if err := db.Where("client_email IN ?", batch).
  334. Delete(model.InboundClientIps{}).Error; err != nil {
  335. return false, err
  336. }
  337. }
  338. }
  339. return needRestart, db.Delete(model.Inbound{}, id).Error
  340. }
  341. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  342. db := database.GetDB()
  343. inbound := &model.Inbound{}
  344. err := db.Model(model.Inbound{}).First(inbound, id).Error
  345. if err != nil {
  346. return nil, err
  347. }
  348. return inbound, nil
  349. }
  350. // SetInboundEnable toggles only the enable flag of an inbound, without
  351. // rewriting the (potentially multi-MB) settings JSON. Used by the UI's
  352. // per-row enable switch — for inbounds with thousands of clients the full
  353. // UpdateInbound path is an order of magnitude too slow for an interactive
  354. // toggle (parses + reserialises every client, runs O(N) traffic diff).
  355. //
  356. // Returns (needRestart, error). needRestart is true when the xray runtime
  357. // could not be re-synced from the cached config and a full restart is
  358. // required to pick up the change.
  359. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  360. inbound, err := s.GetInbound(id)
  361. if err != nil {
  362. return false, err
  363. }
  364. if inbound.Enable == enable {
  365. return false, nil
  366. }
  367. db := database.GetDB()
  368. if err := db.Model(model.Inbound{}).Where("id = ?", id).
  369. Update("enable", enable).Error; err != nil {
  370. return false, err
  371. }
  372. inbound.Enable = enable
  373. // Sync xray runtime: drop the live inbound, add it back if we're enabling.
  374. // "User not found"-style errors from DelInbound mean the inbound was
  375. // already absent from the live config — that's fine. Any other error
  376. // means the live config and DB diverged, so we ask the caller to
  377. // schedule a restart.
  378. needRestart := false
  379. s.xrayApi.Init(p.GetAPIPort())
  380. defer s.xrayApi.Close()
  381. if err := s.xrayApi.DelInbound(inbound.Tag); err != nil &&
  382. !strings.Contains(err.Error(), "not found") {
  383. logger.Debug("SetInboundEnable: DelInbound via api failed:", err)
  384. needRestart = true
  385. }
  386. if !enable {
  387. return needRestart, nil
  388. }
  389. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  390. if err != nil {
  391. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  392. return true, nil
  393. }
  394. inboundJson, err := json.MarshalIndent(runtimeInbound.GenXrayInboundConfig(), "", " ")
  395. if err != nil {
  396. logger.Debug("SetInboundEnable: marshal runtime config failed:", err)
  397. return true, nil
  398. }
  399. if err := s.xrayApi.AddInbound(inboundJson); err != nil {
  400. logger.Debug("SetInboundEnable: AddInbound via api failed:", err)
  401. needRestart = true
  402. }
  403. return needRestart, nil
  404. }
  405. // UpdateInbound modifies an existing inbound configuration.
  406. // It validates changes, updates the database, and syncs with the running Xray instance.
  407. // Returns the updated inbound, whether Xray needs restart, and any error.
  408. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  409. exist, err := s.checkPortConflict(inbound, inbound.Id)
  410. if err != nil {
  411. return inbound, false, err
  412. }
  413. if exist {
  414. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  415. }
  416. oldInbound, err := s.GetInbound(inbound.Id)
  417. if err != nil {
  418. return inbound, false, err
  419. }
  420. tag := oldInbound.Tag
  421. db := database.GetDB()
  422. tx := db.Begin()
  423. defer func() {
  424. if err != nil {
  425. tx.Rollback()
  426. } else {
  427. tx.Commit()
  428. }
  429. }()
  430. err = s.updateClientTraffics(tx, oldInbound, inbound)
  431. if err != nil {
  432. return inbound, false, err
  433. }
  434. // Ensure created_at and updated_at exist in inbound.Settings clients
  435. {
  436. var oldSettings map[string]any
  437. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  438. emailToCreated := map[string]int64{}
  439. emailToUpdated := map[string]int64{}
  440. if oldSettings != nil {
  441. if oc, ok := oldSettings["clients"].([]any); ok {
  442. for _, it := range oc {
  443. if m, ok2 := it.(map[string]any); ok2 {
  444. if email, ok3 := m["email"].(string); ok3 {
  445. switch v := m["created_at"].(type) {
  446. case float64:
  447. emailToCreated[email] = int64(v)
  448. case int64:
  449. emailToCreated[email] = v
  450. }
  451. switch v := m["updated_at"].(type) {
  452. case float64:
  453. emailToUpdated[email] = int64(v)
  454. case int64:
  455. emailToUpdated[email] = v
  456. }
  457. }
  458. }
  459. }
  460. }
  461. }
  462. var newSettings map[string]any
  463. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  464. now := time.Now().Unix() * 1000
  465. if nSlice, ok := newSettings["clients"].([]any); ok {
  466. for i := range nSlice {
  467. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  468. email, _ := m["email"].(string)
  469. if _, ok3 := m["created_at"]; !ok3 {
  470. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  471. m["created_at"] = v
  472. } else {
  473. m["created_at"] = now
  474. }
  475. }
  476. // Preserve client's updated_at if present; do not bump on parent inbound update
  477. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  478. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  479. m["updated_at"] = v
  480. }
  481. }
  482. nSlice[i] = m
  483. }
  484. }
  485. newSettings["clients"] = nSlice
  486. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  487. inbound.Settings = string(bs)
  488. }
  489. }
  490. }
  491. }
  492. oldInbound.Up = inbound.Up
  493. oldInbound.Down = inbound.Down
  494. oldInbound.Total = inbound.Total
  495. oldInbound.Remark = inbound.Remark
  496. oldInbound.Enable = inbound.Enable
  497. oldInbound.ExpiryTime = inbound.ExpiryTime
  498. oldInbound.TrafficReset = inbound.TrafficReset
  499. oldInbound.Listen = inbound.Listen
  500. oldInbound.Port = inbound.Port
  501. oldInbound.Protocol = inbound.Protocol
  502. oldInbound.Settings = inbound.Settings
  503. oldInbound.StreamSettings = inbound.StreamSettings
  504. oldInbound.Sniffing = inbound.Sniffing
  505. // regenerate tag with collision-aware logic. for this row we pass
  506. // inbound.Id as ignoreId so it doesn't see its own old tag in the db.
  507. oldInbound.Tag, err = s.generateInboundTag(inbound, inbound.Id)
  508. if err != nil {
  509. return inbound, false, err
  510. }
  511. needRestart := false
  512. s.xrayApi.Init(p.GetAPIPort())
  513. if s.xrayApi.DelInbound(tag) == nil {
  514. logger.Debug("Old inbound deleted by api:", tag)
  515. }
  516. if inbound.Enable {
  517. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  518. if err2 != nil {
  519. logger.Debug("Unable to prepare runtime inbound config:", err2)
  520. needRestart = true
  521. } else {
  522. inboundJson, err2 := json.MarshalIndent(runtimeInbound.GenXrayInboundConfig(), "", " ")
  523. if err2 != nil {
  524. logger.Debug("Unable to marshal updated inbound config:", err2)
  525. needRestart = true
  526. } else {
  527. err2 = s.xrayApi.AddInbound(inboundJson)
  528. if err2 == nil {
  529. logger.Debug("Updated inbound added by api:", oldInbound.Tag)
  530. } else {
  531. logger.Debug("Unable to update inbound by api:", err2)
  532. needRestart = true
  533. }
  534. }
  535. }
  536. }
  537. s.xrayApi.Close()
  538. return inbound, needRestart, tx.Save(oldInbound).Error
  539. }
  540. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  541. if inbound == nil {
  542. return nil, fmt.Errorf("inbound is nil")
  543. }
  544. runtimeInbound := *inbound
  545. settings := map[string]any{}
  546. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  547. return nil, err
  548. }
  549. clients, ok := settings["clients"].([]any)
  550. if !ok {
  551. return &runtimeInbound, nil
  552. }
  553. var clientStats []xray.ClientTraffic
  554. err := tx.Model(xray.ClientTraffic{}).
  555. Where("inbound_id = ?", inbound.Id).
  556. Select("email", "enable").
  557. Find(&clientStats).Error
  558. if err != nil {
  559. return nil, err
  560. }
  561. enableMap := make(map[string]bool, len(clientStats))
  562. for _, clientTraffic := range clientStats {
  563. enableMap[clientTraffic.Email] = clientTraffic.Enable
  564. }
  565. finalClients := make([]any, 0, len(clients))
  566. for _, client := range clients {
  567. c, ok := client.(map[string]any)
  568. if !ok {
  569. continue
  570. }
  571. email, _ := c["email"].(string)
  572. if enable, exists := enableMap[email]; exists && !enable {
  573. continue
  574. }
  575. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  576. continue
  577. }
  578. finalClients = append(finalClients, c)
  579. }
  580. settings["clients"] = finalClients
  581. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  582. if err != nil {
  583. return nil, err
  584. }
  585. runtimeInbound.Settings = string(modifiedSettings)
  586. return &runtimeInbound, nil
  587. }
  588. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  589. // list: removes rows for emails that disappeared, inserts rows for newly-added
  590. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  591. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  592. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  593. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  594. oldClients, err := s.GetClients(oldInbound)
  595. if err != nil {
  596. return err
  597. }
  598. newClients, err := s.GetClients(newInbound)
  599. if err != nil {
  600. return err
  601. }
  602. // Email is the unique key for ClientTraffic rows. Clients without an
  603. // email have no stats row to sync — skip them on both sides instead of
  604. // risking a unique-constraint hit or accidental delete of an unrelated row.
  605. oldEmails := make(map[string]struct{}, len(oldClients))
  606. for i := range oldClients {
  607. if oldClients[i].Email == "" {
  608. continue
  609. }
  610. oldEmails[oldClients[i].Email] = struct{}{}
  611. }
  612. newEmails := make(map[string]struct{}, len(newClients))
  613. for i := range newClients {
  614. if newClients[i].Email == "" {
  615. continue
  616. }
  617. newEmails[newClients[i].Email] = struct{}{}
  618. }
  619. // Removed clients — drop their stats rows.
  620. for i := range oldClients {
  621. email := oldClients[i].Email
  622. if email == "" {
  623. continue
  624. }
  625. if _, kept := newEmails[email]; kept {
  626. continue
  627. }
  628. if err := s.DelClientStat(tx, email); err != nil {
  629. return err
  630. }
  631. }
  632. // Added clients — create their stats rows.
  633. for i := range newClients {
  634. email := newClients[i].Email
  635. if email == "" {
  636. continue
  637. }
  638. if _, existed := oldEmails[email]; existed {
  639. continue
  640. }
  641. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  642. return err
  643. }
  644. }
  645. return nil
  646. }
  647. func (s *InboundService) AddInboundClient(data *model.Inbound) (bool, error) {
  648. clients, err := s.GetClients(data)
  649. if err != nil {
  650. return false, err
  651. }
  652. var settings map[string]any
  653. err = json.Unmarshal([]byte(data.Settings), &settings)
  654. if err != nil {
  655. return false, err
  656. }
  657. interfaceClients := settings["clients"].([]any)
  658. // Add timestamps for new clients being appended
  659. nowTs := time.Now().Unix() * 1000
  660. for i := range interfaceClients {
  661. if cm, ok := interfaceClients[i].(map[string]any); ok {
  662. if _, ok2 := cm["created_at"]; !ok2 {
  663. cm["created_at"] = nowTs
  664. }
  665. cm["updated_at"] = nowTs
  666. interfaceClients[i] = cm
  667. }
  668. }
  669. existEmail, err := s.checkEmailsExistForClients(clients)
  670. if err != nil {
  671. return false, err
  672. }
  673. if existEmail != "" {
  674. return false, common.NewError("Duplicate email:", existEmail)
  675. }
  676. oldInbound, err := s.GetInbound(data.Id)
  677. if err != nil {
  678. return false, err
  679. }
  680. // Secure client ID
  681. for _, client := range clients {
  682. switch oldInbound.Protocol {
  683. case "trojan":
  684. if client.Password == "" {
  685. return false, common.NewError("empty client ID")
  686. }
  687. case "shadowsocks":
  688. if client.Email == "" {
  689. return false, common.NewError("empty client ID")
  690. }
  691. case "hysteria", "hysteria2":
  692. if client.Auth == "" {
  693. return false, common.NewError("empty client ID")
  694. }
  695. default:
  696. if client.ID == "" {
  697. return false, common.NewError("empty client ID")
  698. }
  699. }
  700. }
  701. var oldSettings map[string]any
  702. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  703. if err != nil {
  704. return false, err
  705. }
  706. oldClients := oldSettings["clients"].([]any)
  707. oldClients = append(oldClients, interfaceClients...)
  708. oldSettings["clients"] = oldClients
  709. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  710. if err != nil {
  711. return false, err
  712. }
  713. oldInbound.Settings = string(newSettings)
  714. db := database.GetDB()
  715. tx := db.Begin()
  716. defer func() {
  717. if err != nil {
  718. tx.Rollback()
  719. } else {
  720. tx.Commit()
  721. }
  722. }()
  723. needRestart := false
  724. s.xrayApi.Init(p.GetAPIPort())
  725. for _, client := range clients {
  726. if len(client.Email) > 0 {
  727. s.AddClientStat(tx, data.Id, &client)
  728. if client.Enable {
  729. cipher := ""
  730. if oldInbound.Protocol == "shadowsocks" {
  731. cipher = oldSettings["method"].(string)
  732. }
  733. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]any{
  734. "email": client.Email,
  735. "id": client.ID,
  736. "auth": client.Auth,
  737. "security": client.Security,
  738. "flow": client.Flow,
  739. "password": client.Password,
  740. "cipher": cipher,
  741. })
  742. if err1 == nil {
  743. logger.Debug("Client added by api:", client.Email)
  744. } else {
  745. logger.Debug("Error in adding client by api:", err1)
  746. needRestart = true
  747. }
  748. }
  749. } else {
  750. needRestart = true
  751. }
  752. }
  753. s.xrayApi.Close()
  754. return needRestart, tx.Save(oldInbound).Error
  755. }
  756. func (s *InboundService) getClientPrimaryKey(protocol model.Protocol, client model.Client) string {
  757. switch protocol {
  758. case model.Trojan:
  759. return client.Password
  760. case model.Shadowsocks:
  761. return client.Email
  762. case model.Hysteria:
  763. return client.Auth
  764. default:
  765. return client.ID
  766. }
  767. }
  768. func (s *InboundService) writeBackClientSubID(sourceInboundID int, sourceProtocol model.Protocol, client model.Client, subID string) (bool, error) {
  769. client.SubID = subID
  770. client.UpdatedAt = time.Now().UnixMilli()
  771. clientID := s.getClientPrimaryKey(sourceProtocol, client)
  772. if clientID == "" {
  773. return false, common.NewError("empty client ID")
  774. }
  775. settingsBytes, err := json.Marshal(map[string][]model.Client{
  776. "clients": {client},
  777. })
  778. if err != nil {
  779. return false, err
  780. }
  781. updatePayload := &model.Inbound{
  782. Id: sourceInboundID,
  783. Settings: string(settingsBytes),
  784. }
  785. return s.UpdateInboundClient(updatePayload, clientID)
  786. }
  787. func (s *InboundService) generateRandomCredential(targetProtocol model.Protocol) string {
  788. switch targetProtocol {
  789. case model.VMESS, model.VLESS:
  790. return uuid.NewString()
  791. default:
  792. return strings.ReplaceAll(uuid.NewString(), "-", "")
  793. }
  794. }
  795. func (s *InboundService) buildTargetClientFromSource(source model.Client, targetProtocol model.Protocol, email string, flow string) (model.Client, error) {
  796. nowTs := time.Now().UnixMilli()
  797. target := source
  798. target.Email = email
  799. target.CreatedAt = nowTs
  800. target.UpdatedAt = nowTs
  801. target.ID = ""
  802. target.Password = ""
  803. target.Auth = ""
  804. target.Flow = ""
  805. switch targetProtocol {
  806. case model.VMESS:
  807. target.ID = s.generateRandomCredential(targetProtocol)
  808. case model.VLESS:
  809. target.ID = s.generateRandomCredential(targetProtocol)
  810. if flow == "xtls-rprx-vision" || flow == "xtls-rprx-vision-udp443" {
  811. target.Flow = flow
  812. }
  813. case model.Trojan, model.Shadowsocks:
  814. target.Password = s.generateRandomCredential(targetProtocol)
  815. case model.Hysteria:
  816. target.Auth = s.generateRandomCredential(targetProtocol)
  817. default:
  818. target.ID = s.generateRandomCredential(targetProtocol)
  819. }
  820. return target, nil
  821. }
  822. func (s *InboundService) nextAvailableCopiedEmail(originalEmail string, targetID int, occupied map[string]struct{}) string {
  823. base := fmt.Sprintf("%s_%d", originalEmail, targetID)
  824. candidate := base
  825. suffix := 0
  826. for {
  827. if _, exists := occupied[strings.ToLower(candidate)]; !exists {
  828. occupied[strings.ToLower(candidate)] = struct{}{}
  829. return candidate
  830. }
  831. suffix++
  832. candidate = fmt.Sprintf("%s_%d", base, suffix)
  833. }
  834. }
  835. func (s *InboundService) CopyInboundClients(targetInboundID int, sourceInboundID int, clientEmails []string, flow string) (*CopyClientsResult, bool, error) {
  836. result := &CopyClientsResult{
  837. Added: []string{},
  838. Skipped: []string{},
  839. Errors: []string{},
  840. }
  841. if targetInboundID == sourceInboundID {
  842. return result, false, common.NewError("source and target inbounds must be different")
  843. }
  844. targetInbound, err := s.GetInbound(targetInboundID)
  845. if err != nil {
  846. return result, false, err
  847. }
  848. sourceInbound, err := s.GetInbound(sourceInboundID)
  849. if err != nil {
  850. return result, false, err
  851. }
  852. sourceClients, err := s.GetClients(sourceInbound)
  853. if err != nil {
  854. return result, false, err
  855. }
  856. if len(sourceClients) == 0 {
  857. return result, false, nil
  858. }
  859. allowedEmails := map[string]struct{}{}
  860. if len(clientEmails) > 0 {
  861. for _, email := range clientEmails {
  862. allowedEmails[strings.ToLower(strings.TrimSpace(email))] = struct{}{}
  863. }
  864. }
  865. occupiedEmails := map[string]struct{}{}
  866. allEmails, err := s.getAllEmails()
  867. if err != nil {
  868. return result, false, err
  869. }
  870. for _, email := range allEmails {
  871. clean := strings.Trim(email, "\"")
  872. if clean != "" {
  873. occupiedEmails[strings.ToLower(clean)] = struct{}{}
  874. }
  875. }
  876. newClients := make([]model.Client, 0)
  877. needRestart := false
  878. for _, sourceClient := range sourceClients {
  879. originalEmail := strings.TrimSpace(sourceClient.Email)
  880. if originalEmail == "" {
  881. continue
  882. }
  883. if len(allowedEmails) > 0 {
  884. if _, ok := allowedEmails[strings.ToLower(originalEmail)]; !ok {
  885. continue
  886. }
  887. }
  888. if sourceClient.SubID == "" {
  889. newSubID := uuid.NewString()
  890. subNeedRestart, subErr := s.writeBackClientSubID(sourceInbound.Id, sourceInbound.Protocol, sourceClient, newSubID)
  891. if subErr != nil {
  892. result.Errors = append(result.Errors, fmt.Sprintf("%s: failed to write source subId: %v", originalEmail, subErr))
  893. continue
  894. }
  895. if subNeedRestart {
  896. needRestart = true
  897. }
  898. sourceClient.SubID = newSubID
  899. }
  900. targetEmail := s.nextAvailableCopiedEmail(originalEmail, targetInboundID, occupiedEmails)
  901. targetClient, buildErr := s.buildTargetClientFromSource(sourceClient, targetInbound.Protocol, targetEmail, flow)
  902. if buildErr != nil {
  903. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", originalEmail, buildErr))
  904. continue
  905. }
  906. newClients = append(newClients, targetClient)
  907. result.Added = append(result.Added, targetEmail)
  908. }
  909. if len(newClients) == 0 {
  910. return result, needRestart, nil
  911. }
  912. settingsPayload, err := json.Marshal(map[string][]model.Client{
  913. "clients": newClients,
  914. })
  915. if err != nil {
  916. return result, needRestart, err
  917. }
  918. addNeedRestart, err := s.AddInboundClient(&model.Inbound{
  919. Id: targetInboundID,
  920. Settings: string(settingsPayload),
  921. })
  922. if err != nil {
  923. return result, needRestart, err
  924. }
  925. if addNeedRestart {
  926. needRestart = true
  927. }
  928. return result, needRestart, nil
  929. }
  930. func (s *InboundService) DelInboundClient(inboundId int, clientId string) (bool, error) {
  931. oldInbound, err := s.GetInbound(inboundId)
  932. if err != nil {
  933. logger.Error("Load Old Data Error")
  934. return false, err
  935. }
  936. var settings map[string]any
  937. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  938. if err != nil {
  939. return false, err
  940. }
  941. email := ""
  942. client_key := "id"
  943. switch oldInbound.Protocol {
  944. case "trojan":
  945. client_key = "password"
  946. case "shadowsocks":
  947. client_key = "email"
  948. case "hysteria", "hysteria2":
  949. client_key = "auth"
  950. }
  951. interfaceClients := settings["clients"].([]any)
  952. var newClients []any
  953. needApiDel := false
  954. clientFound := false
  955. for _, client := range interfaceClients {
  956. c := client.(map[string]any)
  957. c_id := c[client_key].(string)
  958. if c_id == clientId {
  959. clientFound = true
  960. email, _ = c["email"].(string)
  961. needApiDel, _ = c["enable"].(bool)
  962. } else {
  963. newClients = append(newClients, client)
  964. }
  965. }
  966. if !clientFound {
  967. return false, common.NewError("Client Not Found In Inbound For ID:", clientId)
  968. }
  969. if len(newClients) == 0 {
  970. return false, common.NewError("no client remained in Inbound")
  971. }
  972. settings["clients"] = newClients
  973. newSettings, err := json.MarshalIndent(settings, "", " ")
  974. if err != nil {
  975. return false, err
  976. }
  977. oldInbound.Settings = string(newSettings)
  978. db := database.GetDB()
  979. err = s.DelClientIPs(db, email)
  980. if err != nil {
  981. logger.Error("Error in delete client IPs")
  982. return false, err
  983. }
  984. needRestart := false
  985. if len(email) > 0 {
  986. notDepleted := true
  987. err = db.Model(xray.ClientTraffic{}).Select("enable").Where("email = ?", email).First(&notDepleted).Error
  988. if err != nil {
  989. logger.Error("Get stats error")
  990. return false, err
  991. }
  992. err = s.DelClientStat(db, email)
  993. if err != nil {
  994. logger.Error("Delete stats Data Error")
  995. return false, err
  996. }
  997. if needApiDel && notDepleted {
  998. s.xrayApi.Init(p.GetAPIPort())
  999. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email)
  1000. if err1 == nil {
  1001. logger.Debug("Client deleted by api:", email)
  1002. needRestart = false
  1003. } else {
  1004. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  1005. logger.Debug("User is already deleted. Nothing to do more...")
  1006. } else {
  1007. logger.Debug("Error in deleting client by api:", err1)
  1008. needRestart = true
  1009. }
  1010. }
  1011. s.xrayApi.Close()
  1012. }
  1013. }
  1014. return needRestart, db.Save(oldInbound).Error
  1015. }
  1016. func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId string) (bool, error) {
  1017. // TODO: check if TrafficReset field is updating
  1018. clients, err := s.GetClients(data)
  1019. if err != nil {
  1020. return false, err
  1021. }
  1022. var settings map[string]any
  1023. err = json.Unmarshal([]byte(data.Settings), &settings)
  1024. if err != nil {
  1025. return false, err
  1026. }
  1027. interfaceClients := settings["clients"].([]any)
  1028. oldInbound, err := s.GetInbound(data.Id)
  1029. if err != nil {
  1030. return false, err
  1031. }
  1032. oldClients, err := s.GetClients(oldInbound)
  1033. if err != nil {
  1034. return false, err
  1035. }
  1036. oldEmail := ""
  1037. newClientId := ""
  1038. clientIndex := -1
  1039. for index, oldClient := range oldClients {
  1040. oldClientId := ""
  1041. switch oldInbound.Protocol {
  1042. case "trojan":
  1043. oldClientId = oldClient.Password
  1044. newClientId = clients[0].Password
  1045. case "shadowsocks":
  1046. oldClientId = oldClient.Email
  1047. newClientId = clients[0].Email
  1048. case "hysteria", "hysteria2":
  1049. oldClientId = oldClient.Auth
  1050. newClientId = clients[0].Auth
  1051. default:
  1052. oldClientId = oldClient.ID
  1053. newClientId = clients[0].ID
  1054. }
  1055. if clientId == oldClientId {
  1056. oldEmail = oldClient.Email
  1057. clientIndex = index
  1058. break
  1059. }
  1060. }
  1061. // Validate new client ID
  1062. if newClientId == "" || clientIndex == -1 {
  1063. return false, common.NewError("empty client ID")
  1064. }
  1065. if len(clients[0].Email) > 0 && clients[0].Email != oldEmail {
  1066. existEmail, err := s.checkEmailsExistForClients(clients)
  1067. if err != nil {
  1068. return false, err
  1069. }
  1070. if existEmail != "" {
  1071. return false, common.NewError("Duplicate email:", existEmail)
  1072. }
  1073. }
  1074. var oldSettings map[string]any
  1075. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1076. if err != nil {
  1077. return false, err
  1078. }
  1079. settingsClients := oldSettings["clients"].([]any)
  1080. // Preserve created_at and set updated_at for the replacing client
  1081. var preservedCreated any
  1082. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  1083. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  1084. if v, ok2 := oldMap["created_at"]; ok2 {
  1085. preservedCreated = v
  1086. }
  1087. }
  1088. }
  1089. if len(interfaceClients) > 0 {
  1090. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  1091. if preservedCreated == nil {
  1092. preservedCreated = time.Now().Unix() * 1000
  1093. }
  1094. newMap["created_at"] = preservedCreated
  1095. newMap["updated_at"] = time.Now().Unix() * 1000
  1096. interfaceClients[0] = newMap
  1097. }
  1098. }
  1099. settingsClients[clientIndex] = interfaceClients[0]
  1100. oldSettings["clients"] = settingsClients
  1101. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1102. if err != nil {
  1103. return false, err
  1104. }
  1105. oldInbound.Settings = string(newSettings)
  1106. db := database.GetDB()
  1107. tx := db.Begin()
  1108. defer func() {
  1109. if err != nil {
  1110. tx.Rollback()
  1111. } else {
  1112. tx.Commit()
  1113. }
  1114. }()
  1115. if len(clients[0].Email) > 0 {
  1116. if len(oldEmail) > 0 {
  1117. err = s.UpdateClientStat(tx, oldEmail, &clients[0])
  1118. if err != nil {
  1119. return false, err
  1120. }
  1121. err = s.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  1122. if err != nil {
  1123. return false, err
  1124. }
  1125. } else {
  1126. s.AddClientStat(tx, data.Id, &clients[0])
  1127. }
  1128. } else {
  1129. err = s.DelClientStat(tx, oldEmail)
  1130. if err != nil {
  1131. return false, err
  1132. }
  1133. err = s.DelClientIPs(tx, oldEmail)
  1134. if err != nil {
  1135. return false, err
  1136. }
  1137. }
  1138. needRestart := false
  1139. if len(oldEmail) > 0 {
  1140. s.xrayApi.Init(p.GetAPIPort())
  1141. if oldClients[clientIndex].Enable {
  1142. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, oldEmail)
  1143. if err1 == nil {
  1144. logger.Debug("Old client deleted by api:", oldEmail)
  1145. } else {
  1146. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  1147. logger.Debug("User is already deleted. Nothing to do more...")
  1148. } else {
  1149. logger.Debug("Error in deleting client by api:", err1)
  1150. needRestart = true
  1151. }
  1152. }
  1153. }
  1154. if clients[0].Enable {
  1155. cipher := ""
  1156. if oldInbound.Protocol == "shadowsocks" {
  1157. cipher = oldSettings["method"].(string)
  1158. }
  1159. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]any{
  1160. "email": clients[0].Email,
  1161. "id": clients[0].ID,
  1162. "security": clients[0].Security,
  1163. "flow": clients[0].Flow,
  1164. "auth": clients[0].Auth,
  1165. "password": clients[0].Password,
  1166. "cipher": cipher,
  1167. })
  1168. if err1 == nil {
  1169. logger.Debug("Client edited by api:", clients[0].Email)
  1170. } else {
  1171. logger.Debug("Error in adding client by api:", err1)
  1172. needRestart = true
  1173. }
  1174. }
  1175. s.xrayApi.Close()
  1176. } else {
  1177. logger.Debug("Client old email not found")
  1178. needRestart = true
  1179. }
  1180. return needRestart, tx.Save(oldInbound).Error
  1181. }
  1182. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (bool, bool, error) {
  1183. var err error
  1184. db := database.GetDB()
  1185. tx := db.Begin()
  1186. defer func() {
  1187. if err != nil {
  1188. tx.Rollback()
  1189. } else {
  1190. tx.Commit()
  1191. }
  1192. }()
  1193. err = s.addInboundTraffic(tx, inboundTraffics)
  1194. if err != nil {
  1195. return false, false, err
  1196. }
  1197. err = s.addClientTraffic(tx, clientTraffics)
  1198. if err != nil {
  1199. return false, false, err
  1200. }
  1201. needRestart0, count, err := s.autoRenewClients(tx)
  1202. if err != nil {
  1203. logger.Warning("Error in renew clients:", err)
  1204. } else if count > 0 {
  1205. logger.Debugf("%v clients renewed", count)
  1206. }
  1207. disabledClientsCount := int64(0)
  1208. needRestart1, count, err := s.disableInvalidClients(tx)
  1209. if err != nil {
  1210. logger.Warning("Error in disabling invalid clients:", err)
  1211. } else if count > 0 {
  1212. logger.Debugf("%v clients disabled", count)
  1213. disabledClientsCount = count
  1214. }
  1215. needRestart2, count, err := s.disableInvalidInbounds(tx)
  1216. if err != nil {
  1217. logger.Warning("Error in disabling invalid inbounds:", err)
  1218. } else if count > 0 {
  1219. logger.Debugf("%v inbounds disabled", count)
  1220. }
  1221. return needRestart0 || needRestart1 || needRestart2, disabledClientsCount > 0, nil
  1222. }
  1223. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  1224. if len(traffics) == 0 {
  1225. return nil
  1226. }
  1227. var err error
  1228. for _, traffic := range traffics {
  1229. if traffic.IsInbound {
  1230. err = tx.Model(&model.Inbound{}).Where("tag = ?", traffic.Tag).
  1231. Updates(map[string]any{
  1232. "up": gorm.Expr("up + ?", traffic.Up),
  1233. "down": gorm.Expr("down + ?", traffic.Down),
  1234. "all_time": gorm.Expr("COALESCE(all_time, 0) + ?", traffic.Up+traffic.Down),
  1235. }).Error
  1236. if err != nil {
  1237. return err
  1238. }
  1239. }
  1240. }
  1241. return nil
  1242. }
  1243. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  1244. if len(traffics) == 0 {
  1245. // Empty onlineUsers
  1246. if p != nil {
  1247. p.SetOnlineClients(make([]string, 0))
  1248. }
  1249. return nil
  1250. }
  1251. onlineClients := make([]string, 0)
  1252. emails := make([]string, 0, len(traffics))
  1253. for _, traffic := range traffics {
  1254. emails = append(emails, traffic.Email)
  1255. }
  1256. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  1257. err = tx.Model(xray.ClientTraffic{}).Where("email IN (?)", emails).Find(&dbClientTraffics).Error
  1258. if err != nil {
  1259. return err
  1260. }
  1261. // Avoid empty slice error
  1262. if len(dbClientTraffics) == 0 {
  1263. return nil
  1264. }
  1265. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  1266. if err != nil {
  1267. return err
  1268. }
  1269. // Index by email for O(N) merge — the previous nested loop was O(N²)
  1270. // and dominated each cron tick on inbounds with thousands of active
  1271. // clients (7500 × 7500 = 56M string comparisons every 10 seconds).
  1272. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  1273. for i := range traffics {
  1274. if traffics[i] != nil {
  1275. trafficByEmail[traffics[i].Email] = traffics[i]
  1276. }
  1277. }
  1278. now := time.Now().UnixMilli()
  1279. for dbTraffic_index := range dbClientTraffics {
  1280. t, ok := trafficByEmail[dbClientTraffics[dbTraffic_index].Email]
  1281. if !ok {
  1282. continue
  1283. }
  1284. dbClientTraffics[dbTraffic_index].Up += t.Up
  1285. dbClientTraffics[dbTraffic_index].Down += t.Down
  1286. dbClientTraffics[dbTraffic_index].AllTime += t.Up + t.Down
  1287. if t.Up+t.Down > 0 {
  1288. onlineClients = append(onlineClients, t.Email)
  1289. dbClientTraffics[dbTraffic_index].LastOnline = now
  1290. }
  1291. }
  1292. // Set onlineUsers
  1293. p.SetOnlineClients(onlineClients)
  1294. err = tx.Save(dbClientTraffics).Error
  1295. if err != nil {
  1296. logger.Warning("AddClientTraffic update data ", err)
  1297. }
  1298. return nil
  1299. }
  1300. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  1301. inboundIds := make([]int, 0, len(dbClientTraffics))
  1302. for _, dbClientTraffic := range dbClientTraffics {
  1303. if dbClientTraffic.ExpiryTime < 0 {
  1304. inboundIds = append(inboundIds, dbClientTraffic.InboundId)
  1305. }
  1306. }
  1307. if len(inboundIds) > 0 {
  1308. var inbounds []*model.Inbound
  1309. err := tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  1310. if err != nil {
  1311. return nil, err
  1312. }
  1313. for inbound_index := range inbounds {
  1314. settings := map[string]any{}
  1315. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1316. clients, ok := settings["clients"].([]any)
  1317. if ok {
  1318. var newClients []any
  1319. for client_index := range clients {
  1320. c := clients[client_index].(map[string]any)
  1321. for traffic_index := range dbClientTraffics {
  1322. if dbClientTraffics[traffic_index].ExpiryTime < 0 && c["email"] == dbClientTraffics[traffic_index].Email {
  1323. oldExpiryTime := c["expiryTime"].(float64)
  1324. newExpiryTime := (time.Now().Unix() * 1000) - int64(oldExpiryTime)
  1325. c["expiryTime"] = newExpiryTime
  1326. c["updated_at"] = time.Now().Unix() * 1000
  1327. dbClientTraffics[traffic_index].ExpiryTime = newExpiryTime
  1328. break
  1329. }
  1330. }
  1331. // Backfill created_at and updated_at
  1332. if _, ok := c["created_at"]; !ok {
  1333. c["created_at"] = time.Now().Unix() * 1000
  1334. }
  1335. c["updated_at"] = time.Now().Unix() * 1000
  1336. newClients = append(newClients, any(c))
  1337. }
  1338. settings["clients"] = newClients
  1339. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1340. if err != nil {
  1341. return nil, err
  1342. }
  1343. inbounds[inbound_index].Settings = string(modifiedSettings)
  1344. }
  1345. }
  1346. err = tx.Save(inbounds).Error
  1347. if err != nil {
  1348. logger.Warning("AddClientTraffic update inbounds ", err)
  1349. logger.Error(inbounds)
  1350. }
  1351. }
  1352. return dbClientTraffics, nil
  1353. }
  1354. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  1355. // check for time expired
  1356. var traffics []*xray.ClientTraffic
  1357. now := time.Now().Unix() * 1000
  1358. var err, err1 error
  1359. err = tx.Model(xray.ClientTraffic{}).Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).Find(&traffics).Error
  1360. if err != nil {
  1361. return false, 0, err
  1362. }
  1363. // return if there is no client to renew
  1364. if len(traffics) == 0 {
  1365. return false, 0, nil
  1366. }
  1367. var inbound_ids []int
  1368. var inbounds []*model.Inbound
  1369. needRestart := false
  1370. var clientsToAdd []struct {
  1371. protocol string
  1372. tag string
  1373. client map[string]any
  1374. }
  1375. for _, traffic := range traffics {
  1376. inbound_ids = append(inbound_ids, traffic.InboundId)
  1377. }
  1378. // Dedupe so an inbound hosting N expired clients is fetched and saved once
  1379. // per tick instead of N times across chunk boundaries.
  1380. inbound_ids = uniqueInts(inbound_ids)
  1381. // Chunked to stay under SQLite's bind-variable limit when many inbounds
  1382. // are touched in a single tick.
  1383. for _, batch := range chunkInts(inbound_ids, sqliteMaxVars) {
  1384. var page []*model.Inbound
  1385. if err = tx.Model(model.Inbound{}).Where("id IN ?", batch).Find(&page).Error; err != nil {
  1386. return false, 0, err
  1387. }
  1388. inbounds = append(inbounds, page...)
  1389. }
  1390. for inbound_index := range inbounds {
  1391. settings := map[string]any{}
  1392. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1393. clients := settings["clients"].([]any)
  1394. for client_index := range clients {
  1395. c := clients[client_index].(map[string]any)
  1396. for traffic_index, traffic := range traffics {
  1397. if traffic.Email == c["email"].(string) {
  1398. newExpiryTime := traffic.ExpiryTime
  1399. for newExpiryTime < now {
  1400. newExpiryTime += (int64(traffic.Reset) * 86400000)
  1401. }
  1402. c["expiryTime"] = newExpiryTime
  1403. traffics[traffic_index].ExpiryTime = newExpiryTime
  1404. traffics[traffic_index].Down = 0
  1405. traffics[traffic_index].Up = 0
  1406. if !traffic.Enable {
  1407. traffics[traffic_index].Enable = true
  1408. clientsToAdd = append(clientsToAdd,
  1409. struct {
  1410. protocol string
  1411. tag string
  1412. client map[string]any
  1413. }{
  1414. protocol: string(inbounds[inbound_index].Protocol),
  1415. tag: inbounds[inbound_index].Tag,
  1416. client: c,
  1417. })
  1418. }
  1419. clients[client_index] = any(c)
  1420. break
  1421. }
  1422. }
  1423. }
  1424. settings["clients"] = clients
  1425. newSettings, err := json.MarshalIndent(settings, "", " ")
  1426. if err != nil {
  1427. return false, 0, err
  1428. }
  1429. inbounds[inbound_index].Settings = string(newSettings)
  1430. }
  1431. err = tx.Save(inbounds).Error
  1432. if err != nil {
  1433. return false, 0, err
  1434. }
  1435. err = tx.Save(traffics).Error
  1436. if err != nil {
  1437. return false, 0, err
  1438. }
  1439. if p != nil {
  1440. err1 = s.xrayApi.Init(p.GetAPIPort())
  1441. if err1 != nil {
  1442. return true, int64(len(traffics)), nil
  1443. }
  1444. for _, clientToAdd := range clientsToAdd {
  1445. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  1446. if err1 != nil {
  1447. needRestart = true
  1448. }
  1449. }
  1450. s.xrayApi.Close()
  1451. }
  1452. return needRestart, int64(len(traffics)), nil
  1453. }
  1454. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  1455. now := time.Now().Unix() * 1000
  1456. needRestart := false
  1457. if p != nil {
  1458. var tags []string
  1459. err := tx.Table("inbounds").
  1460. Select("inbounds.tag").
  1461. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1462. Scan(&tags).Error
  1463. if err != nil {
  1464. return false, 0, err
  1465. }
  1466. s.xrayApi.Init(p.GetAPIPort())
  1467. for _, tag := range tags {
  1468. err1 := s.xrayApi.DelInbound(tag)
  1469. if err1 == nil {
  1470. logger.Debug("Inbound disabled by api:", tag)
  1471. } else {
  1472. logger.Debug("Error in disabling inbound by api:", err1)
  1473. needRestart = true
  1474. }
  1475. }
  1476. s.xrayApi.Close()
  1477. }
  1478. result := tx.Model(model.Inbound{}).
  1479. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1480. Update("enable", false)
  1481. err := result.Error
  1482. count := result.RowsAffected
  1483. return needRestart, count, err
  1484. }
  1485. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error) {
  1486. now := time.Now().Unix() * 1000
  1487. needRestart := false
  1488. var clientsToDisable []struct {
  1489. InboundId int
  1490. Tag string
  1491. Email string
  1492. }
  1493. err := tx.Table("inbounds").
  1494. Select("inbounds.id as inbound_id, inbounds.tag, client_traffics.email").
  1495. Joins("JOIN client_traffics ON inbounds.id = client_traffics.inbound_id").
  1496. Where("((client_traffics.total > 0 AND client_traffics.up + client_traffics.down >= client_traffics.total) OR (client_traffics.expiry_time > 0 AND client_traffics.expiry_time <= ?)) AND client_traffics.enable = ?", now, true).
  1497. Scan(&clientsToDisable).Error
  1498. if err != nil {
  1499. return false, 0, err
  1500. }
  1501. if p != nil {
  1502. s.xrayApi.Init(p.GetAPIPort())
  1503. for _, client := range clientsToDisable {
  1504. err1 := s.xrayApi.RemoveUser(client.Tag, client.Email)
  1505. if err1 == nil {
  1506. logger.Debug("Client disabled by api:", client.Email)
  1507. } else {
  1508. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", client.Email)) {
  1509. logger.Debug("User is already disabled. Nothing to do more...")
  1510. } else {
  1511. logger.Debug("Error in disabling client by api:", err1)
  1512. needRestart = true
  1513. }
  1514. }
  1515. }
  1516. s.xrayApi.Close()
  1517. }
  1518. result := tx.Model(xray.ClientTraffic{}).
  1519. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1520. Update("enable", false)
  1521. err = result.Error
  1522. count := result.RowsAffected
  1523. if err != nil {
  1524. return needRestart, count, err
  1525. }
  1526. // Also set enable=false in inbounds.settings JSON so clients are visibly disabled
  1527. if len(clientsToDisable) > 0 {
  1528. inboundEmailMap := make(map[int]map[string]struct{})
  1529. for _, c := range clientsToDisable {
  1530. if inboundEmailMap[c.InboundId] == nil {
  1531. inboundEmailMap[c.InboundId] = make(map[string]struct{})
  1532. }
  1533. inboundEmailMap[c.InboundId][c.Email] = struct{}{}
  1534. }
  1535. inboundIds := make([]int, 0, len(inboundEmailMap))
  1536. for id := range inboundEmailMap {
  1537. inboundIds = append(inboundIds, id)
  1538. }
  1539. var inbounds []*model.Inbound
  1540. if err = tx.Model(model.Inbound{}).Where("id IN ?", inboundIds).Find(&inbounds).Error; err != nil {
  1541. logger.Warning("disableInvalidClients fetch inbounds:", err)
  1542. return needRestart, count, nil
  1543. }
  1544. for _, inbound := range inbounds {
  1545. settings := map[string]any{}
  1546. if jsonErr := json.Unmarshal([]byte(inbound.Settings), &settings); jsonErr != nil {
  1547. continue
  1548. }
  1549. clients, ok := settings["clients"].([]any)
  1550. if !ok {
  1551. continue
  1552. }
  1553. emailSet := inboundEmailMap[inbound.Id]
  1554. changed := false
  1555. for i := range clients {
  1556. c, ok := clients[i].(map[string]any)
  1557. if !ok {
  1558. continue
  1559. }
  1560. email, _ := c["email"].(string)
  1561. if _, shouldDisable := emailSet[email]; shouldDisable {
  1562. c["enable"] = false
  1563. c["updated_at"] = time.Now().Unix() * 1000
  1564. clients[i] = c
  1565. changed = true
  1566. }
  1567. }
  1568. if changed {
  1569. settings["clients"] = clients
  1570. modifiedSettings, jsonErr := json.MarshalIndent(settings, "", " ")
  1571. if jsonErr != nil {
  1572. continue
  1573. }
  1574. inbound.Settings = string(modifiedSettings)
  1575. }
  1576. }
  1577. if err = tx.Save(inbounds).Error; err != nil {
  1578. logger.Warning("disableInvalidClients update inbound settings:", err)
  1579. }
  1580. }
  1581. return needRestart, count, nil
  1582. }
  1583. func (s *InboundService) GetInboundTags() (string, error) {
  1584. db := database.GetDB()
  1585. var inboundTags []string
  1586. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1587. if err != nil && err != gorm.ErrRecordNotFound {
  1588. return "", err
  1589. }
  1590. tags, _ := json.Marshal(inboundTags)
  1591. return string(tags), nil
  1592. }
  1593. func (s *InboundService) GetClientReverseTags() (string, error) {
  1594. db := database.GetDB()
  1595. var rawTags []string
  1596. err := db.Raw(`
  1597. SELECT DISTINCT JSON_EXTRACT(client.value, '$.reverse.tag')
  1598. FROM inbounds,
  1599. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1600. WHERE inbounds.protocol = 'vless'
  1601. AND JSON_EXTRACT(client.value, '$.reverse.tag') IS NOT NULL
  1602. AND JSON_EXTRACT(client.value, '$.reverse.tag') != ''
  1603. `).Scan(&rawTags).Error
  1604. if err != nil && err != gorm.ErrRecordNotFound {
  1605. return "[]", err
  1606. }
  1607. result, _ := json.Marshal(rawTags)
  1608. return string(result), nil
  1609. }
  1610. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  1611. db := database.GetDB()
  1612. db.Exec(`
  1613. DELETE FROM client_traffics
  1614. WHERE email NOT IN (
  1615. SELECT JSON_EXTRACT(client.value, '$.email')
  1616. FROM inbounds,
  1617. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1618. )
  1619. `)
  1620. }
  1621. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  1622. clientTraffic := xray.ClientTraffic{}
  1623. clientTraffic.InboundId = inboundId
  1624. clientTraffic.Email = client.Email
  1625. clientTraffic.Total = client.TotalGB
  1626. clientTraffic.ExpiryTime = client.ExpiryTime
  1627. clientTraffic.Enable = client.Enable
  1628. clientTraffic.Up = 0
  1629. clientTraffic.Down = 0
  1630. clientTraffic.Reset = client.Reset
  1631. result := tx.Create(&clientTraffic)
  1632. err := result.Error
  1633. return err
  1634. }
  1635. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  1636. result := tx.Model(xray.ClientTraffic{}).
  1637. Where("email = ?", email).
  1638. Updates(map[string]any{
  1639. "enable": client.Enable,
  1640. "email": client.Email,
  1641. "total": client.TotalGB,
  1642. "expiry_time": client.ExpiryTime,
  1643. "reset": client.Reset,
  1644. })
  1645. err := result.Error
  1646. return err
  1647. }
  1648. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  1649. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  1650. }
  1651. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  1652. return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error
  1653. }
  1654. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  1655. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  1656. }
  1657. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1658. db := database.GetDB()
  1659. var traffics []*xray.ClientTraffic
  1660. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  1661. if err != nil {
  1662. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  1663. return nil, nil, err
  1664. }
  1665. if len(traffics) > 0 {
  1666. inbound, err = s.GetInbound(traffics[0].InboundId)
  1667. return traffics[0], inbound, err
  1668. }
  1669. return nil, nil, nil
  1670. }
  1671. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1672. db := database.GetDB()
  1673. var traffics []*xray.ClientTraffic
  1674. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  1675. if err != nil {
  1676. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1677. return nil, nil, err
  1678. }
  1679. if len(traffics) > 0 {
  1680. inbound, err = s.GetInbound(traffics[0].InboundId)
  1681. return traffics[0], inbound, err
  1682. }
  1683. return nil, nil, nil
  1684. }
  1685. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  1686. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1687. if err != nil {
  1688. return nil, nil, err
  1689. }
  1690. if inbound == nil {
  1691. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  1692. }
  1693. clients, err := s.GetClients(inbound)
  1694. if err != nil {
  1695. return nil, nil, err
  1696. }
  1697. for _, client := range clients {
  1698. if client.Email == clientEmail {
  1699. return traffic, &client, nil
  1700. }
  1701. }
  1702. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  1703. }
  1704. func (s *InboundService) SetClientTelegramUserID(trafficId int, tgId int64) (bool, error) {
  1705. traffic, inbound, err := s.GetClientInboundByTrafficID(trafficId)
  1706. if err != nil {
  1707. return false, err
  1708. }
  1709. if inbound == nil {
  1710. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  1711. }
  1712. clientEmail := traffic.Email
  1713. oldClients, err := s.GetClients(inbound)
  1714. if err != nil {
  1715. return false, err
  1716. }
  1717. clientId := ""
  1718. for _, oldClient := range oldClients {
  1719. if oldClient.Email == clientEmail {
  1720. switch inbound.Protocol {
  1721. case "trojan":
  1722. clientId = oldClient.Password
  1723. case "shadowsocks":
  1724. clientId = oldClient.Email
  1725. default:
  1726. clientId = oldClient.ID
  1727. }
  1728. break
  1729. }
  1730. }
  1731. if len(clientId) == 0 {
  1732. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1733. }
  1734. var settings map[string]any
  1735. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1736. if err != nil {
  1737. return false, err
  1738. }
  1739. clients := settings["clients"].([]any)
  1740. var newClients []any
  1741. for client_index := range clients {
  1742. c := clients[client_index].(map[string]any)
  1743. if c["email"] == clientEmail {
  1744. c["tgId"] = tgId
  1745. c["updated_at"] = time.Now().Unix() * 1000
  1746. newClients = append(newClients, any(c))
  1747. }
  1748. }
  1749. settings["clients"] = newClients
  1750. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1751. if err != nil {
  1752. return false, err
  1753. }
  1754. inbound.Settings = string(modifiedSettings)
  1755. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1756. return needRestart, err
  1757. }
  1758. func (s *InboundService) checkIsEnabledByEmail(clientEmail string) (bool, error) {
  1759. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1760. if err != nil {
  1761. return false, err
  1762. }
  1763. if inbound == nil {
  1764. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1765. }
  1766. clients, err := s.GetClients(inbound)
  1767. if err != nil {
  1768. return false, err
  1769. }
  1770. isEnable := false
  1771. for _, client := range clients {
  1772. if client.Email == clientEmail {
  1773. isEnable = client.Enable
  1774. break
  1775. }
  1776. }
  1777. return isEnable, err
  1778. }
  1779. func (s *InboundService) ToggleClientEnableByEmail(clientEmail string) (bool, bool, error) {
  1780. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1781. if err != nil {
  1782. return false, false, err
  1783. }
  1784. if inbound == nil {
  1785. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1786. }
  1787. oldClients, err := s.GetClients(inbound)
  1788. if err != nil {
  1789. return false, false, err
  1790. }
  1791. clientId := ""
  1792. clientOldEnabled := false
  1793. for _, oldClient := range oldClients {
  1794. if oldClient.Email == clientEmail {
  1795. switch inbound.Protocol {
  1796. case "trojan":
  1797. clientId = oldClient.Password
  1798. case "shadowsocks":
  1799. clientId = oldClient.Email
  1800. default:
  1801. clientId = oldClient.ID
  1802. }
  1803. clientOldEnabled = oldClient.Enable
  1804. break
  1805. }
  1806. }
  1807. if len(clientId) == 0 {
  1808. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  1809. }
  1810. var settings map[string]any
  1811. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1812. if err != nil {
  1813. return false, false, err
  1814. }
  1815. clients := settings["clients"].([]any)
  1816. var newClients []any
  1817. for client_index := range clients {
  1818. c := clients[client_index].(map[string]any)
  1819. if c["email"] == clientEmail {
  1820. c["enable"] = !clientOldEnabled
  1821. c["updated_at"] = time.Now().Unix() * 1000
  1822. newClients = append(newClients, any(c))
  1823. }
  1824. }
  1825. settings["clients"] = newClients
  1826. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1827. if err != nil {
  1828. return false, false, err
  1829. }
  1830. inbound.Settings = string(modifiedSettings)
  1831. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1832. if err != nil {
  1833. return false, needRestart, err
  1834. }
  1835. return !clientOldEnabled, needRestart, nil
  1836. }
  1837. // SetClientEnableByEmail sets client enable state to desired value; returns (changed, needRestart, error)
  1838. func (s *InboundService) SetClientEnableByEmail(clientEmail string, enable bool) (bool, bool, error) {
  1839. current, err := s.checkIsEnabledByEmail(clientEmail)
  1840. if err != nil {
  1841. return false, false, err
  1842. }
  1843. if current == enable {
  1844. return false, false, nil
  1845. }
  1846. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(clientEmail)
  1847. if err != nil {
  1848. return false, needRestart, err
  1849. }
  1850. return newEnabled == enable, needRestart, nil
  1851. }
  1852. func (s *InboundService) ResetClientIpLimitByEmail(clientEmail string, count int) (bool, error) {
  1853. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1854. if err != nil {
  1855. return false, err
  1856. }
  1857. if inbound == nil {
  1858. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1859. }
  1860. oldClients, err := s.GetClients(inbound)
  1861. if err != nil {
  1862. return false, err
  1863. }
  1864. clientId := ""
  1865. for _, oldClient := range oldClients {
  1866. if oldClient.Email == clientEmail {
  1867. switch inbound.Protocol {
  1868. case "trojan":
  1869. clientId = oldClient.Password
  1870. case "shadowsocks":
  1871. clientId = oldClient.Email
  1872. default:
  1873. clientId = oldClient.ID
  1874. }
  1875. break
  1876. }
  1877. }
  1878. if len(clientId) == 0 {
  1879. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1880. }
  1881. var settings map[string]any
  1882. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1883. if err != nil {
  1884. return false, err
  1885. }
  1886. clients := settings["clients"].([]any)
  1887. var newClients []any
  1888. for client_index := range clients {
  1889. c := clients[client_index].(map[string]any)
  1890. if c["email"] == clientEmail {
  1891. c["limitIp"] = count
  1892. c["updated_at"] = time.Now().Unix() * 1000
  1893. newClients = append(newClients, any(c))
  1894. }
  1895. }
  1896. settings["clients"] = newClients
  1897. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1898. if err != nil {
  1899. return false, err
  1900. }
  1901. inbound.Settings = string(modifiedSettings)
  1902. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1903. return needRestart, err
  1904. }
  1905. func (s *InboundService) ResetClientExpiryTimeByEmail(clientEmail string, expiry_time int64) (bool, error) {
  1906. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1907. if err != nil {
  1908. return false, err
  1909. }
  1910. if inbound == nil {
  1911. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1912. }
  1913. oldClients, err := s.GetClients(inbound)
  1914. if err != nil {
  1915. return false, err
  1916. }
  1917. clientId := ""
  1918. for _, oldClient := range oldClients {
  1919. if oldClient.Email == clientEmail {
  1920. switch inbound.Protocol {
  1921. case "trojan":
  1922. clientId = oldClient.Password
  1923. case "shadowsocks":
  1924. clientId = oldClient.Email
  1925. default:
  1926. clientId = oldClient.ID
  1927. }
  1928. break
  1929. }
  1930. }
  1931. if len(clientId) == 0 {
  1932. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1933. }
  1934. var settings map[string]any
  1935. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1936. if err != nil {
  1937. return false, err
  1938. }
  1939. clients := settings["clients"].([]any)
  1940. var newClients []any
  1941. for client_index := range clients {
  1942. c := clients[client_index].(map[string]any)
  1943. if c["email"] == clientEmail {
  1944. c["expiryTime"] = expiry_time
  1945. c["updated_at"] = time.Now().Unix() * 1000
  1946. newClients = append(newClients, any(c))
  1947. }
  1948. }
  1949. settings["clients"] = newClients
  1950. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1951. if err != nil {
  1952. return false, err
  1953. }
  1954. inbound.Settings = string(modifiedSettings)
  1955. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1956. return needRestart, err
  1957. }
  1958. func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, totalGB int) (bool, error) {
  1959. if totalGB < 0 {
  1960. return false, common.NewError("totalGB must be >= 0")
  1961. }
  1962. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1963. if err != nil {
  1964. return false, err
  1965. }
  1966. if inbound == nil {
  1967. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1968. }
  1969. oldClients, err := s.GetClients(inbound)
  1970. if err != nil {
  1971. return false, err
  1972. }
  1973. clientId := ""
  1974. for _, oldClient := range oldClients {
  1975. if oldClient.Email == clientEmail {
  1976. switch inbound.Protocol {
  1977. case "trojan":
  1978. clientId = oldClient.Password
  1979. case "shadowsocks":
  1980. clientId = oldClient.Email
  1981. default:
  1982. clientId = oldClient.ID
  1983. }
  1984. break
  1985. }
  1986. }
  1987. if len(clientId) == 0 {
  1988. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1989. }
  1990. var settings map[string]any
  1991. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1992. if err != nil {
  1993. return false, err
  1994. }
  1995. clients := settings["clients"].([]any)
  1996. var newClients []any
  1997. for client_index := range clients {
  1998. c := clients[client_index].(map[string]any)
  1999. if c["email"] == clientEmail {
  2000. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  2001. c["updated_at"] = time.Now().Unix() * 1000
  2002. newClients = append(newClients, any(c))
  2003. }
  2004. }
  2005. settings["clients"] = newClients
  2006. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2007. if err != nil {
  2008. return false, err
  2009. }
  2010. inbound.Settings = string(modifiedSettings)
  2011. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2012. return needRestart, err
  2013. }
  2014. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  2015. db := database.GetDB()
  2016. // Reset traffic stats in ClientTraffic table
  2017. result := db.Model(xray.ClientTraffic{}).
  2018. Where("email = ?", clientEmail).
  2019. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  2020. err := result.Error
  2021. if err != nil {
  2022. return err
  2023. }
  2024. return nil
  2025. }
  2026. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, error) {
  2027. needRestart := false
  2028. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  2029. if err != nil {
  2030. return false, err
  2031. }
  2032. if !traffic.Enable {
  2033. inbound, err := s.GetInbound(id)
  2034. if err != nil {
  2035. return false, err
  2036. }
  2037. clients, err := s.GetClients(inbound)
  2038. if err != nil {
  2039. return false, err
  2040. }
  2041. for _, client := range clients {
  2042. if client.Email == clientEmail && client.Enable {
  2043. s.xrayApi.Init(p.GetAPIPort())
  2044. cipher := ""
  2045. if string(inbound.Protocol) == "shadowsocks" {
  2046. var oldSettings map[string]any
  2047. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  2048. if err != nil {
  2049. return false, err
  2050. }
  2051. cipher = oldSettings["method"].(string)
  2052. }
  2053. err1 := s.xrayApi.AddUser(string(inbound.Protocol), inbound.Tag, map[string]any{
  2054. "email": client.Email,
  2055. "id": client.ID,
  2056. "auth": client.Auth,
  2057. "security": client.Security,
  2058. "flow": client.Flow,
  2059. "password": client.Password,
  2060. "cipher": cipher,
  2061. })
  2062. if err1 == nil {
  2063. logger.Debug("Client enabled due to reset traffic:", clientEmail)
  2064. } else {
  2065. logger.Debug("Error in enabling client by api:", err1)
  2066. needRestart = true
  2067. }
  2068. s.xrayApi.Close()
  2069. break
  2070. }
  2071. }
  2072. }
  2073. traffic.Up = 0
  2074. traffic.Down = 0
  2075. traffic.Enable = true
  2076. db := database.GetDB()
  2077. err = db.Save(traffic).Error
  2078. if err != nil {
  2079. return false, err
  2080. }
  2081. return needRestart, nil
  2082. }
  2083. func (s *InboundService) ResetAllClientTraffics(id int) error {
  2084. db := database.GetDB()
  2085. now := time.Now().Unix() * 1000
  2086. return db.Transaction(func(tx *gorm.DB) error {
  2087. whereText := "inbound_id "
  2088. if id == -1 {
  2089. whereText += " > ?"
  2090. } else {
  2091. whereText += " = ?"
  2092. }
  2093. // Reset client traffics
  2094. result := tx.Model(xray.ClientTraffic{}).
  2095. Where(whereText, id).
  2096. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  2097. if result.Error != nil {
  2098. return result.Error
  2099. }
  2100. // Update lastTrafficResetTime for the inbound(s)
  2101. inboundWhereText := "id "
  2102. if id == -1 {
  2103. inboundWhereText += " > ?"
  2104. } else {
  2105. inboundWhereText += " = ?"
  2106. }
  2107. result = tx.Model(model.Inbound{}).
  2108. Where(inboundWhereText, id).
  2109. Update("last_traffic_reset_time", now)
  2110. return result.Error
  2111. })
  2112. }
  2113. func (s *InboundService) ResetAllTraffics() error {
  2114. db := database.GetDB()
  2115. result := db.Model(model.Inbound{}).
  2116. Where("user_id > ?", 0).
  2117. Updates(map[string]any{"up": 0, "down": 0})
  2118. err := result.Error
  2119. return err
  2120. }
  2121. func (s *InboundService) ResetInboundTraffic(id int) error {
  2122. db := database.GetDB()
  2123. result := db.Model(model.Inbound{}).
  2124. Where("id = ?", id).
  2125. Updates(map[string]any{"up": 0, "down": 0})
  2126. return result.Error
  2127. }
  2128. func (s *InboundService) DelDepletedClients(id int) (err error) {
  2129. db := database.GetDB()
  2130. tx := db.Begin()
  2131. defer func() {
  2132. if err == nil {
  2133. tx.Commit()
  2134. } else {
  2135. tx.Rollback()
  2136. }
  2137. }()
  2138. whereText := "reset = 0 and inbound_id "
  2139. if id < 0 {
  2140. whereText += "> ?"
  2141. } else {
  2142. whereText += "= ?"
  2143. }
  2144. // Only consider truly depleted clients: expired OR traffic exhausted
  2145. now := time.Now().Unix() * 1000
  2146. depletedClients := []xray.ClientTraffic{}
  2147. err = db.Model(xray.ClientTraffic{}).
  2148. Where(whereText+" and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))", id, now).
  2149. Select("inbound_id, GROUP_CONCAT(email) as email").
  2150. Group("inbound_id").
  2151. Find(&depletedClients).Error
  2152. if err != nil {
  2153. return err
  2154. }
  2155. for _, depletedClient := range depletedClients {
  2156. emails := strings.Split(depletedClient.Email, ",")
  2157. oldInbound, err := s.GetInbound(depletedClient.InboundId)
  2158. if err != nil {
  2159. return err
  2160. }
  2161. var oldSettings map[string]any
  2162. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  2163. if err != nil {
  2164. return err
  2165. }
  2166. oldClients := oldSettings["clients"].([]any)
  2167. var newClients []any
  2168. for _, client := range oldClients {
  2169. deplete := false
  2170. c := client.(map[string]any)
  2171. for _, email := range emails {
  2172. if email == c["email"].(string) {
  2173. deplete = true
  2174. break
  2175. }
  2176. }
  2177. if !deplete {
  2178. newClients = append(newClients, client)
  2179. }
  2180. }
  2181. if len(newClients) > 0 {
  2182. oldSettings["clients"] = newClients
  2183. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  2184. if err != nil {
  2185. return err
  2186. }
  2187. oldInbound.Settings = string(newSettings)
  2188. err = tx.Save(oldInbound).Error
  2189. if err != nil {
  2190. return err
  2191. }
  2192. } else {
  2193. // Delete inbound if no client remains
  2194. s.DelInbound(depletedClient.InboundId)
  2195. }
  2196. }
  2197. // Delete stats only for truly depleted clients
  2198. err = tx.Where(whereText+" and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))", id, now).Delete(xray.ClientTraffic{}).Error
  2199. if err != nil {
  2200. return err
  2201. }
  2202. return nil
  2203. }
  2204. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  2205. db := database.GetDB()
  2206. var inbounds []*model.Inbound
  2207. // Retrieve inbounds where settings contain the given tgId
  2208. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  2209. if err != nil && err != gorm.ErrRecordNotFound {
  2210. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  2211. return nil, err
  2212. }
  2213. var emails []string
  2214. for _, inbound := range inbounds {
  2215. clients, err := s.GetClients(inbound)
  2216. if err != nil {
  2217. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  2218. continue
  2219. }
  2220. for _, client := range clients {
  2221. if client.TgID == tgId {
  2222. emails = append(emails, client.Email)
  2223. }
  2224. }
  2225. }
  2226. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  2227. // account owns thousands of clients across inbounds.
  2228. uniqEmails := uniqueNonEmptyStrings(emails)
  2229. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  2230. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  2231. var page []*xray.ClientTraffic
  2232. if err = db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  2233. if err == gorm.ErrRecordNotFound {
  2234. continue
  2235. }
  2236. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  2237. return nil, err
  2238. }
  2239. traffics = append(traffics, page...)
  2240. }
  2241. if len(traffics) == 0 {
  2242. logger.Warning("No ClientTraffic records found for emails:", emails)
  2243. return nil, nil
  2244. }
  2245. // Populate UUID and other client data for each traffic record
  2246. for i := range traffics {
  2247. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  2248. traffics[i].Enable = client.Enable
  2249. traffics[i].UUID = client.ID
  2250. traffics[i].SubId = client.SubID
  2251. }
  2252. }
  2253. return traffics, nil
  2254. }
  2255. // sqliteMaxVars is a safe ceiling for the number of bind parameters in a
  2256. // single SQL statement. SQLite's SQLITE_MAX_VARIABLE_NUMBER is 999 on builds
  2257. // before 3.32 and 32766 after; staying under 999 keeps queries portable
  2258. // across forks/old binaries and also bounds per-query memory on truly large
  2259. // installs (>32k clients) where even modern SQLite would refuse a single IN.
  2260. const sqliteMaxVars = 900
  2261. // uniqueNonEmptyStrings returns a deduplicated copy of in with empty strings
  2262. // removed, preserving the order of first occurrence.
  2263. func uniqueNonEmptyStrings(in []string) []string {
  2264. if len(in) == 0 {
  2265. return nil
  2266. }
  2267. seen := make(map[string]struct{}, len(in))
  2268. out := make([]string, 0, len(in))
  2269. for _, v := range in {
  2270. if v == "" {
  2271. continue
  2272. }
  2273. if _, ok := seen[v]; ok {
  2274. continue
  2275. }
  2276. seen[v] = struct{}{}
  2277. out = append(out, v)
  2278. }
  2279. return out
  2280. }
  2281. // uniqueInts returns a deduplicated copy of in, preserving order of first occurrence.
  2282. func uniqueInts(in []int) []int {
  2283. if len(in) == 0 {
  2284. return nil
  2285. }
  2286. seen := make(map[int]struct{}, len(in))
  2287. out := make([]int, 0, len(in))
  2288. for _, v := range in {
  2289. if _, ok := seen[v]; ok {
  2290. continue
  2291. }
  2292. seen[v] = struct{}{}
  2293. out = append(out, v)
  2294. }
  2295. return out
  2296. }
  2297. // chunkStrings splits s into consecutive sub-slices of at most size elements.
  2298. // Returns nil for an empty input or non-positive size.
  2299. func chunkStrings(s []string, size int) [][]string {
  2300. if size <= 0 || len(s) == 0 {
  2301. return nil
  2302. }
  2303. out := make([][]string, 0, (len(s)+size-1)/size)
  2304. for i := 0; i < len(s); i += size {
  2305. end := i + size
  2306. if end > len(s) {
  2307. end = len(s)
  2308. }
  2309. out = append(out, s[i:end])
  2310. }
  2311. return out
  2312. }
  2313. // chunkInts splits s into consecutive sub-slices of at most size elements.
  2314. // Returns nil for an empty input or non-positive size.
  2315. func chunkInts(s []int, size int) [][]int {
  2316. if size <= 0 || len(s) == 0 {
  2317. return nil
  2318. }
  2319. out := make([][]int, 0, (len(s)+size-1)/size)
  2320. for i := 0; i < len(s); i += size {
  2321. end := i + size
  2322. if end > len(s) {
  2323. end = len(s)
  2324. }
  2325. out = append(out, s[i:end])
  2326. }
  2327. return out
  2328. }
  2329. // GetActiveClientTraffics returns the absolute ClientTraffic rows for the given
  2330. // emails. Used by the WebSocket delta path to push per-client absolute
  2331. // counters without re-serializing the full inbound list. The query is chunked
  2332. // to stay under SQLite's bind-variable limit on very large active sets.
  2333. // Empty input returns (nil, nil).
  2334. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  2335. uniq := uniqueNonEmptyStrings(emails)
  2336. if len(uniq) == 0 {
  2337. return nil, nil
  2338. }
  2339. db := database.GetDB()
  2340. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  2341. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  2342. var page []*xray.ClientTraffic
  2343. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  2344. return nil, err
  2345. }
  2346. traffics = append(traffics, page...)
  2347. }
  2348. return traffics, nil
  2349. }
  2350. // InboundTrafficSummary is the minimal projection of an inbound's traffic
  2351. // counters used by the WebSocket delta path. Excludes Settings/StreamSettings
  2352. // blobs so the broadcast stays compact even with many inbounds.
  2353. type InboundTrafficSummary struct {
  2354. Id int `json:"id"`
  2355. Up int64 `json:"up"`
  2356. Down int64 `json:"down"`
  2357. Total int64 `json:"total"`
  2358. AllTime int64 `json:"allTime"`
  2359. Enable bool `json:"enable"`
  2360. }
  2361. // GetInboundsTrafficSummary returns inbound-level absolute traffic counters
  2362. // (no per-client expansion). Companion to GetActiveClientTraffics — together
  2363. // they replace the heavy "full inbound list" broadcast on each cron tick.
  2364. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  2365. db := database.GetDB()
  2366. var summaries []InboundTrafficSummary
  2367. if err := db.Model(&model.Inbound{}).
  2368. Select("id, up, down, total, all_time, enable").
  2369. Find(&summaries).Error; err != nil {
  2370. return nil, err
  2371. }
  2372. return summaries, nil
  2373. }
  2374. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  2375. // Prefer retrieving along with client to reflect actual enabled state from inbound settings
  2376. t, client, err := s.GetClientByEmail(email)
  2377. if err != nil {
  2378. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  2379. return nil, err
  2380. }
  2381. if t != nil && client != nil {
  2382. t.UUID = client.ID
  2383. t.SubId = client.SubID
  2384. return t, nil
  2385. }
  2386. return nil, nil
  2387. }
  2388. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  2389. db := database.GetDB()
  2390. // Keep all_time monotonic: it represents historical cumulative usage and
  2391. // must never be less than the currently-tracked up+down. Without this,
  2392. // the UI showed "Общий трафик" (allTime) below the live consumed value
  2393. // after admins manually edited a client's counters.
  2394. result := db.Model(xray.ClientTraffic{}).
  2395. Where("email = ?", email).
  2396. Updates(map[string]any{
  2397. "up": upload,
  2398. "down": download,
  2399. "all_time": gorm.Expr("CASE WHEN COALESCE(all_time, 0) < ? THEN ? ELSE all_time END", upload+download, upload+download),
  2400. })
  2401. err := result.Error
  2402. if err != nil {
  2403. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  2404. return err
  2405. }
  2406. return nil
  2407. }
  2408. func (s *InboundService) GetClientTrafficByID(id string) ([]xray.ClientTraffic, error) {
  2409. db := database.GetDB()
  2410. var traffics []xray.ClientTraffic
  2411. err := db.Model(xray.ClientTraffic{}).Where(`email IN(
  2412. SELECT JSON_EXTRACT(client.value, '$.email') as email
  2413. FROM inbounds,
  2414. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  2415. WHERE
  2416. JSON_EXTRACT(client.value, '$.id') in (?)
  2417. )`, id).Find(&traffics).Error
  2418. if err != nil {
  2419. logger.Debug(err)
  2420. return nil, err
  2421. }
  2422. // Reconcile enable flag with client settings per email to avoid stale DB value
  2423. for i := range traffics {
  2424. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  2425. traffics[i].Enable = client.Enable
  2426. traffics[i].UUID = client.ID
  2427. traffics[i].SubId = client.SubID
  2428. }
  2429. }
  2430. return traffics, err
  2431. }
  2432. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  2433. db := database.GetDB()
  2434. inbound := &model.Inbound{}
  2435. traffic = &xray.ClientTraffic{}
  2436. // Search for inbound settings that contain the query
  2437. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  2438. if err != nil {
  2439. if err == gorm.ErrRecordNotFound {
  2440. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  2441. return nil, err
  2442. }
  2443. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  2444. return nil, err
  2445. }
  2446. traffic.InboundId = inbound.Id
  2447. // Unmarshal settings to get clients
  2448. settings := map[string][]model.Client{}
  2449. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2450. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  2451. return nil, err
  2452. }
  2453. clients := settings["clients"]
  2454. for _, client := range clients {
  2455. if (client.ID == query || client.Password == query) && client.Email != "" {
  2456. traffic.Email = client.Email
  2457. break
  2458. }
  2459. }
  2460. if traffic.Email == "" {
  2461. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  2462. return nil, gorm.ErrRecordNotFound
  2463. }
  2464. // Retrieve ClientTraffic based on the found email
  2465. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  2466. if err != nil {
  2467. if err == gorm.ErrRecordNotFound {
  2468. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  2469. return nil, err
  2470. }
  2471. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  2472. return nil, err
  2473. }
  2474. return traffic, nil
  2475. }
  2476. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  2477. db := database.GetDB()
  2478. InboundClientIps := &model.InboundClientIps{}
  2479. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  2480. if err != nil {
  2481. return "", err
  2482. }
  2483. if InboundClientIps.Ips == "" {
  2484. return "", nil
  2485. }
  2486. // Try to parse as new format (with timestamps)
  2487. type IPWithTimestamp struct {
  2488. IP string `json:"ip"`
  2489. Timestamp int64 `json:"timestamp"`
  2490. }
  2491. var ipsWithTime []IPWithTimestamp
  2492. err = json.Unmarshal([]byte(InboundClientIps.Ips), &ipsWithTime)
  2493. // If successfully parsed as new format, return with timestamps
  2494. if err == nil && len(ipsWithTime) > 0 {
  2495. return InboundClientIps.Ips, nil
  2496. }
  2497. // Otherwise, assume it's old format (simple string array)
  2498. // Try to parse as simple array and convert to new format
  2499. var oldIps []string
  2500. err = json.Unmarshal([]byte(InboundClientIps.Ips), &oldIps)
  2501. if err == nil && len(oldIps) > 0 {
  2502. // Convert old format to new format with current timestamp
  2503. newIpsWithTime := make([]IPWithTimestamp, len(oldIps))
  2504. for i, ip := range oldIps {
  2505. newIpsWithTime[i] = IPWithTimestamp{
  2506. IP: ip,
  2507. Timestamp: time.Now().Unix(),
  2508. }
  2509. }
  2510. result, _ := json.Marshal(newIpsWithTime)
  2511. return string(result), nil
  2512. }
  2513. // Return as-is if parsing fails
  2514. return InboundClientIps.Ips, nil
  2515. }
  2516. func (s *InboundService) ClearClientIps(clientEmail string) error {
  2517. db := database.GetDB()
  2518. result := db.Model(model.InboundClientIps{}).
  2519. Where("client_email = ?", clientEmail).
  2520. Update("ips", "")
  2521. err := result.Error
  2522. if err != nil {
  2523. return err
  2524. }
  2525. return nil
  2526. }
  2527. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  2528. db := database.GetDB()
  2529. var inbounds []*model.Inbound
  2530. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  2531. if err != nil && err != gorm.ErrRecordNotFound {
  2532. return nil, err
  2533. }
  2534. return inbounds, nil
  2535. }
  2536. func (s *InboundService) MigrationRequirements() {
  2537. db := database.GetDB()
  2538. tx := db.Begin()
  2539. var err error
  2540. defer func() {
  2541. if err == nil {
  2542. tx.Commit()
  2543. if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
  2544. logger.Warningf("VACUUM failed: %v", dbErr)
  2545. }
  2546. } else {
  2547. tx.Rollback()
  2548. }
  2549. }()
  2550. // Calculate and backfill all_time from up+down for inbounds and clients
  2551. err = tx.Exec(`
  2552. UPDATE inbounds
  2553. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  2554. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  2555. `).Error
  2556. if err != nil {
  2557. return
  2558. }
  2559. err = tx.Exec(`
  2560. UPDATE client_traffics
  2561. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  2562. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  2563. `).Error
  2564. if err != nil {
  2565. return
  2566. }
  2567. // Fix inbounds based problems
  2568. var inbounds []*model.Inbound
  2569. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan"}).Find(&inbounds).Error
  2570. if err != nil && err != gorm.ErrRecordNotFound {
  2571. return
  2572. }
  2573. for inbound_index := range inbounds {
  2574. settings := map[string]any{}
  2575. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  2576. clients, ok := settings["clients"].([]any)
  2577. if ok {
  2578. // Fix Client configuration problems
  2579. var newClients []any
  2580. for client_index := range clients {
  2581. c := clients[client_index].(map[string]any)
  2582. // Add email='' if it is not exists
  2583. if _, ok := c["email"]; !ok {
  2584. c["email"] = ""
  2585. }
  2586. // Convert string tgId to int64
  2587. if _, ok := c["tgId"]; ok {
  2588. var tgId any = c["tgId"]
  2589. if tgIdStr, ok2 := tgId.(string); ok2 {
  2590. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  2591. if err == nil {
  2592. c["tgId"] = tgIdInt64
  2593. }
  2594. }
  2595. }
  2596. // Remove "flow": "xtls-rprx-direct"
  2597. if _, ok := c["flow"]; ok {
  2598. if c["flow"] == "xtls-rprx-direct" {
  2599. c["flow"] = ""
  2600. }
  2601. }
  2602. // Backfill created_at and updated_at
  2603. if _, ok := c["created_at"]; !ok {
  2604. c["created_at"] = time.Now().Unix() * 1000
  2605. }
  2606. c["updated_at"] = time.Now().Unix() * 1000
  2607. newClients = append(newClients, any(c))
  2608. }
  2609. settings["clients"] = newClients
  2610. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2611. if err != nil {
  2612. return
  2613. }
  2614. inbounds[inbound_index].Settings = string(modifiedSettings)
  2615. }
  2616. // Add client traffic row for all clients which has email
  2617. modelClients, err := s.GetClients(inbounds[inbound_index])
  2618. if err != nil {
  2619. return
  2620. }
  2621. for _, modelClient := range modelClients {
  2622. if len(modelClient.Email) > 0 {
  2623. var count int64
  2624. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  2625. if count == 0 {
  2626. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  2627. }
  2628. }
  2629. }
  2630. }
  2631. tx.Save(inbounds)
  2632. // Remove orphaned traffics
  2633. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  2634. // Migrate old MultiDomain to External Proxy
  2635. var externalProxy []struct {
  2636. Id int
  2637. Port int
  2638. StreamSettings []byte
  2639. }
  2640. err = tx.Raw(`select id, port, stream_settings
  2641. from inbounds
  2642. WHERE protocol in ('vmess','vless','trojan')
  2643. AND json_extract(stream_settings, '$.security') = 'tls'
  2644. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  2645. if err != nil || len(externalProxy) == 0 {
  2646. return
  2647. }
  2648. for _, ep := range externalProxy {
  2649. var reverses any
  2650. var stream map[string]any
  2651. json.Unmarshal(ep.StreamSettings, &stream)
  2652. if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
  2653. if settings, ok := tlsSettings["settings"].(map[string]any); ok {
  2654. if domains, ok := settings["domains"].([]any); ok {
  2655. for _, domain := range domains {
  2656. if domainMap, ok := domain.(map[string]any); ok {
  2657. domainMap["forceTls"] = "same"
  2658. domainMap["port"] = ep.Port
  2659. domainMap["dest"] = domainMap["domain"].(string)
  2660. delete(domainMap, "domain")
  2661. }
  2662. }
  2663. }
  2664. reverses = settings["domains"]
  2665. delete(settings, "domains")
  2666. }
  2667. }
  2668. stream["externalProxy"] = reverses
  2669. newStream, _ := json.MarshalIndent(stream, " ", " ")
  2670. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  2671. }
  2672. err = tx.Raw(`UPDATE inbounds
  2673. SET tag = REPLACE(tag, '0.0.0.0:', '')
  2674. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  2675. if err != nil {
  2676. return
  2677. }
  2678. }
  2679. func (s *InboundService) MigrateDB() {
  2680. s.MigrationRequirements()
  2681. s.MigrationRemoveOrphanedTraffics()
  2682. }
  2683. func (s *InboundService) GetOnlineClients() []string {
  2684. return p.GetOnlineClients()
  2685. }
  2686. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  2687. db := database.GetDB()
  2688. var rows []xray.ClientTraffic
  2689. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  2690. if err != nil && err != gorm.ErrRecordNotFound {
  2691. return nil, err
  2692. }
  2693. result := make(map[string]int64, len(rows))
  2694. for _, r := range rows {
  2695. result[r.Email] = r.LastOnline
  2696. }
  2697. return result, nil
  2698. }
  2699. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  2700. db := database.GetDB()
  2701. // Step 1: Get ClientTraffic records for emails in the input list.
  2702. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  2703. uniqEmails := uniqueNonEmptyStrings(emails)
  2704. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  2705. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  2706. var page []xray.ClientTraffic
  2707. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && err != gorm.ErrRecordNotFound {
  2708. return nil, nil, err
  2709. }
  2710. clients = append(clients, page...)
  2711. }
  2712. // Step 2: Sort clients by (Up + Down) descending
  2713. sort.Slice(clients, func(i, j int) bool {
  2714. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  2715. })
  2716. // Step 3: Extract sorted valid emails and track found ones
  2717. validEmails := make([]string, 0, len(clients))
  2718. found := make(map[string]bool)
  2719. for _, client := range clients {
  2720. validEmails = append(validEmails, client.Email)
  2721. found[client.Email] = true
  2722. }
  2723. // Step 4: Identify emails that were not found in the database
  2724. extraEmails := make([]string, 0)
  2725. for _, email := range emails {
  2726. if !found[email] {
  2727. extraEmails = append(extraEmails, email)
  2728. }
  2729. }
  2730. return validEmails, extraEmails, nil
  2731. }
  2732. func (s *InboundService) DelInboundClientByEmail(inboundId int, email string) (bool, error) {
  2733. oldInbound, err := s.GetInbound(inboundId)
  2734. if err != nil {
  2735. logger.Error("Load Old Data Error")
  2736. return false, err
  2737. }
  2738. var settings map[string]any
  2739. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  2740. return false, err
  2741. }
  2742. interfaceClients, ok := settings["clients"].([]any)
  2743. if !ok {
  2744. return false, common.NewError("invalid clients format in inbound settings")
  2745. }
  2746. var newClients []any
  2747. needApiDel := false
  2748. found := false
  2749. for _, client := range interfaceClients {
  2750. c, ok := client.(map[string]any)
  2751. if !ok {
  2752. continue
  2753. }
  2754. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  2755. // matched client, drop it
  2756. found = true
  2757. needApiDel, _ = c["enable"].(bool)
  2758. } else {
  2759. newClients = append(newClients, client)
  2760. }
  2761. }
  2762. if !found {
  2763. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  2764. }
  2765. if len(newClients) == 0 {
  2766. return false, common.NewError("no client remained in Inbound")
  2767. }
  2768. settings["clients"] = newClients
  2769. newSettings, err := json.MarshalIndent(settings, "", " ")
  2770. if err != nil {
  2771. return false, err
  2772. }
  2773. oldInbound.Settings = string(newSettings)
  2774. db := database.GetDB()
  2775. // remove IP bindings
  2776. if err := s.DelClientIPs(db, email); err != nil {
  2777. logger.Error("Error in delete client IPs")
  2778. return false, err
  2779. }
  2780. needRestart := false
  2781. // remove stats too
  2782. if len(email) > 0 {
  2783. traffic, err := s.GetClientTrafficByEmail(email)
  2784. if err != nil {
  2785. return false, err
  2786. }
  2787. if traffic != nil {
  2788. if err := s.DelClientStat(db, email); err != nil {
  2789. logger.Error("Delete stats Data Error")
  2790. return false, err
  2791. }
  2792. }
  2793. if needApiDel {
  2794. s.xrayApi.Init(p.GetAPIPort())
  2795. if err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email); err1 == nil {
  2796. logger.Debug("Client deleted by api:", email)
  2797. needRestart = false
  2798. } else {
  2799. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  2800. logger.Debug("User is already deleted. Nothing to do more...")
  2801. } else {
  2802. logger.Debug("Error in deleting client by api:", err1)
  2803. needRestart = true
  2804. }
  2805. }
  2806. s.xrayApi.Close()
  2807. }
  2808. }
  2809. return needRestart, db.Save(oldInbound).Error
  2810. }