inbound.go 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149
  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 inbounds []model.Inbound
  1596. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1597. if err != nil && err != gorm.ErrRecordNotFound {
  1598. return "[]", err
  1599. }
  1600. tagSet := make(map[string]struct{})
  1601. for _, inbound := range inbounds {
  1602. var settings map[string]any
  1603. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1604. continue
  1605. }
  1606. clients, ok := settings["clients"].([]any)
  1607. if !ok {
  1608. continue
  1609. }
  1610. for _, client := range clients {
  1611. clientMap, ok := client.(map[string]any)
  1612. if !ok {
  1613. continue
  1614. }
  1615. reverse, ok := clientMap["reverse"].(map[string]any)
  1616. if !ok {
  1617. continue
  1618. }
  1619. tag, _ := reverse["tag"].(string)
  1620. tag = strings.TrimSpace(tag)
  1621. if tag != "" {
  1622. tagSet[tag] = struct{}{}
  1623. }
  1624. }
  1625. }
  1626. rawTags := make([]string, 0, len(tagSet))
  1627. for tag := range tagSet {
  1628. rawTags = append(rawTags, tag)
  1629. }
  1630. sort.Strings(rawTags)
  1631. result, _ := json.Marshal(rawTags)
  1632. return string(result), nil
  1633. }
  1634. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  1635. db := database.GetDB()
  1636. db.Exec(`
  1637. DELETE FROM client_traffics
  1638. WHERE email NOT IN (
  1639. SELECT JSON_EXTRACT(client.value, '$.email')
  1640. FROM inbounds,
  1641. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1642. )
  1643. `)
  1644. }
  1645. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  1646. clientTraffic := xray.ClientTraffic{}
  1647. clientTraffic.InboundId = inboundId
  1648. clientTraffic.Email = client.Email
  1649. clientTraffic.Total = client.TotalGB
  1650. clientTraffic.ExpiryTime = client.ExpiryTime
  1651. clientTraffic.Enable = client.Enable
  1652. clientTraffic.Up = 0
  1653. clientTraffic.Down = 0
  1654. clientTraffic.Reset = client.Reset
  1655. result := tx.Create(&clientTraffic)
  1656. err := result.Error
  1657. return err
  1658. }
  1659. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  1660. result := tx.Model(xray.ClientTraffic{}).
  1661. Where("email = ?", email).
  1662. Updates(map[string]any{
  1663. "enable": client.Enable,
  1664. "email": client.Email,
  1665. "total": client.TotalGB,
  1666. "expiry_time": client.ExpiryTime,
  1667. "reset": client.Reset,
  1668. })
  1669. err := result.Error
  1670. return err
  1671. }
  1672. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  1673. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  1674. }
  1675. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  1676. return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error
  1677. }
  1678. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  1679. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  1680. }
  1681. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1682. db := database.GetDB()
  1683. var traffics []*xray.ClientTraffic
  1684. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  1685. if err != nil {
  1686. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  1687. return nil, nil, err
  1688. }
  1689. if len(traffics) > 0 {
  1690. inbound, err = s.GetInbound(traffics[0].InboundId)
  1691. return traffics[0], inbound, err
  1692. }
  1693. return nil, nil, nil
  1694. }
  1695. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1696. db := database.GetDB()
  1697. var traffics []*xray.ClientTraffic
  1698. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  1699. if err != nil {
  1700. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1701. return nil, nil, err
  1702. }
  1703. if len(traffics) > 0 {
  1704. inbound, err = s.GetInbound(traffics[0].InboundId)
  1705. return traffics[0], inbound, err
  1706. }
  1707. return nil, nil, nil
  1708. }
  1709. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  1710. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1711. if err != nil {
  1712. return nil, nil, err
  1713. }
  1714. if inbound == nil {
  1715. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  1716. }
  1717. clients, err := s.GetClients(inbound)
  1718. if err != nil {
  1719. return nil, nil, err
  1720. }
  1721. for _, client := range clients {
  1722. if client.Email == clientEmail {
  1723. return traffic, &client, nil
  1724. }
  1725. }
  1726. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  1727. }
  1728. func (s *InboundService) SetClientTelegramUserID(trafficId int, tgId int64) (bool, error) {
  1729. traffic, inbound, err := s.GetClientInboundByTrafficID(trafficId)
  1730. if err != nil {
  1731. return false, err
  1732. }
  1733. if inbound == nil {
  1734. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  1735. }
  1736. clientEmail := traffic.Email
  1737. oldClients, err := s.GetClients(inbound)
  1738. if err != nil {
  1739. return false, err
  1740. }
  1741. clientId := ""
  1742. for _, oldClient := range oldClients {
  1743. if oldClient.Email == clientEmail {
  1744. switch inbound.Protocol {
  1745. case "trojan":
  1746. clientId = oldClient.Password
  1747. case "shadowsocks":
  1748. clientId = oldClient.Email
  1749. default:
  1750. clientId = oldClient.ID
  1751. }
  1752. break
  1753. }
  1754. }
  1755. if len(clientId) == 0 {
  1756. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1757. }
  1758. var settings map[string]any
  1759. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1760. if err != nil {
  1761. return false, err
  1762. }
  1763. clients := settings["clients"].([]any)
  1764. var newClients []any
  1765. for client_index := range clients {
  1766. c := clients[client_index].(map[string]any)
  1767. if c["email"] == clientEmail {
  1768. c["tgId"] = tgId
  1769. c["updated_at"] = time.Now().Unix() * 1000
  1770. newClients = append(newClients, any(c))
  1771. }
  1772. }
  1773. settings["clients"] = newClients
  1774. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1775. if err != nil {
  1776. return false, err
  1777. }
  1778. inbound.Settings = string(modifiedSettings)
  1779. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1780. return needRestart, err
  1781. }
  1782. func (s *InboundService) checkIsEnabledByEmail(clientEmail string) (bool, error) {
  1783. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1784. if err != nil {
  1785. return false, err
  1786. }
  1787. if inbound == nil {
  1788. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1789. }
  1790. clients, err := s.GetClients(inbound)
  1791. if err != nil {
  1792. return false, err
  1793. }
  1794. isEnable := false
  1795. for _, client := range clients {
  1796. if client.Email == clientEmail {
  1797. isEnable = client.Enable
  1798. break
  1799. }
  1800. }
  1801. return isEnable, err
  1802. }
  1803. func (s *InboundService) ToggleClientEnableByEmail(clientEmail string) (bool, bool, error) {
  1804. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1805. if err != nil {
  1806. return false, false, err
  1807. }
  1808. if inbound == nil {
  1809. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1810. }
  1811. oldClients, err := s.GetClients(inbound)
  1812. if err != nil {
  1813. return false, false, err
  1814. }
  1815. clientId := ""
  1816. clientOldEnabled := false
  1817. for _, oldClient := range oldClients {
  1818. if oldClient.Email == clientEmail {
  1819. switch inbound.Protocol {
  1820. case "trojan":
  1821. clientId = oldClient.Password
  1822. case "shadowsocks":
  1823. clientId = oldClient.Email
  1824. default:
  1825. clientId = oldClient.ID
  1826. }
  1827. clientOldEnabled = oldClient.Enable
  1828. break
  1829. }
  1830. }
  1831. if len(clientId) == 0 {
  1832. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  1833. }
  1834. var settings map[string]any
  1835. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1836. if err != nil {
  1837. return false, false, err
  1838. }
  1839. clients := settings["clients"].([]any)
  1840. var newClients []any
  1841. for client_index := range clients {
  1842. c := clients[client_index].(map[string]any)
  1843. if c["email"] == clientEmail {
  1844. c["enable"] = !clientOldEnabled
  1845. c["updated_at"] = time.Now().Unix() * 1000
  1846. newClients = append(newClients, any(c))
  1847. }
  1848. }
  1849. settings["clients"] = newClients
  1850. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1851. if err != nil {
  1852. return false, false, err
  1853. }
  1854. inbound.Settings = string(modifiedSettings)
  1855. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1856. if err != nil {
  1857. return false, needRestart, err
  1858. }
  1859. return !clientOldEnabled, needRestart, nil
  1860. }
  1861. // SetClientEnableByEmail sets client enable state to desired value; returns (changed, needRestart, error)
  1862. func (s *InboundService) SetClientEnableByEmail(clientEmail string, enable bool) (bool, bool, error) {
  1863. current, err := s.checkIsEnabledByEmail(clientEmail)
  1864. if err != nil {
  1865. return false, false, err
  1866. }
  1867. if current == enable {
  1868. return false, false, nil
  1869. }
  1870. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(clientEmail)
  1871. if err != nil {
  1872. return false, needRestart, err
  1873. }
  1874. return newEnabled == enable, needRestart, nil
  1875. }
  1876. func (s *InboundService) ResetClientIpLimitByEmail(clientEmail string, count int) (bool, error) {
  1877. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1878. if err != nil {
  1879. return false, err
  1880. }
  1881. if inbound == nil {
  1882. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1883. }
  1884. oldClients, err := s.GetClients(inbound)
  1885. if err != nil {
  1886. return false, err
  1887. }
  1888. clientId := ""
  1889. for _, oldClient := range oldClients {
  1890. if oldClient.Email == clientEmail {
  1891. switch inbound.Protocol {
  1892. case "trojan":
  1893. clientId = oldClient.Password
  1894. case "shadowsocks":
  1895. clientId = oldClient.Email
  1896. default:
  1897. clientId = oldClient.ID
  1898. }
  1899. break
  1900. }
  1901. }
  1902. if len(clientId) == 0 {
  1903. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1904. }
  1905. var settings map[string]any
  1906. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1907. if err != nil {
  1908. return false, err
  1909. }
  1910. clients := settings["clients"].([]any)
  1911. var newClients []any
  1912. for client_index := range clients {
  1913. c := clients[client_index].(map[string]any)
  1914. if c["email"] == clientEmail {
  1915. c["limitIp"] = count
  1916. c["updated_at"] = time.Now().Unix() * 1000
  1917. newClients = append(newClients, any(c))
  1918. }
  1919. }
  1920. settings["clients"] = newClients
  1921. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1922. if err != nil {
  1923. return false, err
  1924. }
  1925. inbound.Settings = string(modifiedSettings)
  1926. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1927. return needRestart, err
  1928. }
  1929. func (s *InboundService) ResetClientExpiryTimeByEmail(clientEmail string, expiry_time int64) (bool, error) {
  1930. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1931. if err != nil {
  1932. return false, err
  1933. }
  1934. if inbound == nil {
  1935. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1936. }
  1937. oldClients, err := s.GetClients(inbound)
  1938. if err != nil {
  1939. return false, err
  1940. }
  1941. clientId := ""
  1942. for _, oldClient := range oldClients {
  1943. if oldClient.Email == clientEmail {
  1944. switch inbound.Protocol {
  1945. case "trojan":
  1946. clientId = oldClient.Password
  1947. case "shadowsocks":
  1948. clientId = oldClient.Email
  1949. default:
  1950. clientId = oldClient.ID
  1951. }
  1952. break
  1953. }
  1954. }
  1955. if len(clientId) == 0 {
  1956. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1957. }
  1958. var settings map[string]any
  1959. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1960. if err != nil {
  1961. return false, err
  1962. }
  1963. clients := settings["clients"].([]any)
  1964. var newClients []any
  1965. for client_index := range clients {
  1966. c := clients[client_index].(map[string]any)
  1967. if c["email"] == clientEmail {
  1968. c["expiryTime"] = expiry_time
  1969. c["updated_at"] = time.Now().Unix() * 1000
  1970. newClients = append(newClients, any(c))
  1971. }
  1972. }
  1973. settings["clients"] = newClients
  1974. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1975. if err != nil {
  1976. return false, err
  1977. }
  1978. inbound.Settings = string(modifiedSettings)
  1979. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1980. return needRestart, err
  1981. }
  1982. func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, totalGB int) (bool, error) {
  1983. if totalGB < 0 {
  1984. return false, common.NewError("totalGB must be >= 0")
  1985. }
  1986. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1987. if err != nil {
  1988. return false, err
  1989. }
  1990. if inbound == nil {
  1991. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1992. }
  1993. oldClients, err := s.GetClients(inbound)
  1994. if err != nil {
  1995. return false, err
  1996. }
  1997. clientId := ""
  1998. for _, oldClient := range oldClients {
  1999. if oldClient.Email == clientEmail {
  2000. switch inbound.Protocol {
  2001. case "trojan":
  2002. clientId = oldClient.Password
  2003. case "shadowsocks":
  2004. clientId = oldClient.Email
  2005. default:
  2006. clientId = oldClient.ID
  2007. }
  2008. break
  2009. }
  2010. }
  2011. if len(clientId) == 0 {
  2012. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2013. }
  2014. var settings map[string]any
  2015. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2016. if err != nil {
  2017. return false, err
  2018. }
  2019. clients := settings["clients"].([]any)
  2020. var newClients []any
  2021. for client_index := range clients {
  2022. c := clients[client_index].(map[string]any)
  2023. if c["email"] == clientEmail {
  2024. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  2025. c["updated_at"] = time.Now().Unix() * 1000
  2026. newClients = append(newClients, any(c))
  2027. }
  2028. }
  2029. settings["clients"] = newClients
  2030. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2031. if err != nil {
  2032. return false, err
  2033. }
  2034. inbound.Settings = string(modifiedSettings)
  2035. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2036. return needRestart, err
  2037. }
  2038. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  2039. db := database.GetDB()
  2040. // Reset traffic stats in ClientTraffic table
  2041. result := db.Model(xray.ClientTraffic{}).
  2042. Where("email = ?", clientEmail).
  2043. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  2044. err := result.Error
  2045. if err != nil {
  2046. return err
  2047. }
  2048. return nil
  2049. }
  2050. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, error) {
  2051. needRestart := false
  2052. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  2053. if err != nil {
  2054. return false, err
  2055. }
  2056. if !traffic.Enable {
  2057. inbound, err := s.GetInbound(id)
  2058. if err != nil {
  2059. return false, err
  2060. }
  2061. clients, err := s.GetClients(inbound)
  2062. if err != nil {
  2063. return false, err
  2064. }
  2065. for _, client := range clients {
  2066. if client.Email == clientEmail && client.Enable {
  2067. s.xrayApi.Init(p.GetAPIPort())
  2068. cipher := ""
  2069. if string(inbound.Protocol) == "shadowsocks" {
  2070. var oldSettings map[string]any
  2071. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  2072. if err != nil {
  2073. return false, err
  2074. }
  2075. cipher = oldSettings["method"].(string)
  2076. }
  2077. err1 := s.xrayApi.AddUser(string(inbound.Protocol), inbound.Tag, map[string]any{
  2078. "email": client.Email,
  2079. "id": client.ID,
  2080. "auth": client.Auth,
  2081. "security": client.Security,
  2082. "flow": client.Flow,
  2083. "password": client.Password,
  2084. "cipher": cipher,
  2085. })
  2086. if err1 == nil {
  2087. logger.Debug("Client enabled due to reset traffic:", clientEmail)
  2088. } else {
  2089. logger.Debug("Error in enabling client by api:", err1)
  2090. needRestart = true
  2091. }
  2092. s.xrayApi.Close()
  2093. break
  2094. }
  2095. }
  2096. }
  2097. traffic.Up = 0
  2098. traffic.Down = 0
  2099. traffic.Enable = true
  2100. db := database.GetDB()
  2101. err = db.Save(traffic).Error
  2102. if err != nil {
  2103. return false, err
  2104. }
  2105. return needRestart, nil
  2106. }
  2107. func (s *InboundService) ResetAllClientTraffics(id int) error {
  2108. db := database.GetDB()
  2109. now := time.Now().Unix() * 1000
  2110. return db.Transaction(func(tx *gorm.DB) error {
  2111. whereText := "inbound_id "
  2112. if id == -1 {
  2113. whereText += " > ?"
  2114. } else {
  2115. whereText += " = ?"
  2116. }
  2117. // Reset client traffics
  2118. result := tx.Model(xray.ClientTraffic{}).
  2119. Where(whereText, id).
  2120. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  2121. if result.Error != nil {
  2122. return result.Error
  2123. }
  2124. // Update lastTrafficResetTime for the inbound(s)
  2125. inboundWhereText := "id "
  2126. if id == -1 {
  2127. inboundWhereText += " > ?"
  2128. } else {
  2129. inboundWhereText += " = ?"
  2130. }
  2131. result = tx.Model(model.Inbound{}).
  2132. Where(inboundWhereText, id).
  2133. Update("last_traffic_reset_time", now)
  2134. return result.Error
  2135. })
  2136. }
  2137. func (s *InboundService) ResetAllTraffics() error {
  2138. db := database.GetDB()
  2139. result := db.Model(model.Inbound{}).
  2140. Where("user_id > ?", 0).
  2141. Updates(map[string]any{"up": 0, "down": 0})
  2142. err := result.Error
  2143. return err
  2144. }
  2145. func (s *InboundService) ResetInboundTraffic(id int) error {
  2146. db := database.GetDB()
  2147. result := db.Model(model.Inbound{}).
  2148. Where("id = ?", id).
  2149. Updates(map[string]any{"up": 0, "down": 0})
  2150. return result.Error
  2151. }
  2152. func (s *InboundService) DelDepletedClients(id int) (err error) {
  2153. db := database.GetDB()
  2154. tx := db.Begin()
  2155. defer func() {
  2156. if err == nil {
  2157. tx.Commit()
  2158. } else {
  2159. tx.Rollback()
  2160. }
  2161. }()
  2162. whereText := "reset = 0 and inbound_id "
  2163. if id < 0 {
  2164. whereText += "> ?"
  2165. } else {
  2166. whereText += "= ?"
  2167. }
  2168. // Only consider truly depleted clients: expired OR traffic exhausted
  2169. now := time.Now().Unix() * 1000
  2170. depletedClients := []xray.ClientTraffic{}
  2171. err = db.Model(xray.ClientTraffic{}).
  2172. Where(whereText+" and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))", id, now).
  2173. Select("inbound_id, GROUP_CONCAT(email) as email").
  2174. Group("inbound_id").
  2175. Find(&depletedClients).Error
  2176. if err != nil {
  2177. return err
  2178. }
  2179. for _, depletedClient := range depletedClients {
  2180. emails := strings.Split(depletedClient.Email, ",")
  2181. oldInbound, err := s.GetInbound(depletedClient.InboundId)
  2182. if err != nil {
  2183. return err
  2184. }
  2185. var oldSettings map[string]any
  2186. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  2187. if err != nil {
  2188. return err
  2189. }
  2190. oldClients := oldSettings["clients"].([]any)
  2191. var newClients []any
  2192. for _, client := range oldClients {
  2193. deplete := false
  2194. c := client.(map[string]any)
  2195. for _, email := range emails {
  2196. if email == c["email"].(string) {
  2197. deplete = true
  2198. break
  2199. }
  2200. }
  2201. if !deplete {
  2202. newClients = append(newClients, client)
  2203. }
  2204. }
  2205. if len(newClients) > 0 {
  2206. oldSettings["clients"] = newClients
  2207. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  2208. if err != nil {
  2209. return err
  2210. }
  2211. oldInbound.Settings = string(newSettings)
  2212. err = tx.Save(oldInbound).Error
  2213. if err != nil {
  2214. return err
  2215. }
  2216. } else {
  2217. // Delete inbound if no client remains
  2218. s.DelInbound(depletedClient.InboundId)
  2219. }
  2220. }
  2221. // Delete stats only for truly depleted clients
  2222. err = tx.Where(whereText+" and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))", id, now).Delete(xray.ClientTraffic{}).Error
  2223. if err != nil {
  2224. return err
  2225. }
  2226. return nil
  2227. }
  2228. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  2229. db := database.GetDB()
  2230. var inbounds []*model.Inbound
  2231. // Retrieve inbounds where settings contain the given tgId
  2232. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  2233. if err != nil && err != gorm.ErrRecordNotFound {
  2234. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  2235. return nil, err
  2236. }
  2237. var emails []string
  2238. for _, inbound := range inbounds {
  2239. clients, err := s.GetClients(inbound)
  2240. if err != nil {
  2241. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  2242. continue
  2243. }
  2244. for _, client := range clients {
  2245. if client.TgID == tgId {
  2246. emails = append(emails, client.Email)
  2247. }
  2248. }
  2249. }
  2250. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  2251. // account owns thousands of clients across inbounds.
  2252. uniqEmails := uniqueNonEmptyStrings(emails)
  2253. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  2254. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  2255. var page []*xray.ClientTraffic
  2256. if err = db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  2257. if err == gorm.ErrRecordNotFound {
  2258. continue
  2259. }
  2260. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  2261. return nil, err
  2262. }
  2263. traffics = append(traffics, page...)
  2264. }
  2265. if len(traffics) == 0 {
  2266. logger.Warning("No ClientTraffic records found for emails:", emails)
  2267. return nil, nil
  2268. }
  2269. // Populate UUID and other client data for each traffic record
  2270. for i := range traffics {
  2271. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  2272. traffics[i].Enable = client.Enable
  2273. traffics[i].UUID = client.ID
  2274. traffics[i].SubId = client.SubID
  2275. }
  2276. }
  2277. return traffics, nil
  2278. }
  2279. // sqliteMaxVars is a safe ceiling for the number of bind parameters in a
  2280. // single SQL statement. SQLite's SQLITE_MAX_VARIABLE_NUMBER is 999 on builds
  2281. // before 3.32 and 32766 after; staying under 999 keeps queries portable
  2282. // across forks/old binaries and also bounds per-query memory on truly large
  2283. // installs (>32k clients) where even modern SQLite would refuse a single IN.
  2284. const sqliteMaxVars = 900
  2285. // uniqueNonEmptyStrings returns a deduplicated copy of in with empty strings
  2286. // removed, preserving the order of first occurrence.
  2287. func uniqueNonEmptyStrings(in []string) []string {
  2288. if len(in) == 0 {
  2289. return nil
  2290. }
  2291. seen := make(map[string]struct{}, len(in))
  2292. out := make([]string, 0, len(in))
  2293. for _, v := range in {
  2294. if v == "" {
  2295. continue
  2296. }
  2297. if _, ok := seen[v]; ok {
  2298. continue
  2299. }
  2300. seen[v] = struct{}{}
  2301. out = append(out, v)
  2302. }
  2303. return out
  2304. }
  2305. // uniqueInts returns a deduplicated copy of in, preserving order of first occurrence.
  2306. func uniqueInts(in []int) []int {
  2307. if len(in) == 0 {
  2308. return nil
  2309. }
  2310. seen := make(map[int]struct{}, len(in))
  2311. out := make([]int, 0, len(in))
  2312. for _, v := range in {
  2313. if _, ok := seen[v]; ok {
  2314. continue
  2315. }
  2316. seen[v] = struct{}{}
  2317. out = append(out, v)
  2318. }
  2319. return out
  2320. }
  2321. // chunkStrings splits s into consecutive sub-slices of at most size elements.
  2322. // Returns nil for an empty input or non-positive size.
  2323. func chunkStrings(s []string, size int) [][]string {
  2324. if size <= 0 || len(s) == 0 {
  2325. return nil
  2326. }
  2327. out := make([][]string, 0, (len(s)+size-1)/size)
  2328. for i := 0; i < len(s); i += size {
  2329. end := i + size
  2330. if end > len(s) {
  2331. end = len(s)
  2332. }
  2333. out = append(out, s[i:end])
  2334. }
  2335. return out
  2336. }
  2337. // chunkInts splits s into consecutive sub-slices of at most size elements.
  2338. // Returns nil for an empty input or non-positive size.
  2339. func chunkInts(s []int, size int) [][]int {
  2340. if size <= 0 || len(s) == 0 {
  2341. return nil
  2342. }
  2343. out := make([][]int, 0, (len(s)+size-1)/size)
  2344. for i := 0; i < len(s); i += size {
  2345. end := i + size
  2346. if end > len(s) {
  2347. end = len(s)
  2348. }
  2349. out = append(out, s[i:end])
  2350. }
  2351. return out
  2352. }
  2353. // GetActiveClientTraffics returns the absolute ClientTraffic rows for the given
  2354. // emails. Used by the WebSocket delta path to push per-client absolute
  2355. // counters without re-serializing the full inbound list. The query is chunked
  2356. // to stay under SQLite's bind-variable limit on very large active sets.
  2357. // Empty input returns (nil, nil).
  2358. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  2359. uniq := uniqueNonEmptyStrings(emails)
  2360. if len(uniq) == 0 {
  2361. return nil, nil
  2362. }
  2363. db := database.GetDB()
  2364. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  2365. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  2366. var page []*xray.ClientTraffic
  2367. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  2368. return nil, err
  2369. }
  2370. traffics = append(traffics, page...)
  2371. }
  2372. return traffics, nil
  2373. }
  2374. // InboundTrafficSummary is the minimal projection of an inbound's traffic
  2375. // counters used by the WebSocket delta path. Excludes Settings/StreamSettings
  2376. // blobs so the broadcast stays compact even with many inbounds.
  2377. type InboundTrafficSummary struct {
  2378. Id int `json:"id"`
  2379. Up int64 `json:"up"`
  2380. Down int64 `json:"down"`
  2381. Total int64 `json:"total"`
  2382. AllTime int64 `json:"allTime"`
  2383. Enable bool `json:"enable"`
  2384. }
  2385. // GetInboundsTrafficSummary returns inbound-level absolute traffic counters
  2386. // (no per-client expansion). Companion to GetActiveClientTraffics — together
  2387. // they replace the heavy "full inbound list" broadcast on each cron tick.
  2388. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  2389. db := database.GetDB()
  2390. var summaries []InboundTrafficSummary
  2391. if err := db.Model(&model.Inbound{}).
  2392. Select("id, up, down, total, all_time, enable").
  2393. Find(&summaries).Error; err != nil {
  2394. return nil, err
  2395. }
  2396. return summaries, nil
  2397. }
  2398. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  2399. // Prefer retrieving along with client to reflect actual enabled state from inbound settings
  2400. t, client, err := s.GetClientByEmail(email)
  2401. if err != nil {
  2402. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  2403. return nil, err
  2404. }
  2405. if t != nil && client != nil {
  2406. t.UUID = client.ID
  2407. t.SubId = client.SubID
  2408. return t, nil
  2409. }
  2410. return nil, nil
  2411. }
  2412. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  2413. db := database.GetDB()
  2414. // Keep all_time monotonic: it represents historical cumulative usage and
  2415. // must never be less than the currently-tracked up+down. Without this,
  2416. // the UI showed "Общий трафик" (allTime) below the live consumed value
  2417. // after admins manually edited a client's counters.
  2418. result := db.Model(xray.ClientTraffic{}).
  2419. Where("email = ?", email).
  2420. Updates(map[string]any{
  2421. "up": upload,
  2422. "down": download,
  2423. "all_time": gorm.Expr("CASE WHEN COALESCE(all_time, 0) < ? THEN ? ELSE all_time END", upload+download, upload+download),
  2424. })
  2425. err := result.Error
  2426. if err != nil {
  2427. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  2428. return err
  2429. }
  2430. return nil
  2431. }
  2432. func (s *InboundService) GetClientTrafficByID(id string) ([]xray.ClientTraffic, error) {
  2433. db := database.GetDB()
  2434. var traffics []xray.ClientTraffic
  2435. err := db.Model(xray.ClientTraffic{}).Where(`email IN(
  2436. SELECT JSON_EXTRACT(client.value, '$.email') as email
  2437. FROM inbounds,
  2438. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  2439. WHERE
  2440. JSON_EXTRACT(client.value, '$.id') in (?)
  2441. )`, id).Find(&traffics).Error
  2442. if err != nil {
  2443. logger.Debug(err)
  2444. return nil, err
  2445. }
  2446. // Reconcile enable flag with client settings per email to avoid stale DB value
  2447. for i := range traffics {
  2448. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  2449. traffics[i].Enable = client.Enable
  2450. traffics[i].UUID = client.ID
  2451. traffics[i].SubId = client.SubID
  2452. }
  2453. }
  2454. return traffics, err
  2455. }
  2456. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  2457. db := database.GetDB()
  2458. inbound := &model.Inbound{}
  2459. traffic = &xray.ClientTraffic{}
  2460. // Search for inbound settings that contain the query
  2461. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  2462. if err != nil {
  2463. if err == gorm.ErrRecordNotFound {
  2464. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  2465. return nil, err
  2466. }
  2467. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  2468. return nil, err
  2469. }
  2470. traffic.InboundId = inbound.Id
  2471. // Unmarshal settings to get clients
  2472. settings := map[string][]model.Client{}
  2473. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2474. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  2475. return nil, err
  2476. }
  2477. clients := settings["clients"]
  2478. for _, client := range clients {
  2479. if (client.ID == query || client.Password == query) && client.Email != "" {
  2480. traffic.Email = client.Email
  2481. break
  2482. }
  2483. }
  2484. if traffic.Email == "" {
  2485. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  2486. return nil, gorm.ErrRecordNotFound
  2487. }
  2488. // Retrieve ClientTraffic based on the found email
  2489. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  2490. if err != nil {
  2491. if err == gorm.ErrRecordNotFound {
  2492. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  2493. return nil, err
  2494. }
  2495. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  2496. return nil, err
  2497. }
  2498. return traffic, nil
  2499. }
  2500. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  2501. db := database.GetDB()
  2502. InboundClientIps := &model.InboundClientIps{}
  2503. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  2504. if err != nil {
  2505. return "", err
  2506. }
  2507. if InboundClientIps.Ips == "" {
  2508. return "", nil
  2509. }
  2510. // Try to parse as new format (with timestamps)
  2511. type IPWithTimestamp struct {
  2512. IP string `json:"ip"`
  2513. Timestamp int64 `json:"timestamp"`
  2514. }
  2515. var ipsWithTime []IPWithTimestamp
  2516. err = json.Unmarshal([]byte(InboundClientIps.Ips), &ipsWithTime)
  2517. // If successfully parsed as new format, return with timestamps
  2518. if err == nil && len(ipsWithTime) > 0 {
  2519. return InboundClientIps.Ips, nil
  2520. }
  2521. // Otherwise, assume it's old format (simple string array)
  2522. // Try to parse as simple array and convert to new format
  2523. var oldIps []string
  2524. err = json.Unmarshal([]byte(InboundClientIps.Ips), &oldIps)
  2525. if err == nil && len(oldIps) > 0 {
  2526. // Convert old format to new format with current timestamp
  2527. newIpsWithTime := make([]IPWithTimestamp, len(oldIps))
  2528. for i, ip := range oldIps {
  2529. newIpsWithTime[i] = IPWithTimestamp{
  2530. IP: ip,
  2531. Timestamp: time.Now().Unix(),
  2532. }
  2533. }
  2534. result, _ := json.Marshal(newIpsWithTime)
  2535. return string(result), nil
  2536. }
  2537. // Return as-is if parsing fails
  2538. return InboundClientIps.Ips, nil
  2539. }
  2540. func (s *InboundService) ClearClientIps(clientEmail string) error {
  2541. db := database.GetDB()
  2542. result := db.Model(model.InboundClientIps{}).
  2543. Where("client_email = ?", clientEmail).
  2544. Update("ips", "")
  2545. err := result.Error
  2546. if err != nil {
  2547. return err
  2548. }
  2549. return nil
  2550. }
  2551. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  2552. db := database.GetDB()
  2553. var inbounds []*model.Inbound
  2554. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  2555. if err != nil && err != gorm.ErrRecordNotFound {
  2556. return nil, err
  2557. }
  2558. return inbounds, nil
  2559. }
  2560. func (s *InboundService) MigrationRequirements() {
  2561. db := database.GetDB()
  2562. tx := db.Begin()
  2563. var err error
  2564. defer func() {
  2565. if err == nil {
  2566. tx.Commit()
  2567. if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
  2568. logger.Warningf("VACUUM failed: %v", dbErr)
  2569. }
  2570. } else {
  2571. tx.Rollback()
  2572. }
  2573. }()
  2574. // Calculate and backfill all_time from up+down for inbounds and clients
  2575. err = tx.Exec(`
  2576. UPDATE inbounds
  2577. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  2578. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  2579. `).Error
  2580. if err != nil {
  2581. return
  2582. }
  2583. err = tx.Exec(`
  2584. UPDATE client_traffics
  2585. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  2586. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  2587. `).Error
  2588. if err != nil {
  2589. return
  2590. }
  2591. // Fix inbounds based problems
  2592. var inbounds []*model.Inbound
  2593. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan"}).Find(&inbounds).Error
  2594. if err != nil && err != gorm.ErrRecordNotFound {
  2595. return
  2596. }
  2597. for inbound_index := range inbounds {
  2598. settings := map[string]any{}
  2599. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  2600. clients, ok := settings["clients"].([]any)
  2601. if ok {
  2602. // Fix Client configuration problems
  2603. var newClients []any
  2604. for client_index := range clients {
  2605. c := clients[client_index].(map[string]any)
  2606. // Add email='' if it is not exists
  2607. if _, ok := c["email"]; !ok {
  2608. c["email"] = ""
  2609. }
  2610. // Convert string tgId to int64
  2611. if _, ok := c["tgId"]; ok {
  2612. var tgId any = c["tgId"]
  2613. if tgIdStr, ok2 := tgId.(string); ok2 {
  2614. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  2615. if err == nil {
  2616. c["tgId"] = tgIdInt64
  2617. }
  2618. }
  2619. }
  2620. // Remove "flow": "xtls-rprx-direct"
  2621. if _, ok := c["flow"]; ok {
  2622. if c["flow"] == "xtls-rprx-direct" {
  2623. c["flow"] = ""
  2624. }
  2625. }
  2626. // Backfill created_at and updated_at
  2627. if _, ok := c["created_at"]; !ok {
  2628. c["created_at"] = time.Now().Unix() * 1000
  2629. }
  2630. c["updated_at"] = time.Now().Unix() * 1000
  2631. newClients = append(newClients, any(c))
  2632. }
  2633. settings["clients"] = newClients
  2634. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2635. if err != nil {
  2636. return
  2637. }
  2638. inbounds[inbound_index].Settings = string(modifiedSettings)
  2639. }
  2640. // Add client traffic row for all clients which has email
  2641. modelClients, err := s.GetClients(inbounds[inbound_index])
  2642. if err != nil {
  2643. return
  2644. }
  2645. for _, modelClient := range modelClients {
  2646. if len(modelClient.Email) > 0 {
  2647. var count int64
  2648. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  2649. if count == 0 {
  2650. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  2651. }
  2652. }
  2653. }
  2654. }
  2655. tx.Save(inbounds)
  2656. // Remove orphaned traffics
  2657. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  2658. // Migrate old MultiDomain to External Proxy
  2659. var externalProxy []struct {
  2660. Id int
  2661. Port int
  2662. StreamSettings []byte
  2663. }
  2664. err = tx.Raw(`select id, port, stream_settings
  2665. from inbounds
  2666. WHERE protocol in ('vmess','vless','trojan')
  2667. AND json_extract(stream_settings, '$.security') = 'tls'
  2668. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  2669. if err != nil || len(externalProxy) == 0 {
  2670. return
  2671. }
  2672. for _, ep := range externalProxy {
  2673. var reverses any
  2674. var stream map[string]any
  2675. json.Unmarshal(ep.StreamSettings, &stream)
  2676. if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
  2677. if settings, ok := tlsSettings["settings"].(map[string]any); ok {
  2678. if domains, ok := settings["domains"].([]any); ok {
  2679. for _, domain := range domains {
  2680. if domainMap, ok := domain.(map[string]any); ok {
  2681. domainMap["forceTls"] = "same"
  2682. domainMap["port"] = ep.Port
  2683. domainMap["dest"] = domainMap["domain"].(string)
  2684. delete(domainMap, "domain")
  2685. }
  2686. }
  2687. }
  2688. reverses = settings["domains"]
  2689. delete(settings, "domains")
  2690. }
  2691. }
  2692. stream["externalProxy"] = reverses
  2693. newStream, _ := json.MarshalIndent(stream, " ", " ")
  2694. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  2695. }
  2696. err = tx.Raw(`UPDATE inbounds
  2697. SET tag = REPLACE(tag, '0.0.0.0:', '')
  2698. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  2699. if err != nil {
  2700. return
  2701. }
  2702. }
  2703. func (s *InboundService) MigrateDB() {
  2704. s.MigrationRequirements()
  2705. s.MigrationRemoveOrphanedTraffics()
  2706. }
  2707. func (s *InboundService) GetOnlineClients() []string {
  2708. return p.GetOnlineClients()
  2709. }
  2710. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  2711. db := database.GetDB()
  2712. var rows []xray.ClientTraffic
  2713. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  2714. if err != nil && err != gorm.ErrRecordNotFound {
  2715. return nil, err
  2716. }
  2717. result := make(map[string]int64, len(rows))
  2718. for _, r := range rows {
  2719. result[r.Email] = r.LastOnline
  2720. }
  2721. return result, nil
  2722. }
  2723. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  2724. db := database.GetDB()
  2725. // Step 1: Get ClientTraffic records for emails in the input list.
  2726. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  2727. uniqEmails := uniqueNonEmptyStrings(emails)
  2728. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  2729. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  2730. var page []xray.ClientTraffic
  2731. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && err != gorm.ErrRecordNotFound {
  2732. return nil, nil, err
  2733. }
  2734. clients = append(clients, page...)
  2735. }
  2736. // Step 2: Sort clients by (Up + Down) descending
  2737. sort.Slice(clients, func(i, j int) bool {
  2738. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  2739. })
  2740. // Step 3: Extract sorted valid emails and track found ones
  2741. validEmails := make([]string, 0, len(clients))
  2742. found := make(map[string]bool)
  2743. for _, client := range clients {
  2744. validEmails = append(validEmails, client.Email)
  2745. found[client.Email] = true
  2746. }
  2747. // Step 4: Identify emails that were not found in the database
  2748. extraEmails := make([]string, 0)
  2749. for _, email := range emails {
  2750. if !found[email] {
  2751. extraEmails = append(extraEmails, email)
  2752. }
  2753. }
  2754. return validEmails, extraEmails, nil
  2755. }
  2756. func (s *InboundService) DelInboundClientByEmail(inboundId int, email string) (bool, error) {
  2757. oldInbound, err := s.GetInbound(inboundId)
  2758. if err != nil {
  2759. logger.Error("Load Old Data Error")
  2760. return false, err
  2761. }
  2762. var settings map[string]any
  2763. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  2764. return false, err
  2765. }
  2766. interfaceClients, ok := settings["clients"].([]any)
  2767. if !ok {
  2768. return false, common.NewError("invalid clients format in inbound settings")
  2769. }
  2770. var newClients []any
  2771. needApiDel := false
  2772. found := false
  2773. for _, client := range interfaceClients {
  2774. c, ok := client.(map[string]any)
  2775. if !ok {
  2776. continue
  2777. }
  2778. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  2779. // matched client, drop it
  2780. found = true
  2781. needApiDel, _ = c["enable"].(bool)
  2782. } else {
  2783. newClients = append(newClients, client)
  2784. }
  2785. }
  2786. if !found {
  2787. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  2788. }
  2789. if len(newClients) == 0 {
  2790. return false, common.NewError("no client remained in Inbound")
  2791. }
  2792. settings["clients"] = newClients
  2793. newSettings, err := json.MarshalIndent(settings, "", " ")
  2794. if err != nil {
  2795. return false, err
  2796. }
  2797. oldInbound.Settings = string(newSettings)
  2798. db := database.GetDB()
  2799. // remove IP bindings
  2800. if err := s.DelClientIPs(db, email); err != nil {
  2801. logger.Error("Error in delete client IPs")
  2802. return false, err
  2803. }
  2804. needRestart := false
  2805. // remove stats too
  2806. if len(email) > 0 {
  2807. traffic, err := s.GetClientTrafficByEmail(email)
  2808. if err != nil {
  2809. return false, err
  2810. }
  2811. if traffic != nil {
  2812. if err := s.DelClientStat(db, email); err != nil {
  2813. logger.Error("Delete stats Data Error")
  2814. return false, err
  2815. }
  2816. }
  2817. if needApiDel {
  2818. s.xrayApi.Init(p.GetAPIPort())
  2819. if err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email); err1 == nil {
  2820. logger.Debug("Client deleted by api:", email)
  2821. needRestart = false
  2822. } else {
  2823. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  2824. logger.Debug("User is already deleted. Nothing to do more...")
  2825. } else {
  2826. logger.Debug("Error in deleting client by api:", err1)
  2827. needRestart = true
  2828. }
  2829. }
  2830. s.xrayApi.Close()
  2831. }
  2832. }
  2833. return needRestart, db.Save(oldInbound).Error
  2834. }