inbound.go 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875
  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. "context"
  6. "encoding/json"
  7. "fmt"
  8. "sort"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/google/uuid"
  13. "github.com/mhsanaei/3x-ui/v3/database"
  14. "github.com/mhsanaei/3x-ui/v3/database/model"
  15. "github.com/mhsanaei/3x-ui/v3/logger"
  16. "github.com/mhsanaei/3x-ui/v3/util/common"
  17. "github.com/mhsanaei/3x-ui/v3/web/runtime"
  18. "github.com/mhsanaei/3x-ui/v3/xray"
  19. "gorm.io/gorm"
  20. "gorm.io/gorm/clause"
  21. )
  22. type InboundService struct {
  23. xrayApi xray.XrayAPI
  24. }
  25. func (s *InboundService) runtimeFor(ib *model.Inbound) (runtime.Runtime, error) {
  26. mgr := runtime.GetManager()
  27. if mgr == nil {
  28. return nil, fmt.Errorf("runtime manager not initialised")
  29. }
  30. return mgr.RuntimeFor(ib.NodeID)
  31. }
  32. type CopyClientsResult struct {
  33. Added []string `json:"added"`
  34. Skipped []string `json:"skipped"`
  35. Errors []string `json:"errors"`
  36. }
  37. // enrichClientStats parses each inbound's clients once, fills in the
  38. // UUID/SubId fields on the preloaded ClientStats, and tops up rows owned by
  39. // a sibling inbound (shared-email mode — the row is keyed on email so it
  40. // only preloads on its owning inbound).
  41. func (s *InboundService) enrichClientStats(db *gorm.DB, inbounds []*model.Inbound) {
  42. if len(inbounds) == 0 {
  43. return
  44. }
  45. clientsByInbound := make([][]model.Client, len(inbounds))
  46. seenByInbound := make([]map[string]struct{}, len(inbounds))
  47. missing := make(map[string]struct{})
  48. for i, inbound := range inbounds {
  49. clients, _ := s.GetClients(inbound)
  50. clientsByInbound[i] = clients
  51. seen := make(map[string]struct{}, len(inbound.ClientStats))
  52. for _, st := range inbound.ClientStats {
  53. if st.Email != "" {
  54. seen[strings.ToLower(st.Email)] = struct{}{}
  55. }
  56. }
  57. seenByInbound[i] = seen
  58. for _, c := range clients {
  59. if c.Email == "" {
  60. continue
  61. }
  62. if _, ok := seen[strings.ToLower(c.Email)]; !ok {
  63. missing[c.Email] = struct{}{}
  64. }
  65. }
  66. }
  67. if len(missing) > 0 {
  68. emails := make([]string, 0, len(missing))
  69. for e := range missing {
  70. emails = append(emails, e)
  71. }
  72. var extra []xray.ClientTraffic
  73. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", emails).Find(&extra).Error; err != nil {
  74. logger.Warning("enrichClientStats:", err)
  75. } else {
  76. byEmail := make(map[string]xray.ClientTraffic, len(extra))
  77. for _, st := range extra {
  78. byEmail[strings.ToLower(st.Email)] = st
  79. }
  80. for i, inbound := range inbounds {
  81. for _, c := range clientsByInbound[i] {
  82. if c.Email == "" {
  83. continue
  84. }
  85. key := strings.ToLower(c.Email)
  86. if _, ok := seenByInbound[i][key]; ok {
  87. continue
  88. }
  89. if st, ok := byEmail[key]; ok {
  90. inbound.ClientStats = append(inbound.ClientStats, st)
  91. seenByInbound[i][key] = struct{}{}
  92. }
  93. }
  94. }
  95. }
  96. }
  97. for i, inbound := range inbounds {
  98. clients := clientsByInbound[i]
  99. if len(clients) == 0 || len(inbound.ClientStats) == 0 {
  100. continue
  101. }
  102. cMap := make(map[string]model.Client, len(clients))
  103. for _, c := range clients {
  104. cMap[strings.ToLower(c.Email)] = c
  105. }
  106. for j := range inbound.ClientStats {
  107. email := strings.ToLower(inbound.ClientStats[j].Email)
  108. if c, ok := cMap[email]; ok {
  109. inbound.ClientStats[j].UUID = c.ID
  110. inbound.ClientStats[j].SubId = c.SubID
  111. }
  112. }
  113. }
  114. }
  115. // GetInbounds retrieves all inbounds for a specific user with client stats.
  116. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  117. db := database.GetDB()
  118. var inbounds []*model.Inbound
  119. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Find(&inbounds).Error
  120. if err != nil && err != gorm.ErrRecordNotFound {
  121. return nil, err
  122. }
  123. s.enrichClientStats(db, inbounds)
  124. return inbounds, nil
  125. }
  126. // GetAllInbounds retrieves all inbounds with client stats.
  127. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  128. db := database.GetDB()
  129. var inbounds []*model.Inbound
  130. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  131. if err != nil && err != gorm.ErrRecordNotFound {
  132. return nil, err
  133. }
  134. s.enrichClientStats(db, inbounds)
  135. return inbounds, nil
  136. }
  137. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  138. db := database.GetDB()
  139. var inbounds []*model.Inbound
  140. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  141. if err != nil && err != gorm.ErrRecordNotFound {
  142. return nil, err
  143. }
  144. return inbounds, nil
  145. }
  146. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  147. settings := map[string][]model.Client{}
  148. json.Unmarshal([]byte(inbound.Settings), &settings)
  149. if settings == nil {
  150. return nil, fmt.Errorf("setting is null")
  151. }
  152. clients := settings["clients"]
  153. if clients == nil {
  154. return nil, nil
  155. }
  156. return clients, nil
  157. }
  158. func (s *InboundService) getAllEmails() ([]string, error) {
  159. db := database.GetDB()
  160. var emails []string
  161. err := db.Raw(`
  162. SELECT DISTINCT JSON_EXTRACT(client.value, '$.email')
  163. FROM inbounds,
  164. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  165. `).Scan(&emails).Error
  166. if err != nil {
  167. return nil, err
  168. }
  169. return emails, nil
  170. }
  171. // getAllEmailSubIDs returns email→subId. An email seen with two different
  172. // non-empty subIds is locked (mapped to "") so neither identity can claim it.
  173. func (s *InboundService) getAllEmailSubIDs() (map[string]string, error) {
  174. db := database.GetDB()
  175. var rows []struct {
  176. Email string
  177. SubID string
  178. }
  179. err := db.Raw(`
  180. SELECT JSON_EXTRACT(client.value, '$.email') AS email,
  181. JSON_EXTRACT(client.value, '$.subId') AS sub_id
  182. FROM inbounds,
  183. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  184. `).Scan(&rows).Error
  185. if err != nil {
  186. return nil, err
  187. }
  188. result := make(map[string]string, len(rows))
  189. for _, r := range rows {
  190. email := strings.ToLower(strings.Trim(r.Email, "\""))
  191. if email == "" {
  192. continue
  193. }
  194. subID := strings.Trim(r.SubID, "\"")
  195. if existing, ok := result[email]; ok {
  196. if existing != subID {
  197. result[email] = ""
  198. }
  199. continue
  200. }
  201. result[email] = subID
  202. }
  203. return result, nil
  204. }
  205. func lowerAll(in []string) []string {
  206. out := make([]string, len(in))
  207. for i, s := range in {
  208. out[i] = strings.ToLower(s)
  209. }
  210. return out
  211. }
  212. // emailUsedByOtherInbounds reports whether email lives in any inbound other
  213. // than exceptInboundId. Empty email returns false.
  214. func (s *InboundService) emailUsedByOtherInbounds(email string, exceptInboundId int) (bool, error) {
  215. if email == "" {
  216. return false, nil
  217. }
  218. db := database.GetDB()
  219. var count int64
  220. err := db.Raw(`
  221. SELECT COUNT(*)
  222. FROM inbounds,
  223. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  224. WHERE inbounds.id != ?
  225. AND LOWER(JSON_EXTRACT(client.value, '$.email')) = LOWER(?)
  226. `, exceptInboundId, email).Scan(&count).Error
  227. if err != nil {
  228. return false, err
  229. }
  230. return count > 0, nil
  231. }
  232. // checkEmailsExistForClients validates a batch of incoming clients. An email
  233. // collides only when the existing holder has a different (or empty) subId —
  234. // matching non-empty subIds let multiple inbounds share one identity.
  235. func (s *InboundService) checkEmailsExistForClients(clients []model.Client) (string, error) {
  236. emailSubIDs, err := s.getAllEmailSubIDs()
  237. if err != nil {
  238. return "", err
  239. }
  240. seen := make(map[string]string, len(clients))
  241. for _, client := range clients {
  242. if client.Email == "" {
  243. continue
  244. }
  245. key := strings.ToLower(client.Email)
  246. // Within the same payload, the same email must carry the same subId;
  247. // otherwise we would silently merge two distinct identities.
  248. if prev, ok := seen[key]; ok {
  249. if prev != client.SubID || client.SubID == "" {
  250. return client.Email, nil
  251. }
  252. continue
  253. }
  254. seen[key] = client.SubID
  255. if existingSub, ok := emailSubIDs[key]; ok {
  256. if client.SubID == "" || existingSub == "" || existingSub != client.SubID {
  257. return client.Email, nil
  258. }
  259. }
  260. }
  261. return "", nil
  262. }
  263. // AddInbound creates a new inbound configuration.
  264. // It validates port uniqueness, client email uniqueness, and required fields,
  265. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  266. // Returns the created inbound, whether Xray needs restart, and any error.
  267. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  268. exist, err := s.checkPortConflict(inbound, 0)
  269. if err != nil {
  270. return inbound, false, err
  271. }
  272. if exist {
  273. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  274. }
  275. // pick a tag that won't collide with an existing row. for the common
  276. // case this is the same "inbound-<port>" string the controller already
  277. // set; only when this port already has another inbound on a different
  278. // transport (now possible after the transport-aware port check) does
  279. // this disambiguate with a -tcp/-udp suffix. see #4103.
  280. inbound.Tag, err = s.generateInboundTag(inbound, 0)
  281. if err != nil {
  282. return inbound, false, err
  283. }
  284. clients, err := s.GetClients(inbound)
  285. if err != nil {
  286. return inbound, false, err
  287. }
  288. existEmail, err := s.checkEmailsExistForClients(clients)
  289. if err != nil {
  290. return inbound, false, err
  291. }
  292. if existEmail != "" {
  293. return inbound, false, common.NewError("Duplicate email:", existEmail)
  294. }
  295. // Ensure created_at and updated_at on clients in settings
  296. if len(clients) > 0 {
  297. var settings map[string]any
  298. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  299. now := time.Now().Unix() * 1000
  300. updatedClients := make([]model.Client, 0, len(clients))
  301. for _, c := range clients {
  302. if c.CreatedAt == 0 {
  303. c.CreatedAt = now
  304. }
  305. c.UpdatedAt = now
  306. updatedClients = append(updatedClients, c)
  307. }
  308. settings["clients"] = updatedClients
  309. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  310. inbound.Settings = string(bs)
  311. } else {
  312. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  313. }
  314. } else if err2 != nil {
  315. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  316. }
  317. }
  318. // Secure client ID
  319. for _, client := range clients {
  320. switch inbound.Protocol {
  321. case "trojan":
  322. if client.Password == "" {
  323. return inbound, false, common.NewError("empty client ID")
  324. }
  325. case "shadowsocks":
  326. if client.Email == "" {
  327. return inbound, false, common.NewError("empty client ID")
  328. }
  329. case "hysteria", "hysteria2":
  330. if client.Auth == "" {
  331. return inbound, false, common.NewError("empty client ID")
  332. }
  333. default:
  334. if client.ID == "" {
  335. return inbound, false, common.NewError("empty client ID")
  336. }
  337. }
  338. }
  339. db := database.GetDB()
  340. tx := db.Begin()
  341. defer func() {
  342. if err == nil {
  343. tx.Commit()
  344. } else {
  345. tx.Rollback()
  346. }
  347. }()
  348. err = tx.Save(inbound).Error
  349. if err == nil {
  350. if len(inbound.ClientStats) == 0 {
  351. for _, client := range clients {
  352. s.AddClientStat(tx, inbound.Id, &client)
  353. }
  354. }
  355. } else {
  356. return inbound, false, err
  357. }
  358. needRestart := false
  359. if inbound.Enable {
  360. rt, rterr := s.runtimeFor(inbound)
  361. if rterr != nil {
  362. err = rterr
  363. return inbound, false, err
  364. }
  365. if err1 := rt.AddInbound(context.Background(), inbound); err1 == nil {
  366. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  367. } else {
  368. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  369. if inbound.NodeID != nil {
  370. err = err1
  371. return inbound, false, err
  372. }
  373. needRestart = true
  374. }
  375. }
  376. return inbound, needRestart, err
  377. }
  378. func (s *InboundService) DelInbound(id int) (bool, error) {
  379. db := database.GetDB()
  380. needRestart := false
  381. var ib model.Inbound
  382. loadErr := db.Model(model.Inbound{}).Where("id = ? and enable = ?", id, true).First(&ib).Error
  383. if loadErr == nil {
  384. rt, rterr := s.runtimeFor(&ib)
  385. if rterr != nil {
  386. logger.Warning("DelInbound: runtime lookup failed, deleting central row anyway:", rterr)
  387. if ib.NodeID == nil {
  388. needRestart = true
  389. }
  390. } else if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  391. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  392. } else {
  393. logger.Warning("DelInbound on", rt.Name(), "failed, deleting central row anyway:", err1)
  394. if ib.NodeID == nil {
  395. needRestart = true
  396. }
  397. }
  398. } else {
  399. logger.Debug("No enabled inbound found to remove by api, id:", id)
  400. }
  401. // Delete client traffics of inbounds
  402. err := db.Where("inbound_id = ?", id).Delete(xray.ClientTraffic{}).Error
  403. if err != nil {
  404. return false, err
  405. }
  406. inbound, err := s.GetInbound(id)
  407. if err != nil {
  408. return false, err
  409. }
  410. clients, err := s.GetClients(inbound)
  411. if err != nil {
  412. return false, err
  413. }
  414. // Bulk-delete client IPs for every email in this inbound. The previous
  415. // per-client loop fired one DELETE per row — at 7k+ clients that meant
  416. // thousands of synchronous SQL roundtrips and a multi-second freeze.
  417. // Chunked to stay under SQLite's bind-variable limit on huge inbounds.
  418. if len(clients) > 0 {
  419. emails := make([]string, 0, len(clients))
  420. for i := range clients {
  421. if clients[i].Email != "" {
  422. emails = append(emails, clients[i].Email)
  423. }
  424. }
  425. for _, batch := range chunkStrings(uniqueNonEmptyStrings(emails), sqliteMaxVars) {
  426. if err := db.Where("client_email IN ?", batch).
  427. Delete(model.InboundClientIps{}).Error; err != nil {
  428. return false, err
  429. }
  430. }
  431. }
  432. return needRestart, db.Delete(model.Inbound{}, id).Error
  433. }
  434. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  435. db := database.GetDB()
  436. inbound := &model.Inbound{}
  437. err := db.Model(model.Inbound{}).First(inbound, id).Error
  438. if err != nil {
  439. return nil, err
  440. }
  441. return inbound, nil
  442. }
  443. // SetInboundEnable toggles only the enable flag of an inbound, without
  444. // rewriting the (potentially multi-MB) settings JSON. Used by the UI's
  445. // per-row enable switch — for inbounds with thousands of clients the full
  446. // UpdateInbound path is an order of magnitude too slow for an interactive
  447. // toggle (parses + reserialises every client, runs O(N) traffic diff).
  448. //
  449. // Returns (needRestart, error). needRestart is true when the xray runtime
  450. // could not be re-synced from the cached config and a full restart is
  451. // required to pick up the change.
  452. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  453. inbound, err := s.GetInbound(id)
  454. if err != nil {
  455. return false, err
  456. }
  457. if inbound.Enable == enable {
  458. return false, nil
  459. }
  460. db := database.GetDB()
  461. if err := db.Model(model.Inbound{}).Where("id = ?", id).
  462. Update("enable", enable).Error; err != nil {
  463. return false, err
  464. }
  465. inbound.Enable = enable
  466. needRestart := false
  467. rt, rterr := s.runtimeFor(inbound)
  468. if rterr != nil {
  469. if inbound.NodeID != nil {
  470. return false, rterr
  471. }
  472. return true, nil
  473. }
  474. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  475. !strings.Contains(err.Error(), "not found") {
  476. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  477. needRestart = true
  478. }
  479. if !enable {
  480. return needRestart, nil
  481. }
  482. addTarget := inbound
  483. if inbound.NodeID == nil {
  484. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  485. if err != nil {
  486. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  487. return true, nil
  488. }
  489. addTarget = runtimeInbound
  490. }
  491. if err := rt.AddInbound(context.Background(), addTarget); err != nil {
  492. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  493. if inbound.NodeID != nil {
  494. return false, err
  495. }
  496. needRestart = true
  497. }
  498. return needRestart, nil
  499. }
  500. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  501. exist, err := s.checkPortConflict(inbound, inbound.Id)
  502. if err != nil {
  503. return inbound, false, err
  504. }
  505. if exist {
  506. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  507. }
  508. oldInbound, err := s.GetInbound(inbound.Id)
  509. if err != nil {
  510. return inbound, false, err
  511. }
  512. tag := oldInbound.Tag
  513. db := database.GetDB()
  514. tx := db.Begin()
  515. defer func() {
  516. if err != nil {
  517. tx.Rollback()
  518. } else {
  519. tx.Commit()
  520. }
  521. }()
  522. err = s.updateClientTraffics(tx, oldInbound, inbound)
  523. if err != nil {
  524. return inbound, false, err
  525. }
  526. // Ensure created_at and updated_at exist in inbound.Settings clients
  527. {
  528. var oldSettings map[string]any
  529. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  530. emailToCreated := map[string]int64{}
  531. emailToUpdated := map[string]int64{}
  532. if oldSettings != nil {
  533. if oc, ok := oldSettings["clients"].([]any); ok {
  534. for _, it := range oc {
  535. if m, ok2 := it.(map[string]any); ok2 {
  536. if email, ok3 := m["email"].(string); ok3 {
  537. switch v := m["created_at"].(type) {
  538. case float64:
  539. emailToCreated[email] = int64(v)
  540. case int64:
  541. emailToCreated[email] = v
  542. }
  543. switch v := m["updated_at"].(type) {
  544. case float64:
  545. emailToUpdated[email] = int64(v)
  546. case int64:
  547. emailToUpdated[email] = v
  548. }
  549. }
  550. }
  551. }
  552. }
  553. }
  554. var newSettings map[string]any
  555. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  556. now := time.Now().Unix() * 1000
  557. if nSlice, ok := newSettings["clients"].([]any); ok {
  558. for i := range nSlice {
  559. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  560. email, _ := m["email"].(string)
  561. if _, ok3 := m["created_at"]; !ok3 {
  562. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  563. m["created_at"] = v
  564. } else {
  565. m["created_at"] = now
  566. }
  567. }
  568. // Preserve client's updated_at if present; do not bump on parent inbound update
  569. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  570. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  571. m["updated_at"] = v
  572. }
  573. }
  574. nSlice[i] = m
  575. }
  576. }
  577. newSettings["clients"] = nSlice
  578. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  579. inbound.Settings = string(bs)
  580. }
  581. }
  582. }
  583. }
  584. oldInbound.Total = inbound.Total
  585. oldInbound.Remark = inbound.Remark
  586. oldInbound.Enable = inbound.Enable
  587. oldInbound.ExpiryTime = inbound.ExpiryTime
  588. oldInbound.TrafficReset = inbound.TrafficReset
  589. oldInbound.Listen = inbound.Listen
  590. oldInbound.Port = inbound.Port
  591. oldInbound.Protocol = inbound.Protocol
  592. oldInbound.Settings = inbound.Settings
  593. oldInbound.StreamSettings = inbound.StreamSettings
  594. oldInbound.Sniffing = inbound.Sniffing
  595. // regenerate tag with collision-aware logic. for this row we pass
  596. // inbound.Id as ignoreId so it doesn't see its own old tag in the db.
  597. oldInbound.Tag, err = s.generateInboundTag(inbound, inbound.Id)
  598. if err != nil {
  599. return inbound, false, err
  600. }
  601. needRestart := false
  602. rt, rterr := s.runtimeFor(oldInbound)
  603. if rterr != nil {
  604. if oldInbound.NodeID != nil {
  605. err = rterr
  606. return inbound, false, err
  607. }
  608. needRestart = true
  609. } else {
  610. oldSnapshot := *oldInbound
  611. oldSnapshot.Tag = tag
  612. if oldInbound.NodeID == nil {
  613. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  614. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  615. }
  616. if inbound.Enable {
  617. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  618. if err2 != nil {
  619. logger.Debug("Unable to prepare runtime inbound config:", err2)
  620. needRestart = true
  621. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  622. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  623. } else {
  624. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  625. needRestart = true
  626. }
  627. }
  628. } else {
  629. if !inbound.Enable {
  630. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  631. err = err2
  632. return inbound, false, err
  633. }
  634. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  635. err = err2
  636. return inbound, false, err
  637. }
  638. }
  639. }
  640. return inbound, needRestart, tx.Save(oldInbound).Error
  641. }
  642. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  643. if inbound == nil {
  644. return nil, fmt.Errorf("inbound is nil")
  645. }
  646. runtimeInbound := *inbound
  647. settings := map[string]any{}
  648. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  649. return nil, err
  650. }
  651. clients, ok := settings["clients"].([]any)
  652. if !ok {
  653. return &runtimeInbound, nil
  654. }
  655. var clientStats []xray.ClientTraffic
  656. err := tx.Model(xray.ClientTraffic{}).
  657. Where("inbound_id = ?", inbound.Id).
  658. Select("email", "enable").
  659. Find(&clientStats).Error
  660. if err != nil {
  661. return nil, err
  662. }
  663. enableMap := make(map[string]bool, len(clientStats))
  664. for _, clientTraffic := range clientStats {
  665. enableMap[clientTraffic.Email] = clientTraffic.Enable
  666. }
  667. finalClients := make([]any, 0, len(clients))
  668. for _, client := range clients {
  669. c, ok := client.(map[string]any)
  670. if !ok {
  671. continue
  672. }
  673. email, _ := c["email"].(string)
  674. if enable, exists := enableMap[email]; exists && !enable {
  675. continue
  676. }
  677. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  678. continue
  679. }
  680. finalClients = append(finalClients, c)
  681. }
  682. settings["clients"] = finalClients
  683. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  684. if err != nil {
  685. return nil, err
  686. }
  687. runtimeInbound.Settings = string(modifiedSettings)
  688. return &runtimeInbound, nil
  689. }
  690. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  691. // list: removes rows for emails that disappeared, inserts rows for newly-added
  692. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  693. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  694. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  695. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  696. oldClients, err := s.GetClients(oldInbound)
  697. if err != nil {
  698. return err
  699. }
  700. newClients, err := s.GetClients(newInbound)
  701. if err != nil {
  702. return err
  703. }
  704. // Email is the unique key for ClientTraffic rows. Clients without an
  705. // email have no stats row to sync — skip them on both sides instead of
  706. // risking a unique-constraint hit or accidental delete of an unrelated row.
  707. oldEmails := make(map[string]struct{}, len(oldClients))
  708. for i := range oldClients {
  709. if oldClients[i].Email == "" {
  710. continue
  711. }
  712. oldEmails[oldClients[i].Email] = struct{}{}
  713. }
  714. newEmails := make(map[string]struct{}, len(newClients))
  715. for i := range newClients {
  716. if newClients[i].Email == "" {
  717. continue
  718. }
  719. newEmails[newClients[i].Email] = struct{}{}
  720. }
  721. // Drop stats rows for removed emails — but not when a sibling inbound
  722. // still references the email, since the row is the shared accumulator.
  723. for i := range oldClients {
  724. email := oldClients[i].Email
  725. if email == "" {
  726. continue
  727. }
  728. if _, kept := newEmails[email]; kept {
  729. continue
  730. }
  731. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  732. if err != nil {
  733. return err
  734. }
  735. if stillUsed {
  736. continue
  737. }
  738. if err := s.DelClientStat(tx, email); err != nil {
  739. return err
  740. }
  741. }
  742. for i := range newClients {
  743. email := newClients[i].Email
  744. if email == "" {
  745. continue
  746. }
  747. if _, existed := oldEmails[email]; existed {
  748. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  749. return err
  750. }
  751. continue
  752. }
  753. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  754. return err
  755. }
  756. }
  757. return nil
  758. }
  759. func (s *InboundService) AddInboundClient(data *model.Inbound) (bool, error) {
  760. clients, err := s.GetClients(data)
  761. if err != nil {
  762. return false, err
  763. }
  764. var settings map[string]any
  765. err = json.Unmarshal([]byte(data.Settings), &settings)
  766. if err != nil {
  767. return false, err
  768. }
  769. interfaceClients := settings["clients"].([]any)
  770. // Add timestamps for new clients being appended
  771. nowTs := time.Now().Unix() * 1000
  772. for i := range interfaceClients {
  773. if cm, ok := interfaceClients[i].(map[string]any); ok {
  774. if _, ok2 := cm["created_at"]; !ok2 {
  775. cm["created_at"] = nowTs
  776. }
  777. cm["updated_at"] = nowTs
  778. interfaceClients[i] = cm
  779. }
  780. }
  781. existEmail, err := s.checkEmailsExistForClients(clients)
  782. if err != nil {
  783. return false, err
  784. }
  785. if existEmail != "" {
  786. return false, common.NewError("Duplicate email:", existEmail)
  787. }
  788. oldInbound, err := s.GetInbound(data.Id)
  789. if err != nil {
  790. return false, err
  791. }
  792. // Secure client ID
  793. for _, client := range clients {
  794. switch oldInbound.Protocol {
  795. case "trojan":
  796. if client.Password == "" {
  797. return false, common.NewError("empty client ID")
  798. }
  799. case "shadowsocks":
  800. if client.Email == "" {
  801. return false, common.NewError("empty client ID")
  802. }
  803. case "hysteria", "hysteria2":
  804. if client.Auth == "" {
  805. return false, common.NewError("empty client ID")
  806. }
  807. default:
  808. if client.ID == "" {
  809. return false, common.NewError("empty client ID")
  810. }
  811. }
  812. }
  813. var oldSettings map[string]any
  814. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  815. if err != nil {
  816. return false, err
  817. }
  818. oldClients := oldSettings["clients"].([]any)
  819. oldClients = append(oldClients, interfaceClients...)
  820. oldSettings["clients"] = oldClients
  821. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  822. if err != nil {
  823. return false, err
  824. }
  825. oldInbound.Settings = string(newSettings)
  826. db := database.GetDB()
  827. tx := db.Begin()
  828. defer func() {
  829. if err != nil {
  830. tx.Rollback()
  831. } else {
  832. tx.Commit()
  833. }
  834. }()
  835. needRestart := false
  836. rt, rterr := s.runtimeFor(oldInbound)
  837. if rterr != nil {
  838. if oldInbound.NodeID != nil {
  839. err = rterr
  840. return false, err
  841. }
  842. needRestart = true
  843. } else if oldInbound.NodeID == nil {
  844. for _, client := range clients {
  845. if len(client.Email) == 0 {
  846. needRestart = true
  847. continue
  848. }
  849. s.AddClientStat(tx, data.Id, &client)
  850. if !client.Enable {
  851. continue
  852. }
  853. cipher := ""
  854. if oldInbound.Protocol == "shadowsocks" {
  855. cipher = oldSettings["method"].(string)
  856. }
  857. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  858. "email": client.Email,
  859. "id": client.ID,
  860. "auth": client.Auth,
  861. "security": client.Security,
  862. "flow": client.Flow,
  863. "password": client.Password,
  864. "cipher": cipher,
  865. })
  866. if err1 == nil {
  867. logger.Debug("Client added on", rt.Name(), ":", client.Email)
  868. } else {
  869. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  870. needRestart = true
  871. }
  872. }
  873. } else {
  874. for _, client := range clients {
  875. if len(client.Email) > 0 {
  876. s.AddClientStat(tx, data.Id, &client)
  877. }
  878. }
  879. if err1 := rt.UpdateInbound(context.Background(), oldInbound, oldInbound); err1 != nil {
  880. err = err1
  881. return false, err
  882. }
  883. }
  884. return needRestart, tx.Save(oldInbound).Error
  885. }
  886. func (s *InboundService) getClientPrimaryKey(protocol model.Protocol, client model.Client) string {
  887. switch protocol {
  888. case model.Trojan:
  889. return client.Password
  890. case model.Shadowsocks:
  891. return client.Email
  892. case model.Hysteria:
  893. return client.Auth
  894. default:
  895. return client.ID
  896. }
  897. }
  898. func (s *InboundService) writeBackClientSubID(sourceInboundID int, sourceProtocol model.Protocol, client model.Client, subID string) (bool, error) {
  899. client.SubID = subID
  900. client.UpdatedAt = time.Now().UnixMilli()
  901. clientID := s.getClientPrimaryKey(sourceProtocol, client)
  902. if clientID == "" {
  903. return false, common.NewError("empty client ID")
  904. }
  905. settingsBytes, err := json.Marshal(map[string][]model.Client{
  906. "clients": {client},
  907. })
  908. if err != nil {
  909. return false, err
  910. }
  911. updatePayload := &model.Inbound{
  912. Id: sourceInboundID,
  913. Settings: string(settingsBytes),
  914. }
  915. return s.UpdateInboundClient(updatePayload, clientID)
  916. }
  917. func (s *InboundService) generateRandomCredential(targetProtocol model.Protocol) string {
  918. switch targetProtocol {
  919. case model.VMESS, model.VLESS:
  920. return uuid.NewString()
  921. default:
  922. return strings.ReplaceAll(uuid.NewString(), "-", "")
  923. }
  924. }
  925. func (s *InboundService) buildTargetClientFromSource(source model.Client, targetProtocol model.Protocol, email string, flow string) (model.Client, error) {
  926. nowTs := time.Now().UnixMilli()
  927. target := source
  928. target.Email = email
  929. target.CreatedAt = nowTs
  930. target.UpdatedAt = nowTs
  931. target.ID = ""
  932. target.Password = ""
  933. target.Auth = ""
  934. target.Flow = ""
  935. switch targetProtocol {
  936. case model.VMESS:
  937. target.ID = s.generateRandomCredential(targetProtocol)
  938. case model.VLESS:
  939. target.ID = s.generateRandomCredential(targetProtocol)
  940. if flow == "xtls-rprx-vision" || flow == "xtls-rprx-vision-udp443" {
  941. target.Flow = flow
  942. }
  943. case model.Trojan, model.Shadowsocks:
  944. target.Password = s.generateRandomCredential(targetProtocol)
  945. case model.Hysteria:
  946. target.Auth = s.generateRandomCredential(targetProtocol)
  947. default:
  948. target.ID = s.generateRandomCredential(targetProtocol)
  949. }
  950. return target, nil
  951. }
  952. func (s *InboundService) nextAvailableCopiedEmail(originalEmail string, targetID int, occupied map[string]struct{}) string {
  953. base := fmt.Sprintf("%s_%d", originalEmail, targetID)
  954. candidate := base
  955. suffix := 0
  956. for {
  957. if _, exists := occupied[strings.ToLower(candidate)]; !exists {
  958. occupied[strings.ToLower(candidate)] = struct{}{}
  959. return candidate
  960. }
  961. suffix++
  962. candidate = fmt.Sprintf("%s_%d", base, suffix)
  963. }
  964. }
  965. func (s *InboundService) CopyInboundClients(targetInboundID int, sourceInboundID int, clientEmails []string, flow string) (*CopyClientsResult, bool, error) {
  966. result := &CopyClientsResult{
  967. Added: []string{},
  968. Skipped: []string{},
  969. Errors: []string{},
  970. }
  971. if targetInboundID == sourceInboundID {
  972. return result, false, common.NewError("source and target inbounds must be different")
  973. }
  974. targetInbound, err := s.GetInbound(targetInboundID)
  975. if err != nil {
  976. return result, false, err
  977. }
  978. sourceInbound, err := s.GetInbound(sourceInboundID)
  979. if err != nil {
  980. return result, false, err
  981. }
  982. sourceClients, err := s.GetClients(sourceInbound)
  983. if err != nil {
  984. return result, false, err
  985. }
  986. if len(sourceClients) == 0 {
  987. return result, false, nil
  988. }
  989. allowedEmails := map[string]struct{}{}
  990. if len(clientEmails) > 0 {
  991. for _, email := range clientEmails {
  992. allowedEmails[strings.ToLower(strings.TrimSpace(email))] = struct{}{}
  993. }
  994. }
  995. occupiedEmails := map[string]struct{}{}
  996. allEmails, err := s.getAllEmails()
  997. if err != nil {
  998. return result, false, err
  999. }
  1000. for _, email := range allEmails {
  1001. clean := strings.Trim(email, "\"")
  1002. if clean != "" {
  1003. occupiedEmails[strings.ToLower(clean)] = struct{}{}
  1004. }
  1005. }
  1006. newClients := make([]model.Client, 0)
  1007. needRestart := false
  1008. for _, sourceClient := range sourceClients {
  1009. originalEmail := strings.TrimSpace(sourceClient.Email)
  1010. if originalEmail == "" {
  1011. continue
  1012. }
  1013. if len(allowedEmails) > 0 {
  1014. if _, ok := allowedEmails[strings.ToLower(originalEmail)]; !ok {
  1015. continue
  1016. }
  1017. }
  1018. if sourceClient.SubID == "" {
  1019. newSubID := uuid.NewString()
  1020. subNeedRestart, subErr := s.writeBackClientSubID(sourceInbound.Id, sourceInbound.Protocol, sourceClient, newSubID)
  1021. if subErr != nil {
  1022. result.Errors = append(result.Errors, fmt.Sprintf("%s: failed to write source subId: %v", originalEmail, subErr))
  1023. continue
  1024. }
  1025. if subNeedRestart {
  1026. needRestart = true
  1027. }
  1028. sourceClient.SubID = newSubID
  1029. }
  1030. targetEmail := s.nextAvailableCopiedEmail(originalEmail, targetInboundID, occupiedEmails)
  1031. targetClient, buildErr := s.buildTargetClientFromSource(sourceClient, targetInbound.Protocol, targetEmail, flow)
  1032. if buildErr != nil {
  1033. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", originalEmail, buildErr))
  1034. continue
  1035. }
  1036. newClients = append(newClients, targetClient)
  1037. result.Added = append(result.Added, targetEmail)
  1038. }
  1039. if len(newClients) == 0 {
  1040. return result, needRestart, nil
  1041. }
  1042. settingsPayload, err := json.Marshal(map[string][]model.Client{
  1043. "clients": newClients,
  1044. })
  1045. if err != nil {
  1046. return result, needRestart, err
  1047. }
  1048. addNeedRestart, err := s.AddInboundClient(&model.Inbound{
  1049. Id: targetInboundID,
  1050. Settings: string(settingsPayload),
  1051. })
  1052. if err != nil {
  1053. return result, needRestart, err
  1054. }
  1055. if addNeedRestart {
  1056. needRestart = true
  1057. }
  1058. return result, needRestart, nil
  1059. }
  1060. func (s *InboundService) DelInboundClient(inboundId int, clientId string) (bool, error) {
  1061. oldInbound, err := s.GetInbound(inboundId)
  1062. if err != nil {
  1063. logger.Error("Load Old Data Error")
  1064. return false, err
  1065. }
  1066. var settings map[string]any
  1067. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  1068. if err != nil {
  1069. return false, err
  1070. }
  1071. email := ""
  1072. client_key := "id"
  1073. switch oldInbound.Protocol {
  1074. case "trojan":
  1075. client_key = "password"
  1076. case "shadowsocks":
  1077. client_key = "email"
  1078. case "hysteria", "hysteria2":
  1079. client_key = "auth"
  1080. }
  1081. interfaceClients := settings["clients"].([]any)
  1082. var newClients []any
  1083. needApiDel := false
  1084. clientFound := false
  1085. for _, client := range interfaceClients {
  1086. c := client.(map[string]any)
  1087. c_id := c[client_key].(string)
  1088. if c_id == clientId {
  1089. clientFound = true
  1090. email, _ = c["email"].(string)
  1091. needApiDel, _ = c["enable"].(bool)
  1092. } else {
  1093. newClients = append(newClients, client)
  1094. }
  1095. }
  1096. if !clientFound {
  1097. return false, common.NewError("Client Not Found In Inbound For ID:", clientId)
  1098. }
  1099. if len(newClients) == 0 {
  1100. return false, common.NewError("no client remained in Inbound")
  1101. }
  1102. settings["clients"] = newClients
  1103. newSettings, err := json.MarshalIndent(settings, "", " ")
  1104. if err != nil {
  1105. return false, err
  1106. }
  1107. oldInbound.Settings = string(newSettings)
  1108. db := database.GetDB()
  1109. // Keep the client_traffics row and IPs alive when another inbound still
  1110. // references this email — siblings depend on the shared accounting state.
  1111. emailShared, err := s.emailUsedByOtherInbounds(email, inboundId)
  1112. if err != nil {
  1113. return false, err
  1114. }
  1115. if !emailShared {
  1116. err = s.DelClientIPs(db, email)
  1117. if err != nil {
  1118. logger.Error("Error in delete client IPs")
  1119. return false, err
  1120. }
  1121. }
  1122. needRestart := false
  1123. if len(email) > 0 {
  1124. notDepleted := true
  1125. err = db.Model(xray.ClientTraffic{}).Select("enable").Where("email = ?", email).First(&notDepleted).Error
  1126. if err != nil {
  1127. logger.Error("Get stats error")
  1128. return false, err
  1129. }
  1130. if !emailShared {
  1131. err = s.DelClientStat(db, email)
  1132. if err != nil {
  1133. logger.Error("Delete stats Data Error")
  1134. return false, err
  1135. }
  1136. }
  1137. if needApiDel && notDepleted {
  1138. rt, rterr := s.runtimeFor(oldInbound)
  1139. if rterr != nil {
  1140. if oldInbound.NodeID != nil {
  1141. return false, rterr
  1142. }
  1143. needRestart = true
  1144. } else if oldInbound.NodeID == nil {
  1145. err1 := rt.RemoveUser(context.Background(), oldInbound, email)
  1146. if err1 == nil {
  1147. logger.Debug("Client deleted on", rt.Name(), ":", email)
  1148. needRestart = false
  1149. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  1150. logger.Debug("User is already deleted. Nothing to do more...")
  1151. } else {
  1152. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  1153. needRestart = true
  1154. }
  1155. } else {
  1156. if err1 := rt.UpdateInbound(context.Background(), oldInbound, oldInbound); err1 != nil {
  1157. return false, err1
  1158. }
  1159. }
  1160. }
  1161. }
  1162. return needRestart, db.Save(oldInbound).Error
  1163. }
  1164. func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId string) (bool, error) {
  1165. // TODO: check if TrafficReset field is updating
  1166. clients, err := s.GetClients(data)
  1167. if err != nil {
  1168. return false, err
  1169. }
  1170. var settings map[string]any
  1171. err = json.Unmarshal([]byte(data.Settings), &settings)
  1172. if err != nil {
  1173. return false, err
  1174. }
  1175. interfaceClients := settings["clients"].([]any)
  1176. oldInbound, err := s.GetInbound(data.Id)
  1177. if err != nil {
  1178. return false, err
  1179. }
  1180. oldClients, err := s.GetClients(oldInbound)
  1181. if err != nil {
  1182. return false, err
  1183. }
  1184. oldEmail := ""
  1185. newClientId := ""
  1186. clientIndex := -1
  1187. for index, oldClient := range oldClients {
  1188. oldClientId := ""
  1189. switch oldInbound.Protocol {
  1190. case "trojan":
  1191. oldClientId = oldClient.Password
  1192. newClientId = clients[0].Password
  1193. case "shadowsocks":
  1194. oldClientId = oldClient.Email
  1195. newClientId = clients[0].Email
  1196. case "hysteria", "hysteria2":
  1197. oldClientId = oldClient.Auth
  1198. newClientId = clients[0].Auth
  1199. default:
  1200. oldClientId = oldClient.ID
  1201. newClientId = clients[0].ID
  1202. }
  1203. if clientId == oldClientId {
  1204. oldEmail = oldClient.Email
  1205. clientIndex = index
  1206. break
  1207. }
  1208. }
  1209. // Validate new client ID
  1210. if newClientId == "" || clientIndex == -1 {
  1211. return false, common.NewError("empty client ID")
  1212. }
  1213. if len(clients[0].Email) > 0 && clients[0].Email != oldEmail {
  1214. existEmail, err := s.checkEmailsExistForClients(clients)
  1215. if err != nil {
  1216. return false, err
  1217. }
  1218. if existEmail != "" {
  1219. return false, common.NewError("Duplicate email:", existEmail)
  1220. }
  1221. }
  1222. var oldSettings map[string]any
  1223. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1224. if err != nil {
  1225. return false, err
  1226. }
  1227. settingsClients := oldSettings["clients"].([]any)
  1228. // Preserve created_at and set updated_at for the replacing client
  1229. var preservedCreated any
  1230. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  1231. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  1232. if v, ok2 := oldMap["created_at"]; ok2 {
  1233. preservedCreated = v
  1234. }
  1235. }
  1236. }
  1237. if len(interfaceClients) > 0 {
  1238. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  1239. if preservedCreated == nil {
  1240. preservedCreated = time.Now().Unix() * 1000
  1241. }
  1242. newMap["created_at"] = preservedCreated
  1243. newMap["updated_at"] = time.Now().Unix() * 1000
  1244. interfaceClients[0] = newMap
  1245. }
  1246. }
  1247. settingsClients[clientIndex] = interfaceClients[0]
  1248. oldSettings["clients"] = settingsClients
  1249. // testseed is only meaningful when at least one VLESS client uses the exact
  1250. // xtls-rprx-vision flow. The client-edit path only rewrites a single client,
  1251. // so re-check the flow set here and strip a stale testseed when nothing in the
  1252. // inbound still warrants it. The full-inbound update path already handles this
  1253. // on the JS side via VLESSSettings.toJson().
  1254. if oldInbound.Protocol == model.VLESS {
  1255. hasVisionFlow := false
  1256. for _, c := range settingsClients {
  1257. cm, ok := c.(map[string]any)
  1258. if !ok {
  1259. continue
  1260. }
  1261. if flow, _ := cm["flow"].(string); flow == "xtls-rprx-vision" {
  1262. hasVisionFlow = true
  1263. break
  1264. }
  1265. }
  1266. if !hasVisionFlow {
  1267. delete(oldSettings, "testseed")
  1268. }
  1269. }
  1270. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1271. if err != nil {
  1272. return false, err
  1273. }
  1274. oldInbound.Settings = string(newSettings)
  1275. db := database.GetDB()
  1276. tx := db.Begin()
  1277. defer func() {
  1278. if err != nil {
  1279. tx.Rollback()
  1280. } else {
  1281. tx.Commit()
  1282. }
  1283. }()
  1284. if len(clients[0].Email) > 0 {
  1285. if len(oldEmail) > 0 {
  1286. // Repointing onto an email that already has a row would collide on
  1287. // the unique constraint, so retire the donor and let the surviving
  1288. // row carry the merged identity.
  1289. emailUnchanged := strings.EqualFold(oldEmail, clients[0].Email)
  1290. targetExists := int64(0)
  1291. if !emailUnchanged {
  1292. if err = tx.Model(xray.ClientTraffic{}).Where("email = ?", clients[0].Email).Count(&targetExists).Error; err != nil {
  1293. return false, err
  1294. }
  1295. }
  1296. if emailUnchanged || targetExists == 0 {
  1297. err = s.UpdateClientStat(tx, oldEmail, &clients[0])
  1298. if err != nil {
  1299. return false, err
  1300. }
  1301. err = s.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  1302. if err != nil {
  1303. return false, err
  1304. }
  1305. } else {
  1306. stillUsed, sErr := s.emailUsedByOtherInbounds(oldEmail, data.Id)
  1307. if sErr != nil {
  1308. return false, sErr
  1309. }
  1310. if !stillUsed {
  1311. if err = s.DelClientStat(tx, oldEmail); err != nil {
  1312. return false, err
  1313. }
  1314. if err = s.DelClientIPs(tx, oldEmail); err != nil {
  1315. return false, err
  1316. }
  1317. }
  1318. // Refresh the surviving row with the new client's limits/expiry.
  1319. if err = s.UpdateClientStat(tx, clients[0].Email, &clients[0]); err != nil {
  1320. return false, err
  1321. }
  1322. }
  1323. } else {
  1324. s.AddClientStat(tx, data.Id, &clients[0])
  1325. }
  1326. } else {
  1327. stillUsed, err := s.emailUsedByOtherInbounds(oldEmail, data.Id)
  1328. if err != nil {
  1329. return false, err
  1330. }
  1331. if !stillUsed {
  1332. err = s.DelClientStat(tx, oldEmail)
  1333. if err != nil {
  1334. return false, err
  1335. }
  1336. err = s.DelClientIPs(tx, oldEmail)
  1337. if err != nil {
  1338. return false, err
  1339. }
  1340. }
  1341. }
  1342. needRestart := false
  1343. if len(oldEmail) > 0 {
  1344. rt, rterr := s.runtimeFor(oldInbound)
  1345. if rterr != nil {
  1346. if oldInbound.NodeID != nil {
  1347. err = rterr
  1348. return false, err
  1349. }
  1350. needRestart = true
  1351. } else if oldInbound.NodeID == nil {
  1352. if oldClients[clientIndex].Enable {
  1353. err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
  1354. if err1 == nil {
  1355. logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail)
  1356. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  1357. logger.Debug("User is already deleted. Nothing to do more...")
  1358. } else {
  1359. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  1360. needRestart = true
  1361. }
  1362. }
  1363. if clients[0].Enable {
  1364. cipher := ""
  1365. if oldInbound.Protocol == "shadowsocks" {
  1366. cipher = oldSettings["method"].(string)
  1367. }
  1368. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  1369. "email": clients[0].Email,
  1370. "id": clients[0].ID,
  1371. "security": clients[0].Security,
  1372. "flow": clients[0].Flow,
  1373. "auth": clients[0].Auth,
  1374. "password": clients[0].Password,
  1375. "cipher": cipher,
  1376. })
  1377. if err1 == nil {
  1378. logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
  1379. } else {
  1380. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  1381. needRestart = true
  1382. }
  1383. }
  1384. } else {
  1385. if err1 := rt.UpdateInbound(context.Background(), oldInbound, oldInbound); err1 != nil {
  1386. err = err1
  1387. return false, err
  1388. }
  1389. }
  1390. } else {
  1391. logger.Debug("Client old email not found")
  1392. needRestart = true
  1393. }
  1394. return needRestart, tx.Save(oldInbound).Error
  1395. }
  1396. const resetGracePeriodMs int64 = 30000
  1397. func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot) (bool, error) {
  1398. var structuralChange bool
  1399. err := submitTrafficWrite(func() error {
  1400. var inner error
  1401. structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap)
  1402. return inner
  1403. })
  1404. return structuralChange, err
  1405. }
  1406. func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.TrafficSnapshot) (bool, error) {
  1407. if snap == nil || nodeID <= 0 {
  1408. return false, nil
  1409. }
  1410. db := database.GetDB()
  1411. now := time.Now().UnixMilli()
  1412. var central []model.Inbound
  1413. if err := db.Model(model.Inbound{}).
  1414. Where("node_id = ?", nodeID).
  1415. Find(&central).Error; err != nil {
  1416. return false, err
  1417. }
  1418. tagToCentral := make(map[string]*model.Inbound, len(central))
  1419. for i := range central {
  1420. tagToCentral[central[i].Tag] = &central[i]
  1421. }
  1422. var centralClientStats []xray.ClientTraffic
  1423. if len(central) > 0 {
  1424. ids := make([]int, 0, len(central))
  1425. for i := range central {
  1426. ids = append(ids, central[i].Id)
  1427. }
  1428. if err := db.Model(xray.ClientTraffic{}).
  1429. Where("inbound_id IN ?", ids).
  1430. Find(&centralClientStats).Error; err != nil {
  1431. return false, err
  1432. }
  1433. }
  1434. type csKey struct {
  1435. inboundID int
  1436. email string
  1437. }
  1438. centralCS := make(map[csKey]*xray.ClientTraffic, len(centralClientStats))
  1439. for i := range centralClientStats {
  1440. centralCS[csKey{centralClientStats[i].InboundId, centralClientStats[i].Email}] = &centralClientStats[i]
  1441. }
  1442. var defaultUserId int
  1443. if len(central) > 0 {
  1444. defaultUserId = central[0].UserId
  1445. } else {
  1446. var u model.User
  1447. if err := db.Model(model.User{}).Order("id asc").First(&u).Error; err == nil {
  1448. defaultUserId = u.Id
  1449. } else {
  1450. defaultUserId = 1
  1451. }
  1452. }
  1453. tx := db.Begin()
  1454. committed := false
  1455. defer func() {
  1456. if !committed {
  1457. tx.Rollback()
  1458. }
  1459. }()
  1460. structuralChange := false
  1461. snapTags := make(map[string]struct{}, len(snap.Inbounds))
  1462. for _, snapIb := range snap.Inbounds {
  1463. if snapIb == nil {
  1464. continue
  1465. }
  1466. snapTags[snapIb.Tag] = struct{}{}
  1467. c, ok := tagToCentral[snapIb.Tag]
  1468. if !ok {
  1469. newIb := model.Inbound{
  1470. UserId: defaultUserId,
  1471. NodeID: &nodeID,
  1472. Tag: snapIb.Tag,
  1473. Listen: snapIb.Listen,
  1474. Port: snapIb.Port,
  1475. Protocol: snapIb.Protocol,
  1476. Settings: snapIb.Settings,
  1477. StreamSettings: snapIb.StreamSettings,
  1478. Sniffing: snapIb.Sniffing,
  1479. TrafficReset: snapIb.TrafficReset,
  1480. Enable: snapIb.Enable,
  1481. Remark: snapIb.Remark,
  1482. Total: snapIb.Total,
  1483. ExpiryTime: snapIb.ExpiryTime,
  1484. Up: snapIb.Up,
  1485. Down: snapIb.Down,
  1486. AllTime: snapIb.AllTime,
  1487. }
  1488. if err := tx.Create(&newIb).Error; err != nil {
  1489. logger.Warning("setRemoteTraffic: create central inbound for tag", snapIb.Tag, "failed:", err)
  1490. continue
  1491. }
  1492. tagToCentral[snapIb.Tag] = &newIb
  1493. structuralChange = true
  1494. continue
  1495. }
  1496. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  1497. updates := map[string]any{
  1498. "enable": snapIb.Enable,
  1499. "remark": snapIb.Remark,
  1500. "listen": snapIb.Listen,
  1501. "port": snapIb.Port,
  1502. "protocol": snapIb.Protocol,
  1503. "total": snapIb.Total,
  1504. "expiry_time": snapIb.ExpiryTime,
  1505. "settings": snapIb.Settings,
  1506. "stream_settings": snapIb.StreamSettings,
  1507. "sniffing": snapIb.Sniffing,
  1508. "traffic_reset": snapIb.TrafficReset,
  1509. }
  1510. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  1511. updates["up"] = snapIb.Up
  1512. updates["down"] = snapIb.Down
  1513. }
  1514. if snapIb.AllTime > c.AllTime {
  1515. updates["all_time"] = snapIb.AllTime
  1516. }
  1517. if c.Settings != snapIb.Settings ||
  1518. c.Remark != snapIb.Remark ||
  1519. c.Listen != snapIb.Listen ||
  1520. c.Port != snapIb.Port ||
  1521. c.Total != snapIb.Total ||
  1522. c.ExpiryTime != snapIb.ExpiryTime ||
  1523. c.Enable != snapIb.Enable {
  1524. structuralChange = true
  1525. }
  1526. if err := tx.Model(model.Inbound{}).
  1527. Where("id = ?", c.Id).
  1528. Updates(updates).Error; err != nil {
  1529. return false, err
  1530. }
  1531. }
  1532. for _, c := range central {
  1533. if _, kept := snapTags[c.Tag]; kept {
  1534. continue
  1535. }
  1536. if err := tx.Where("inbound_id = ?", c.Id).
  1537. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1538. return false, err
  1539. }
  1540. if err := tx.Where("id = ?", c.Id).
  1541. Delete(&model.Inbound{}).Error; err != nil {
  1542. return false, err
  1543. }
  1544. delete(tagToCentral, c.Tag)
  1545. structuralChange = true
  1546. }
  1547. for _, snapIb := range snap.Inbounds {
  1548. if snapIb == nil {
  1549. continue
  1550. }
  1551. c, ok := tagToCentral[snapIb.Tag]
  1552. if !ok {
  1553. continue
  1554. }
  1555. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  1556. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  1557. for _, cs := range snapIb.ClientStats {
  1558. snapEmails[cs.Email] = struct{}{}
  1559. existing := centralCS[csKey{c.Id, cs.Email}]
  1560. if existing == nil {
  1561. if err := tx.Create(&xray.ClientTraffic{
  1562. InboundId: c.Id,
  1563. Email: cs.Email,
  1564. Enable: cs.Enable,
  1565. Total: cs.Total,
  1566. ExpiryTime: cs.ExpiryTime,
  1567. Reset: cs.Reset,
  1568. Up: cs.Up,
  1569. Down: cs.Down,
  1570. AllTime: cs.AllTime,
  1571. LastOnline: cs.LastOnline,
  1572. }).Error; err != nil {
  1573. return false, err
  1574. }
  1575. structuralChange = true
  1576. continue
  1577. }
  1578. if existing.Enable != cs.Enable ||
  1579. existing.Total != cs.Total ||
  1580. existing.ExpiryTime != cs.ExpiryTime ||
  1581. existing.Reset != cs.Reset {
  1582. structuralChange = true
  1583. }
  1584. allTime := existing.AllTime
  1585. if cs.AllTime > allTime {
  1586. allTime = cs.AllTime
  1587. }
  1588. if inGrace && cs.Up+cs.Down > 0 {
  1589. if err := tx.Exec(
  1590. `UPDATE client_traffics
  1591. SET enable = ?, total = ?, expiry_time = ?, reset = ?, all_time = ?
  1592. WHERE inbound_id = ? AND email = ?`,
  1593. cs.Enable, cs.Total, cs.ExpiryTime, cs.Reset, allTime, c.Id, cs.Email,
  1594. ).Error; err != nil {
  1595. return false, err
  1596. }
  1597. continue
  1598. }
  1599. if err := tx.Exec(
  1600. `UPDATE client_traffics
  1601. SET up = ?, down = ?, enable = ?, total = ?, expiry_time = ?, reset = ?,
  1602. all_time = ?, last_online = MAX(last_online, ?)
  1603. WHERE inbound_id = ? AND email = ?`,
  1604. cs.Up, cs.Down, cs.Enable, cs.Total, cs.ExpiryTime, cs.Reset, allTime,
  1605. cs.LastOnline, c.Id, cs.Email,
  1606. ).Error; err != nil {
  1607. return false, err
  1608. }
  1609. }
  1610. for k, existing := range centralCS {
  1611. if k.inboundID != c.Id {
  1612. continue
  1613. }
  1614. if _, kept := snapEmails[k.email]; kept {
  1615. continue
  1616. }
  1617. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  1618. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1619. return false, err
  1620. }
  1621. structuralChange = true
  1622. }
  1623. }
  1624. if err := tx.Commit().Error; err != nil {
  1625. return false, err
  1626. }
  1627. committed = true
  1628. if p != nil {
  1629. p.SetNodeOnlineClients(nodeID, snap.OnlineEmails)
  1630. }
  1631. return structuralChange, nil
  1632. }
  1633. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (needRestart bool, clientsDisabled bool, err error) {
  1634. err = submitTrafficWrite(func() error {
  1635. var inner error
  1636. needRestart, clientsDisabled, inner = s.addTrafficLocked(inboundTraffics, clientTraffics)
  1637. return inner
  1638. })
  1639. return
  1640. }
  1641. func (s *InboundService) addTrafficLocked(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (bool, bool, error) {
  1642. var err error
  1643. db := database.GetDB()
  1644. tx := db.Begin()
  1645. defer func() {
  1646. if err != nil {
  1647. tx.Rollback()
  1648. } else {
  1649. tx.Commit()
  1650. }
  1651. }()
  1652. err = s.addInboundTraffic(tx, inboundTraffics)
  1653. if err != nil {
  1654. return false, false, err
  1655. }
  1656. err = s.addClientTraffic(tx, clientTraffics)
  1657. if err != nil {
  1658. return false, false, err
  1659. }
  1660. needRestart0, count, err := s.autoRenewClients(tx)
  1661. if err != nil {
  1662. logger.Warning("Error in renew clients:", err)
  1663. } else if count > 0 {
  1664. logger.Debugf("%v clients renewed", count)
  1665. }
  1666. disabledClientsCount := int64(0)
  1667. needRestart1, count, err := s.disableInvalidClients(tx)
  1668. if err != nil {
  1669. logger.Warning("Error in disabling invalid clients:", err)
  1670. } else if count > 0 {
  1671. logger.Debugf("%v clients disabled", count)
  1672. disabledClientsCount = count
  1673. }
  1674. needRestart2, count, err := s.disableInvalidInbounds(tx)
  1675. if err != nil {
  1676. logger.Warning("Error in disabling invalid inbounds:", err)
  1677. } else if count > 0 {
  1678. logger.Debugf("%v inbounds disabled", count)
  1679. }
  1680. return needRestart0 || needRestart1 || needRestart2, disabledClientsCount > 0, nil
  1681. }
  1682. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  1683. if len(traffics) == 0 {
  1684. return nil
  1685. }
  1686. var err error
  1687. for _, traffic := range traffics {
  1688. if traffic.IsInbound {
  1689. err = tx.Model(&model.Inbound{}).Where("tag = ? AND node_id IS NULL", traffic.Tag).
  1690. Updates(map[string]any{
  1691. "up": gorm.Expr("up + ?", traffic.Up),
  1692. "down": gorm.Expr("down + ?", traffic.Down),
  1693. "all_time": gorm.Expr("COALESCE(all_time, 0) + ?", traffic.Up+traffic.Down),
  1694. }).Error
  1695. if err != nil {
  1696. return err
  1697. }
  1698. }
  1699. }
  1700. return nil
  1701. }
  1702. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  1703. if len(traffics) == 0 {
  1704. // Empty onlineUsers
  1705. if p != nil {
  1706. p.SetOnlineClients(make([]string, 0))
  1707. }
  1708. return nil
  1709. }
  1710. onlineClients := make([]string, 0)
  1711. emails := make([]string, 0, len(traffics))
  1712. for _, traffic := range traffics {
  1713. emails = append(emails, traffic.Email)
  1714. }
  1715. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  1716. err = tx.Model(xray.ClientTraffic{}).
  1717. Where("email IN (?) AND inbound_id IN (?)", emails,
  1718. tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NULL")).
  1719. Find(&dbClientTraffics).Error
  1720. if err != nil {
  1721. return err
  1722. }
  1723. // Avoid empty slice error
  1724. if len(dbClientTraffics) == 0 {
  1725. return nil
  1726. }
  1727. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  1728. if err != nil {
  1729. return err
  1730. }
  1731. // Index by email for O(N) merge — the previous nested loop was O(N²)
  1732. // and dominated each cron tick on inbounds with thousands of active
  1733. // clients (7500 × 7500 = 56M string comparisons every 10 seconds).
  1734. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  1735. for i := range traffics {
  1736. if traffics[i] != nil {
  1737. trafficByEmail[traffics[i].Email] = traffics[i]
  1738. }
  1739. }
  1740. now := time.Now().UnixMilli()
  1741. for dbTraffic_index := range dbClientTraffics {
  1742. t, ok := trafficByEmail[dbClientTraffics[dbTraffic_index].Email]
  1743. if !ok {
  1744. continue
  1745. }
  1746. dbClientTraffics[dbTraffic_index].Up += t.Up
  1747. dbClientTraffics[dbTraffic_index].Down += t.Down
  1748. dbClientTraffics[dbTraffic_index].AllTime += t.Up + t.Down
  1749. if t.Up+t.Down > 0 {
  1750. onlineClients = append(onlineClients, t.Email)
  1751. dbClientTraffics[dbTraffic_index].LastOnline = now
  1752. }
  1753. }
  1754. // Set onlineUsers
  1755. p.SetOnlineClients(onlineClients)
  1756. err = tx.Save(dbClientTraffics).Error
  1757. if err != nil {
  1758. logger.Warning("AddClientTraffic update data ", err)
  1759. }
  1760. return nil
  1761. }
  1762. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  1763. inboundIds := make([]int, 0, len(dbClientTraffics))
  1764. for _, dbClientTraffic := range dbClientTraffics {
  1765. if dbClientTraffic.ExpiryTime < 0 {
  1766. inboundIds = append(inboundIds, dbClientTraffic.InboundId)
  1767. }
  1768. }
  1769. if len(inboundIds) > 0 {
  1770. var inbounds []*model.Inbound
  1771. err := tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  1772. if err != nil {
  1773. return nil, err
  1774. }
  1775. for inbound_index := range inbounds {
  1776. settings := map[string]any{}
  1777. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1778. clients, ok := settings["clients"].([]any)
  1779. if ok {
  1780. var newClients []any
  1781. for client_index := range clients {
  1782. c := clients[client_index].(map[string]any)
  1783. for traffic_index := range dbClientTraffics {
  1784. if dbClientTraffics[traffic_index].ExpiryTime < 0 && c["email"] == dbClientTraffics[traffic_index].Email {
  1785. oldExpiryTime := c["expiryTime"].(float64)
  1786. newExpiryTime := (time.Now().Unix() * 1000) - int64(oldExpiryTime)
  1787. c["expiryTime"] = newExpiryTime
  1788. c["updated_at"] = time.Now().Unix() * 1000
  1789. dbClientTraffics[traffic_index].ExpiryTime = newExpiryTime
  1790. break
  1791. }
  1792. }
  1793. // Backfill created_at and updated_at
  1794. if _, ok := c["created_at"]; !ok {
  1795. c["created_at"] = time.Now().Unix() * 1000
  1796. }
  1797. c["updated_at"] = time.Now().Unix() * 1000
  1798. newClients = append(newClients, any(c))
  1799. }
  1800. settings["clients"] = newClients
  1801. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1802. if err != nil {
  1803. return nil, err
  1804. }
  1805. inbounds[inbound_index].Settings = string(modifiedSettings)
  1806. }
  1807. }
  1808. err = tx.Save(inbounds).Error
  1809. if err != nil {
  1810. logger.Warning("AddClientTraffic update inbounds ", err)
  1811. logger.Error(inbounds)
  1812. }
  1813. }
  1814. return dbClientTraffics, nil
  1815. }
  1816. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  1817. // check for time expired
  1818. var traffics []*xray.ClientTraffic
  1819. now := time.Now().Unix() * 1000
  1820. var err, err1 error
  1821. err = tx.Model(xray.ClientTraffic{}).
  1822. Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).
  1823. Where("inbound_id IN (?)", tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NULL")).
  1824. Find(&traffics).Error
  1825. if err != nil {
  1826. return false, 0, err
  1827. }
  1828. // return if there is no client to renew
  1829. if len(traffics) == 0 {
  1830. return false, 0, nil
  1831. }
  1832. var inbound_ids []int
  1833. var inbounds []*model.Inbound
  1834. needRestart := false
  1835. var clientsToAdd []struct {
  1836. protocol string
  1837. tag string
  1838. client map[string]any
  1839. }
  1840. for _, traffic := range traffics {
  1841. inbound_ids = append(inbound_ids, traffic.InboundId)
  1842. }
  1843. // Dedupe so an inbound hosting N expired clients is fetched and saved once
  1844. // per tick instead of N times across chunk boundaries.
  1845. inbound_ids = uniqueInts(inbound_ids)
  1846. // Chunked to stay under SQLite's bind-variable limit when many inbounds
  1847. // are touched in a single tick.
  1848. for _, batch := range chunkInts(inbound_ids, sqliteMaxVars) {
  1849. var page []*model.Inbound
  1850. if err = tx.Model(model.Inbound{}).Where("id IN ?", batch).Find(&page).Error; err != nil {
  1851. return false, 0, err
  1852. }
  1853. inbounds = append(inbounds, page...)
  1854. }
  1855. for inbound_index := range inbounds {
  1856. settings := map[string]any{}
  1857. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1858. clients := settings["clients"].([]any)
  1859. for client_index := range clients {
  1860. c := clients[client_index].(map[string]any)
  1861. for traffic_index, traffic := range traffics {
  1862. if traffic.Email == c["email"].(string) {
  1863. newExpiryTime := traffic.ExpiryTime
  1864. for newExpiryTime < now {
  1865. newExpiryTime += (int64(traffic.Reset) * 86400000)
  1866. }
  1867. c["expiryTime"] = newExpiryTime
  1868. traffics[traffic_index].ExpiryTime = newExpiryTime
  1869. traffics[traffic_index].Down = 0
  1870. traffics[traffic_index].Up = 0
  1871. if !traffic.Enable {
  1872. traffics[traffic_index].Enable = true
  1873. clientsToAdd = append(clientsToAdd,
  1874. struct {
  1875. protocol string
  1876. tag string
  1877. client map[string]any
  1878. }{
  1879. protocol: string(inbounds[inbound_index].Protocol),
  1880. tag: inbounds[inbound_index].Tag,
  1881. client: c,
  1882. })
  1883. }
  1884. clients[client_index] = any(c)
  1885. break
  1886. }
  1887. }
  1888. }
  1889. settings["clients"] = clients
  1890. newSettings, err := json.MarshalIndent(settings, "", " ")
  1891. if err != nil {
  1892. return false, 0, err
  1893. }
  1894. inbounds[inbound_index].Settings = string(newSettings)
  1895. }
  1896. err = tx.Save(inbounds).Error
  1897. if err != nil {
  1898. return false, 0, err
  1899. }
  1900. err = tx.Save(traffics).Error
  1901. if err != nil {
  1902. return false, 0, err
  1903. }
  1904. if p != nil {
  1905. err1 = s.xrayApi.Init(p.GetAPIPort())
  1906. if err1 != nil {
  1907. return true, int64(len(traffics)), nil
  1908. }
  1909. for _, clientToAdd := range clientsToAdd {
  1910. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  1911. if err1 != nil {
  1912. needRestart = true
  1913. }
  1914. }
  1915. s.xrayApi.Close()
  1916. }
  1917. return needRestart, int64(len(traffics)), nil
  1918. }
  1919. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  1920. now := time.Now().Unix() * 1000
  1921. needRestart := false
  1922. if p != nil {
  1923. var tags []string
  1924. err := tx.Table("inbounds").
  1925. Select("inbounds.tag").
  1926. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ? and node_id IS NULL", now, true).
  1927. Scan(&tags).Error
  1928. if err != nil {
  1929. return false, 0, err
  1930. }
  1931. s.xrayApi.Init(p.GetAPIPort())
  1932. for _, tag := range tags {
  1933. err1 := s.xrayApi.DelInbound(tag)
  1934. if err1 == nil {
  1935. logger.Debug("Inbound disabled by api:", tag)
  1936. } else {
  1937. logger.Debug("Error in disabling inbound by api:", err1)
  1938. needRestart = true
  1939. }
  1940. }
  1941. s.xrayApi.Close()
  1942. }
  1943. result := tx.Model(model.Inbound{}).
  1944. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ? and node_id IS NULL", now, true).
  1945. Update("enable", false)
  1946. err := result.Error
  1947. count := result.RowsAffected
  1948. return needRestart, count, err
  1949. }
  1950. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error) {
  1951. now := time.Now().Unix() * 1000
  1952. needRestart := false
  1953. var depletedRows []xray.ClientTraffic
  1954. err := tx.Model(xray.ClientTraffic{}).
  1955. Where("((total > 0 AND up + down >= total) OR (expiry_time > 0 AND expiry_time <= ?)) AND enable = ?", now, true).
  1956. Where("inbound_id IN (?)", tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NULL")).
  1957. Find(&depletedRows).Error
  1958. if err != nil {
  1959. return false, 0, err
  1960. }
  1961. if len(depletedRows) == 0 {
  1962. return false, 0, nil
  1963. }
  1964. rowByEmail := make(map[string]*xray.ClientTraffic, len(depletedRows))
  1965. depletedEmails := make([]string, 0, len(depletedRows))
  1966. for i := range depletedRows {
  1967. if depletedRows[i].Email == "" {
  1968. continue
  1969. }
  1970. rowByEmail[strings.ToLower(depletedRows[i].Email)] = &depletedRows[i]
  1971. depletedEmails = append(depletedEmails, depletedRows[i].Email)
  1972. }
  1973. // Resolve inbound membership only for the depleted emails — pushing the
  1974. // filter into SQLite avoids dragging every panel client through Go for
  1975. // the common case where most clients are healthy.
  1976. var memberships []struct {
  1977. InboundId int
  1978. Tag string
  1979. Email string
  1980. SubID string `gorm:"column:sub_id"`
  1981. }
  1982. if len(depletedEmails) > 0 {
  1983. err = tx.Raw(`
  1984. SELECT inbounds.id AS inbound_id,
  1985. inbounds.tag AS tag,
  1986. JSON_EXTRACT(client.value, '$.email') AS email,
  1987. JSON_EXTRACT(client.value, '$.subId') AS sub_id
  1988. FROM inbounds,
  1989. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1990. WHERE LOWER(JSON_EXTRACT(client.value, '$.email')) IN ?
  1991. `, lowerAll(depletedEmails)).Scan(&memberships).Error
  1992. if err != nil {
  1993. return false, 0, err
  1994. }
  1995. }
  1996. // Discover the row holder's subId per email. Only siblings sharing it
  1997. // get cascaded; legacy data where two identities reuse the same email
  1998. // stays isolated to the row owner.
  1999. holderSub := make(map[string]string, len(rowByEmail))
  2000. for _, m := range memberships {
  2001. email := strings.ToLower(strings.Trim(m.Email, "\""))
  2002. row, ok := rowByEmail[email]
  2003. if !ok || m.InboundId != row.InboundId {
  2004. continue
  2005. }
  2006. holderSub[email] = strings.Trim(m.SubID, "\"")
  2007. }
  2008. type target struct {
  2009. InboundId int
  2010. Tag string
  2011. Email string
  2012. }
  2013. var targets []target
  2014. for _, m := range memberships {
  2015. email := strings.ToLower(strings.Trim(m.Email, "\""))
  2016. row, ok := rowByEmail[email]
  2017. if !ok {
  2018. continue
  2019. }
  2020. expected, hasSub := holderSub[email]
  2021. mSub := strings.Trim(m.SubID, "\"")
  2022. switch {
  2023. case !hasSub || expected == "":
  2024. if m.InboundId != row.InboundId {
  2025. continue
  2026. }
  2027. case mSub != expected:
  2028. continue
  2029. }
  2030. targets = append(targets, target{
  2031. InboundId: m.InboundId,
  2032. Tag: m.Tag,
  2033. Email: strings.Trim(m.Email, "\""),
  2034. })
  2035. }
  2036. if p != nil && len(targets) > 0 {
  2037. s.xrayApi.Init(p.GetAPIPort())
  2038. for _, t := range targets {
  2039. err1 := s.xrayApi.RemoveUser(t.Tag, t.Email)
  2040. if err1 == nil {
  2041. logger.Debug("Client disabled by api:", t.Email)
  2042. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.Email)) {
  2043. logger.Debug("User is already disabled. Nothing to do more...")
  2044. } else {
  2045. logger.Debug("Error in disabling client by api:", err1)
  2046. needRestart = true
  2047. }
  2048. }
  2049. s.xrayApi.Close()
  2050. }
  2051. result := tx.Model(xray.ClientTraffic{}).
  2052. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  2053. Where("inbound_id IN (?)", tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NULL")).
  2054. Update("enable", false)
  2055. err = result.Error
  2056. count := result.RowsAffected
  2057. if err != nil {
  2058. return needRestart, count, err
  2059. }
  2060. if len(targets) == 0 {
  2061. return needRestart, count, nil
  2062. }
  2063. inboundEmailMap := make(map[int]map[string]struct{})
  2064. for _, t := range targets {
  2065. if inboundEmailMap[t.InboundId] == nil {
  2066. inboundEmailMap[t.InboundId] = make(map[string]struct{})
  2067. }
  2068. inboundEmailMap[t.InboundId][t.Email] = struct{}{}
  2069. }
  2070. inboundIds := make([]int, 0, len(inboundEmailMap))
  2071. for id := range inboundEmailMap {
  2072. inboundIds = append(inboundIds, id)
  2073. }
  2074. var inbounds []*model.Inbound
  2075. if err = tx.Model(model.Inbound{}).Where("id IN ?", inboundIds).Find(&inbounds).Error; err != nil {
  2076. logger.Warning("disableInvalidClients fetch inbounds:", err)
  2077. return needRestart, count, nil
  2078. }
  2079. dirty := make([]*model.Inbound, 0, len(inbounds))
  2080. for _, inbound := range inbounds {
  2081. settings := map[string]any{}
  2082. if jsonErr := json.Unmarshal([]byte(inbound.Settings), &settings); jsonErr != nil {
  2083. continue
  2084. }
  2085. clientsRaw, ok := settings["clients"].([]any)
  2086. if !ok {
  2087. continue
  2088. }
  2089. emailSet := inboundEmailMap[inbound.Id]
  2090. changed := false
  2091. for i := range clientsRaw {
  2092. c, ok := clientsRaw[i].(map[string]any)
  2093. if !ok {
  2094. continue
  2095. }
  2096. email, _ := c["email"].(string)
  2097. if _, shouldDisable := emailSet[email]; !shouldDisable {
  2098. continue
  2099. }
  2100. c["enable"] = false
  2101. if row, ok := rowByEmail[strings.ToLower(email)]; ok {
  2102. c["totalGB"] = row.Total
  2103. c["expiryTime"] = row.ExpiryTime
  2104. }
  2105. c["updated_at"] = now
  2106. clientsRaw[i] = c
  2107. changed = true
  2108. }
  2109. if !changed {
  2110. continue
  2111. }
  2112. settings["clients"] = clientsRaw
  2113. modifiedSettings, jsonErr := json.MarshalIndent(settings, "", " ")
  2114. if jsonErr != nil {
  2115. continue
  2116. }
  2117. inbound.Settings = string(modifiedSettings)
  2118. dirty = append(dirty, inbound)
  2119. }
  2120. if len(dirty) > 0 {
  2121. if err = tx.Save(dirty).Error; err != nil {
  2122. logger.Warning("disableInvalidClients update inbound settings:", err)
  2123. }
  2124. }
  2125. return needRestart, count, nil
  2126. }
  2127. func (s *InboundService) GetInboundTags() (string, error) {
  2128. db := database.GetDB()
  2129. var inboundTags []string
  2130. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  2131. if err != nil && err != gorm.ErrRecordNotFound {
  2132. return "", err
  2133. }
  2134. tags, _ := json.Marshal(inboundTags)
  2135. return string(tags), nil
  2136. }
  2137. func (s *InboundService) GetClientReverseTags() (string, error) {
  2138. db := database.GetDB()
  2139. var inbounds []model.Inbound
  2140. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  2141. if err != nil && err != gorm.ErrRecordNotFound {
  2142. return "[]", err
  2143. }
  2144. tagSet := make(map[string]struct{})
  2145. for _, inbound := range inbounds {
  2146. var settings map[string]any
  2147. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2148. continue
  2149. }
  2150. clients, ok := settings["clients"].([]any)
  2151. if !ok {
  2152. continue
  2153. }
  2154. for _, client := range clients {
  2155. clientMap, ok := client.(map[string]any)
  2156. if !ok {
  2157. continue
  2158. }
  2159. reverse, ok := clientMap["reverse"].(map[string]any)
  2160. if !ok {
  2161. continue
  2162. }
  2163. tag, _ := reverse["tag"].(string)
  2164. tag = strings.TrimSpace(tag)
  2165. if tag != "" {
  2166. tagSet[tag] = struct{}{}
  2167. }
  2168. }
  2169. }
  2170. rawTags := make([]string, 0, len(tagSet))
  2171. for tag := range tagSet {
  2172. rawTags = append(rawTags, tag)
  2173. }
  2174. sort.Strings(rawTags)
  2175. result, _ := json.Marshal(rawTags)
  2176. return string(result), nil
  2177. }
  2178. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  2179. db := database.GetDB()
  2180. db.Exec(`
  2181. DELETE FROM client_traffics
  2182. WHERE email NOT IN (
  2183. SELECT JSON_EXTRACT(client.value, '$.email')
  2184. FROM inbounds,
  2185. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  2186. )
  2187. `)
  2188. }
  2189. // AddClientStat inserts a per-client accounting row, no-op on email
  2190. // conflict. Xray reports traffic per email, so the surviving row acts as
  2191. // the shared accumulator for inbounds that re-use the same identity.
  2192. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  2193. clientTraffic := xray.ClientTraffic{
  2194. InboundId: inboundId,
  2195. Email: client.Email,
  2196. Total: client.TotalGB,
  2197. ExpiryTime: client.ExpiryTime,
  2198. Enable: client.Enable,
  2199. Reset: client.Reset,
  2200. }
  2201. return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  2202. Create(&clientTraffic).Error
  2203. }
  2204. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  2205. result := tx.Model(xray.ClientTraffic{}).
  2206. Where("email = ?", email).
  2207. Updates(map[string]any{
  2208. "enable": client.Enable,
  2209. "email": client.Email,
  2210. "total": client.TotalGB,
  2211. "expiry_time": client.ExpiryTime,
  2212. "reset": client.Reset,
  2213. })
  2214. err := result.Error
  2215. return err
  2216. }
  2217. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  2218. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  2219. }
  2220. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  2221. return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error
  2222. }
  2223. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  2224. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  2225. }
  2226. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  2227. db := database.GetDB()
  2228. var traffics []*xray.ClientTraffic
  2229. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  2230. if err != nil {
  2231. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  2232. return nil, nil, err
  2233. }
  2234. if len(traffics) > 0 {
  2235. inbound, err = s.GetInbound(traffics[0].InboundId)
  2236. return traffics[0], inbound, err
  2237. }
  2238. return nil, nil, nil
  2239. }
  2240. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  2241. db := database.GetDB()
  2242. var traffics []*xray.ClientTraffic
  2243. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  2244. if err != nil {
  2245. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  2246. return nil, nil, err
  2247. }
  2248. if len(traffics) > 0 {
  2249. inbound, err = s.GetInbound(traffics[0].InboundId)
  2250. return traffics[0], inbound, err
  2251. }
  2252. return nil, nil, nil
  2253. }
  2254. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  2255. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2256. if err != nil {
  2257. return nil, nil, err
  2258. }
  2259. if inbound == nil {
  2260. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  2261. }
  2262. clients, err := s.GetClients(inbound)
  2263. if err != nil {
  2264. return nil, nil, err
  2265. }
  2266. for _, client := range clients {
  2267. if client.Email == clientEmail {
  2268. return traffic, &client, nil
  2269. }
  2270. }
  2271. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  2272. }
  2273. func (s *InboundService) SetClientTelegramUserID(trafficId int, tgId int64) (bool, error) {
  2274. traffic, inbound, err := s.GetClientInboundByTrafficID(trafficId)
  2275. if err != nil {
  2276. return false, err
  2277. }
  2278. if inbound == nil {
  2279. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  2280. }
  2281. clientEmail := traffic.Email
  2282. oldClients, err := s.GetClients(inbound)
  2283. if err != nil {
  2284. return false, err
  2285. }
  2286. clientId := ""
  2287. for _, oldClient := range oldClients {
  2288. if oldClient.Email == clientEmail {
  2289. switch inbound.Protocol {
  2290. case "trojan":
  2291. clientId = oldClient.Password
  2292. case "shadowsocks":
  2293. clientId = oldClient.Email
  2294. default:
  2295. clientId = oldClient.ID
  2296. }
  2297. break
  2298. }
  2299. }
  2300. if len(clientId) == 0 {
  2301. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2302. }
  2303. var settings map[string]any
  2304. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2305. if err != nil {
  2306. return false, err
  2307. }
  2308. clients := settings["clients"].([]any)
  2309. var newClients []any
  2310. for client_index := range clients {
  2311. c := clients[client_index].(map[string]any)
  2312. if c["email"] == clientEmail {
  2313. c["tgId"] = tgId
  2314. c["updated_at"] = time.Now().Unix() * 1000
  2315. newClients = append(newClients, any(c))
  2316. }
  2317. }
  2318. settings["clients"] = newClients
  2319. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2320. if err != nil {
  2321. return false, err
  2322. }
  2323. inbound.Settings = string(modifiedSettings)
  2324. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2325. return needRestart, err
  2326. }
  2327. func (s *InboundService) checkIsEnabledByEmail(clientEmail string) (bool, error) {
  2328. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2329. if err != nil {
  2330. return false, err
  2331. }
  2332. if inbound == nil {
  2333. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2334. }
  2335. clients, err := s.GetClients(inbound)
  2336. if err != nil {
  2337. return false, err
  2338. }
  2339. isEnable := false
  2340. for _, client := range clients {
  2341. if client.Email == clientEmail {
  2342. isEnable = client.Enable
  2343. break
  2344. }
  2345. }
  2346. return isEnable, err
  2347. }
  2348. func (s *InboundService) ToggleClientEnableByEmail(clientEmail string) (bool, bool, error) {
  2349. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2350. if err != nil {
  2351. return false, false, err
  2352. }
  2353. if inbound == nil {
  2354. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2355. }
  2356. oldClients, err := s.GetClients(inbound)
  2357. if err != nil {
  2358. return false, false, err
  2359. }
  2360. clientId := ""
  2361. clientOldEnabled := false
  2362. for _, oldClient := range oldClients {
  2363. if oldClient.Email == clientEmail {
  2364. switch inbound.Protocol {
  2365. case "trojan":
  2366. clientId = oldClient.Password
  2367. case "shadowsocks":
  2368. clientId = oldClient.Email
  2369. default:
  2370. clientId = oldClient.ID
  2371. }
  2372. clientOldEnabled = oldClient.Enable
  2373. break
  2374. }
  2375. }
  2376. if len(clientId) == 0 {
  2377. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  2378. }
  2379. var settings map[string]any
  2380. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2381. if err != nil {
  2382. return false, false, err
  2383. }
  2384. clients := settings["clients"].([]any)
  2385. var newClients []any
  2386. for client_index := range clients {
  2387. c := clients[client_index].(map[string]any)
  2388. if c["email"] == clientEmail {
  2389. c["enable"] = !clientOldEnabled
  2390. c["updated_at"] = time.Now().Unix() * 1000
  2391. newClients = append(newClients, any(c))
  2392. }
  2393. }
  2394. settings["clients"] = newClients
  2395. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2396. if err != nil {
  2397. return false, false, err
  2398. }
  2399. inbound.Settings = string(modifiedSettings)
  2400. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2401. if err != nil {
  2402. return false, needRestart, err
  2403. }
  2404. return !clientOldEnabled, needRestart, nil
  2405. }
  2406. // SetClientEnableByEmail sets client enable state to desired value; returns (changed, needRestart, error)
  2407. func (s *InboundService) SetClientEnableByEmail(clientEmail string, enable bool) (bool, bool, error) {
  2408. current, err := s.checkIsEnabledByEmail(clientEmail)
  2409. if err != nil {
  2410. return false, false, err
  2411. }
  2412. if current == enable {
  2413. return false, false, nil
  2414. }
  2415. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(clientEmail)
  2416. if err != nil {
  2417. return false, needRestart, err
  2418. }
  2419. return newEnabled == enable, needRestart, nil
  2420. }
  2421. func (s *InboundService) ResetClientIpLimitByEmail(clientEmail string, count int) (bool, error) {
  2422. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2423. if err != nil {
  2424. return false, err
  2425. }
  2426. if inbound == nil {
  2427. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2428. }
  2429. oldClients, err := s.GetClients(inbound)
  2430. if err != nil {
  2431. return false, err
  2432. }
  2433. clientId := ""
  2434. for _, oldClient := range oldClients {
  2435. if oldClient.Email == clientEmail {
  2436. switch inbound.Protocol {
  2437. case "trojan":
  2438. clientId = oldClient.Password
  2439. case "shadowsocks":
  2440. clientId = oldClient.Email
  2441. default:
  2442. clientId = oldClient.ID
  2443. }
  2444. break
  2445. }
  2446. }
  2447. if len(clientId) == 0 {
  2448. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2449. }
  2450. var settings map[string]any
  2451. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2452. if err != nil {
  2453. return false, err
  2454. }
  2455. clients := settings["clients"].([]any)
  2456. var newClients []any
  2457. for client_index := range clients {
  2458. c := clients[client_index].(map[string]any)
  2459. if c["email"] == clientEmail {
  2460. c["limitIp"] = count
  2461. c["updated_at"] = time.Now().Unix() * 1000
  2462. newClients = append(newClients, any(c))
  2463. }
  2464. }
  2465. settings["clients"] = newClients
  2466. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2467. if err != nil {
  2468. return false, err
  2469. }
  2470. inbound.Settings = string(modifiedSettings)
  2471. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2472. return needRestart, err
  2473. }
  2474. func (s *InboundService) ResetClientExpiryTimeByEmail(clientEmail string, expiry_time int64) (bool, error) {
  2475. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2476. if err != nil {
  2477. return false, err
  2478. }
  2479. if inbound == nil {
  2480. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2481. }
  2482. oldClients, err := s.GetClients(inbound)
  2483. if err != nil {
  2484. return false, err
  2485. }
  2486. clientId := ""
  2487. for _, oldClient := range oldClients {
  2488. if oldClient.Email == clientEmail {
  2489. switch inbound.Protocol {
  2490. case "trojan":
  2491. clientId = oldClient.Password
  2492. case "shadowsocks":
  2493. clientId = oldClient.Email
  2494. default:
  2495. clientId = oldClient.ID
  2496. }
  2497. break
  2498. }
  2499. }
  2500. if len(clientId) == 0 {
  2501. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2502. }
  2503. var settings map[string]any
  2504. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2505. if err != nil {
  2506. return false, err
  2507. }
  2508. clients := settings["clients"].([]any)
  2509. var newClients []any
  2510. for client_index := range clients {
  2511. c := clients[client_index].(map[string]any)
  2512. if c["email"] == clientEmail {
  2513. c["expiryTime"] = expiry_time
  2514. c["updated_at"] = time.Now().Unix() * 1000
  2515. newClients = append(newClients, any(c))
  2516. }
  2517. }
  2518. settings["clients"] = newClients
  2519. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2520. if err != nil {
  2521. return false, err
  2522. }
  2523. inbound.Settings = string(modifiedSettings)
  2524. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2525. return needRestart, err
  2526. }
  2527. func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, totalGB int) (bool, error) {
  2528. if totalGB < 0 {
  2529. return false, common.NewError("totalGB must be >= 0")
  2530. }
  2531. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2532. if err != nil {
  2533. return false, err
  2534. }
  2535. if inbound == nil {
  2536. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2537. }
  2538. oldClients, err := s.GetClients(inbound)
  2539. if err != nil {
  2540. return false, err
  2541. }
  2542. clientId := ""
  2543. for _, oldClient := range oldClients {
  2544. if oldClient.Email == clientEmail {
  2545. switch inbound.Protocol {
  2546. case "trojan":
  2547. clientId = oldClient.Password
  2548. case "shadowsocks":
  2549. clientId = oldClient.Email
  2550. default:
  2551. clientId = oldClient.ID
  2552. }
  2553. break
  2554. }
  2555. }
  2556. if len(clientId) == 0 {
  2557. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2558. }
  2559. var settings map[string]any
  2560. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2561. if err != nil {
  2562. return false, err
  2563. }
  2564. clients := settings["clients"].([]any)
  2565. var newClients []any
  2566. for client_index := range clients {
  2567. c := clients[client_index].(map[string]any)
  2568. if c["email"] == clientEmail {
  2569. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  2570. c["updated_at"] = time.Now().Unix() * 1000
  2571. newClients = append(newClients, any(c))
  2572. }
  2573. }
  2574. settings["clients"] = newClients
  2575. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2576. if err != nil {
  2577. return false, err
  2578. }
  2579. inbound.Settings = string(modifiedSettings)
  2580. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2581. return needRestart, err
  2582. }
  2583. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  2584. return submitTrafficWrite(func() error {
  2585. db := database.GetDB()
  2586. return db.Model(xray.ClientTraffic{}).
  2587. Where("email = ?", clientEmail).
  2588. Updates(map[string]any{"enable": true, "up": 0, "down": 0}).Error
  2589. })
  2590. }
  2591. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (needRestart bool, err error) {
  2592. err = submitTrafficWrite(func() error {
  2593. var inner error
  2594. needRestart, inner = s.resetClientTrafficLocked(id, clientEmail)
  2595. return inner
  2596. })
  2597. return
  2598. }
  2599. func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (bool, error) {
  2600. needRestart := false
  2601. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  2602. if err != nil {
  2603. return false, err
  2604. }
  2605. if !traffic.Enable {
  2606. inbound, err := s.GetInbound(id)
  2607. if err != nil {
  2608. return false, err
  2609. }
  2610. clients, err := s.GetClients(inbound)
  2611. if err != nil {
  2612. return false, err
  2613. }
  2614. for _, client := range clients {
  2615. if client.Email == clientEmail && client.Enable {
  2616. rt, rterr := s.runtimeFor(inbound)
  2617. if rterr != nil {
  2618. if inbound.NodeID != nil {
  2619. return false, rterr
  2620. }
  2621. needRestart = true
  2622. break
  2623. }
  2624. cipher := ""
  2625. if string(inbound.Protocol) == "shadowsocks" {
  2626. var oldSettings map[string]any
  2627. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  2628. if err != nil {
  2629. return false, err
  2630. }
  2631. cipher = oldSettings["method"].(string)
  2632. }
  2633. err1 := rt.AddUser(context.Background(), inbound, map[string]any{
  2634. "email": client.Email,
  2635. "id": client.ID,
  2636. "auth": client.Auth,
  2637. "security": client.Security,
  2638. "flow": client.Flow,
  2639. "password": client.Password,
  2640. "cipher": cipher,
  2641. })
  2642. if err1 == nil {
  2643. logger.Debug("Client enabled on", rt.Name(), "due to reset traffic:", clientEmail)
  2644. } else {
  2645. logger.Debug("Error in enabling client on", rt.Name(), ":", err1)
  2646. needRestart = true
  2647. }
  2648. break
  2649. }
  2650. }
  2651. }
  2652. traffic.Up = 0
  2653. traffic.Down = 0
  2654. traffic.Enable = true
  2655. db := database.GetDB()
  2656. err = db.Save(traffic).Error
  2657. if err != nil {
  2658. return false, err
  2659. }
  2660. now := time.Now().UnixMilli()
  2661. _ = db.Model(model.Inbound{}).
  2662. Where("id = ?", id).
  2663. Update("last_traffic_reset_time", now).Error
  2664. inbound, err := s.GetInbound(id)
  2665. if err == nil && inbound != nil && inbound.NodeID != nil {
  2666. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  2667. if e := rt.ResetClientTraffic(context.Background(), inbound, clientEmail); e != nil {
  2668. logger.Warning("ResetClientTraffic: remote propagation to", rt.Name(), "failed:", e)
  2669. }
  2670. } else {
  2671. logger.Warning("ResetClientTraffic: runtime lookup failed:", rterr)
  2672. }
  2673. }
  2674. return needRestart, nil
  2675. }
  2676. func (s *InboundService) ResetAllClientTraffics(id int) error {
  2677. return submitTrafficWrite(func() error {
  2678. return s.resetAllClientTrafficsLocked(id)
  2679. })
  2680. }
  2681. func (s *InboundService) resetAllClientTrafficsLocked(id int) error {
  2682. db := database.GetDB()
  2683. now := time.Now().Unix() * 1000
  2684. if err := db.Transaction(func(tx *gorm.DB) error {
  2685. whereText := "inbound_id "
  2686. if id == -1 {
  2687. whereText += " > ?"
  2688. } else {
  2689. whereText += " = ?"
  2690. }
  2691. // Reset client traffics
  2692. result := tx.Model(xray.ClientTraffic{}).
  2693. Where(whereText, id).
  2694. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  2695. if result.Error != nil {
  2696. return result.Error
  2697. }
  2698. // Update lastTrafficResetTime for the inbound(s)
  2699. inboundWhereText := "id "
  2700. if id == -1 {
  2701. inboundWhereText += " > ?"
  2702. } else {
  2703. inboundWhereText += " = ?"
  2704. }
  2705. result = tx.Model(model.Inbound{}).
  2706. Where(inboundWhereText, id).
  2707. Update("last_traffic_reset_time", now)
  2708. return result.Error
  2709. }); err != nil {
  2710. return err
  2711. }
  2712. var inbounds []model.Inbound
  2713. q := db.Model(model.Inbound{}).Where("node_id IS NOT NULL")
  2714. if id != -1 {
  2715. q = q.Where("id = ?", id)
  2716. }
  2717. if err := q.Find(&inbounds).Error; err != nil {
  2718. logger.Warning("ResetAllClientTraffics: discover node inbounds failed:", err)
  2719. return nil
  2720. }
  2721. for i := range inbounds {
  2722. ib := &inbounds[i]
  2723. rt, rterr := s.runtimeFor(ib)
  2724. if rterr != nil {
  2725. logger.Warning("ResetAllClientTraffics: runtime lookup for inbound", ib.Id, "failed:", rterr)
  2726. continue
  2727. }
  2728. if e := rt.ResetInboundClientTraffics(context.Background(), ib); e != nil {
  2729. logger.Warning("ResetAllClientTraffics: remote propagation to", rt.Name(), "failed:", e)
  2730. }
  2731. }
  2732. return nil
  2733. }
  2734. func (s *InboundService) ResetAllTraffics() error {
  2735. return submitTrafficWrite(func() error {
  2736. return s.resetAllTrafficsLocked()
  2737. })
  2738. }
  2739. func (s *InboundService) resetAllTrafficsLocked() error {
  2740. db := database.GetDB()
  2741. now := time.Now().UnixMilli()
  2742. if err := db.Model(model.Inbound{}).
  2743. Where("user_id > ?", 0).
  2744. Updates(map[string]any{
  2745. "up": 0,
  2746. "down": 0,
  2747. "last_traffic_reset_time": now,
  2748. }).Error; err != nil {
  2749. return err
  2750. }
  2751. var inbounds []model.Inbound
  2752. if err := db.Model(model.Inbound{}).
  2753. Where("node_id IS NOT NULL").
  2754. Find(&inbounds).Error; err != nil {
  2755. logger.Warning("ResetAllTraffics: discover node inbounds failed:", err)
  2756. return nil
  2757. }
  2758. for i := range inbounds {
  2759. ib := &inbounds[i]
  2760. rt, rterr := s.runtimeFor(ib)
  2761. if rterr != nil {
  2762. logger.Warning("ResetAllTraffics: runtime lookup for inbound", ib.Id, "failed:", rterr)
  2763. continue
  2764. }
  2765. if e := rt.ResetInboundClientTraffics(context.Background(), ib); e != nil {
  2766. logger.Warning("ResetAllTraffics: remote propagation to", rt.Name(), "failed:", e)
  2767. }
  2768. }
  2769. return nil
  2770. }
  2771. func (s *InboundService) ResetInboundTraffic(id int) error {
  2772. return submitTrafficWrite(func() error {
  2773. db := database.GetDB()
  2774. return db.Model(model.Inbound{}).
  2775. Where("id = ?", id).
  2776. Updates(map[string]any{"up": 0, "down": 0}).Error
  2777. })
  2778. }
  2779. func (s *InboundService) DelDepletedClients(id int) (err error) {
  2780. db := database.GetDB()
  2781. tx := db.Begin()
  2782. defer func() {
  2783. if err == nil {
  2784. tx.Commit()
  2785. } else {
  2786. tx.Rollback()
  2787. }
  2788. }()
  2789. // Collect depleted emails globally — a shared-email row owned by one
  2790. // inbound depletes every sibling that lists the email.
  2791. now := time.Now().Unix() * 1000
  2792. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  2793. var depletedRows []xray.ClientTraffic
  2794. err = db.Model(xray.ClientTraffic{}).
  2795. Where(depletedClause, now).
  2796. Find(&depletedRows).Error
  2797. if err != nil {
  2798. return err
  2799. }
  2800. if len(depletedRows) == 0 {
  2801. return nil
  2802. }
  2803. depletedEmails := make(map[string]struct{}, len(depletedRows))
  2804. for _, r := range depletedRows {
  2805. if r.Email == "" {
  2806. continue
  2807. }
  2808. depletedEmails[strings.ToLower(r.Email)] = struct{}{}
  2809. }
  2810. if len(depletedEmails) == 0 {
  2811. return nil
  2812. }
  2813. var inbounds []*model.Inbound
  2814. inboundQuery := db.Model(model.Inbound{})
  2815. if id >= 0 {
  2816. inboundQuery = inboundQuery.Where("id = ?", id)
  2817. }
  2818. if err = inboundQuery.Find(&inbounds).Error; err != nil {
  2819. return err
  2820. }
  2821. for _, inbound := range inbounds {
  2822. var settings map[string]any
  2823. if err = json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2824. return err
  2825. }
  2826. rawClients, ok := settings["clients"].([]any)
  2827. if !ok {
  2828. continue
  2829. }
  2830. newClients := make([]any, 0, len(rawClients))
  2831. removed := 0
  2832. for _, client := range rawClients {
  2833. c, ok := client.(map[string]any)
  2834. if !ok {
  2835. newClients = append(newClients, client)
  2836. continue
  2837. }
  2838. email, _ := c["email"].(string)
  2839. if _, isDepleted := depletedEmails[strings.ToLower(email)]; isDepleted {
  2840. removed++
  2841. continue
  2842. }
  2843. newClients = append(newClients, client)
  2844. }
  2845. if removed == 0 {
  2846. continue
  2847. }
  2848. if len(newClients) == 0 {
  2849. s.DelInbound(inbound.Id)
  2850. continue
  2851. }
  2852. settings["clients"] = newClients
  2853. ns, mErr := json.MarshalIndent(settings, "", " ")
  2854. if mErr != nil {
  2855. return mErr
  2856. }
  2857. inbound.Settings = string(ns)
  2858. if err = tx.Save(inbound).Error; err != nil {
  2859. return err
  2860. }
  2861. }
  2862. // Drop now-orphaned rows. With id >= 0, a row is safe to drop only when
  2863. // no out-of-scope inbound still references the email.
  2864. if id < 0 {
  2865. err = tx.Where(depletedClause, now).Delete(xray.ClientTraffic{}).Error
  2866. return err
  2867. }
  2868. emails := make([]string, 0, len(depletedEmails))
  2869. for e := range depletedEmails {
  2870. emails = append(emails, e)
  2871. }
  2872. var stillReferenced []string
  2873. if err = tx.Raw(`
  2874. SELECT DISTINCT LOWER(JSON_EXTRACT(client.value, '$.email'))
  2875. FROM inbounds,
  2876. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  2877. WHERE LOWER(JSON_EXTRACT(client.value, '$.email')) IN ?
  2878. `, emails).Scan(&stillReferenced).Error; err != nil {
  2879. return err
  2880. }
  2881. stillSet := make(map[string]struct{}, len(stillReferenced))
  2882. for _, e := range stillReferenced {
  2883. stillSet[e] = struct{}{}
  2884. }
  2885. toDelete := make([]string, 0, len(emails))
  2886. for _, e := range emails {
  2887. if _, kept := stillSet[e]; !kept {
  2888. toDelete = append(toDelete, e)
  2889. }
  2890. }
  2891. if len(toDelete) > 0 {
  2892. if err = tx.Where("LOWER(email) IN ?", toDelete).Delete(xray.ClientTraffic{}).Error; err != nil {
  2893. return err
  2894. }
  2895. }
  2896. return nil
  2897. }
  2898. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  2899. db := database.GetDB()
  2900. var inbounds []*model.Inbound
  2901. // Retrieve inbounds where settings contain the given tgId
  2902. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  2903. if err != nil && err != gorm.ErrRecordNotFound {
  2904. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  2905. return nil, err
  2906. }
  2907. var emails []string
  2908. for _, inbound := range inbounds {
  2909. clients, err := s.GetClients(inbound)
  2910. if err != nil {
  2911. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  2912. continue
  2913. }
  2914. for _, client := range clients {
  2915. if client.TgID == tgId {
  2916. emails = append(emails, client.Email)
  2917. }
  2918. }
  2919. }
  2920. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  2921. // account owns thousands of clients across inbounds.
  2922. uniqEmails := uniqueNonEmptyStrings(emails)
  2923. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  2924. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  2925. var page []*xray.ClientTraffic
  2926. if err = db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  2927. if err == gorm.ErrRecordNotFound {
  2928. continue
  2929. }
  2930. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  2931. return nil, err
  2932. }
  2933. traffics = append(traffics, page...)
  2934. }
  2935. if len(traffics) == 0 {
  2936. logger.Warning("No ClientTraffic records found for emails:", emails)
  2937. return nil, nil
  2938. }
  2939. // Populate UUID and other client data for each traffic record
  2940. for i := range traffics {
  2941. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  2942. traffics[i].Enable = client.Enable
  2943. traffics[i].UUID = client.ID
  2944. traffics[i].SubId = client.SubID
  2945. }
  2946. }
  2947. return traffics, nil
  2948. }
  2949. // sqliteMaxVars is a safe ceiling for the number of bind parameters in a
  2950. // single SQL statement. SQLite's SQLITE_MAX_VARIABLE_NUMBER is 999 on builds
  2951. // before 3.32 and 32766 after; staying under 999 keeps queries portable
  2952. // across forks/old binaries and also bounds per-query memory on truly large
  2953. // installs (>32k clients) where even modern SQLite would refuse a single IN.
  2954. const sqliteMaxVars = 900
  2955. // uniqueNonEmptyStrings returns a deduplicated copy of in with empty strings
  2956. // removed, preserving the order of first occurrence.
  2957. func uniqueNonEmptyStrings(in []string) []string {
  2958. if len(in) == 0 {
  2959. return nil
  2960. }
  2961. seen := make(map[string]struct{}, len(in))
  2962. out := make([]string, 0, len(in))
  2963. for _, v := range in {
  2964. if v == "" {
  2965. continue
  2966. }
  2967. if _, ok := seen[v]; ok {
  2968. continue
  2969. }
  2970. seen[v] = struct{}{}
  2971. out = append(out, v)
  2972. }
  2973. return out
  2974. }
  2975. // uniqueInts returns a deduplicated copy of in, preserving order of first occurrence.
  2976. func uniqueInts(in []int) []int {
  2977. if len(in) == 0 {
  2978. return nil
  2979. }
  2980. seen := make(map[int]struct{}, len(in))
  2981. out := make([]int, 0, len(in))
  2982. for _, v := range in {
  2983. if _, ok := seen[v]; ok {
  2984. continue
  2985. }
  2986. seen[v] = struct{}{}
  2987. out = append(out, v)
  2988. }
  2989. return out
  2990. }
  2991. // chunkStrings splits s into consecutive sub-slices of at most size elements.
  2992. // Returns nil for an empty input or non-positive size.
  2993. func chunkStrings(s []string, size int) [][]string {
  2994. if size <= 0 || len(s) == 0 {
  2995. return nil
  2996. }
  2997. out := make([][]string, 0, (len(s)+size-1)/size)
  2998. for i := 0; i < len(s); i += size {
  2999. end := i + size
  3000. if end > len(s) {
  3001. end = len(s)
  3002. }
  3003. out = append(out, s[i:end])
  3004. }
  3005. return out
  3006. }
  3007. // chunkInts splits s into consecutive sub-slices of at most size elements.
  3008. // Returns nil for an empty input or non-positive size.
  3009. func chunkInts(s []int, size int) [][]int {
  3010. if size <= 0 || len(s) == 0 {
  3011. return nil
  3012. }
  3013. out := make([][]int, 0, (len(s)+size-1)/size)
  3014. for i := 0; i < len(s); i += size {
  3015. end := i + size
  3016. if end > len(s) {
  3017. end = len(s)
  3018. }
  3019. out = append(out, s[i:end])
  3020. }
  3021. return out
  3022. }
  3023. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  3024. uniq := uniqueNonEmptyStrings(emails)
  3025. if len(uniq) == 0 {
  3026. return nil, nil
  3027. }
  3028. db := database.GetDB()
  3029. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  3030. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  3031. var page []*xray.ClientTraffic
  3032. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  3033. return nil, err
  3034. }
  3035. traffics = append(traffics, page...)
  3036. }
  3037. return traffics, nil
  3038. }
  3039. type InboundTrafficSummary struct {
  3040. Id int `json:"id"`
  3041. Up int64 `json:"up"`
  3042. Down int64 `json:"down"`
  3043. Total int64 `json:"total"`
  3044. AllTime int64 `json:"allTime"`
  3045. Enable bool `json:"enable"`
  3046. }
  3047. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  3048. db := database.GetDB()
  3049. var summaries []InboundTrafficSummary
  3050. if err := db.Model(&model.Inbound{}).
  3051. Select("id, up, down, total, all_time, enable").
  3052. Find(&summaries).Error; err != nil {
  3053. return nil, err
  3054. }
  3055. return summaries, nil
  3056. }
  3057. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  3058. // Prefer retrieving along with client to reflect actual enabled state from inbound settings
  3059. t, client, err := s.GetClientByEmail(email)
  3060. if err != nil {
  3061. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  3062. return nil, err
  3063. }
  3064. if t != nil && client != nil {
  3065. t.UUID = client.ID
  3066. t.SubId = client.SubID
  3067. return t, nil
  3068. }
  3069. return nil, nil
  3070. }
  3071. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  3072. return submitTrafficWrite(func() error {
  3073. db := database.GetDB()
  3074. err := db.Model(xray.ClientTraffic{}).
  3075. Where("email = ?", email).
  3076. Updates(map[string]any{
  3077. "up": upload,
  3078. "down": download,
  3079. "all_time": gorm.Expr("CASE WHEN COALESCE(all_time, 0) < ? THEN ? ELSE all_time END", upload+download, upload+download),
  3080. }).Error
  3081. if err != nil {
  3082. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  3083. }
  3084. return err
  3085. })
  3086. }
  3087. func (s *InboundService) GetClientTrafficByID(id string) ([]xray.ClientTraffic, error) {
  3088. db := database.GetDB()
  3089. var traffics []xray.ClientTraffic
  3090. err := db.Model(xray.ClientTraffic{}).Where(`email IN(
  3091. SELECT JSON_EXTRACT(client.value, '$.email') as email
  3092. FROM inbounds,
  3093. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  3094. WHERE
  3095. JSON_EXTRACT(client.value, '$.id') in (?)
  3096. )`, id).Find(&traffics).Error
  3097. if err != nil {
  3098. logger.Debug(err)
  3099. return nil, err
  3100. }
  3101. // Reconcile enable flag with client settings per email to avoid stale DB value
  3102. for i := range traffics {
  3103. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  3104. traffics[i].Enable = client.Enable
  3105. traffics[i].UUID = client.ID
  3106. traffics[i].SubId = client.SubID
  3107. }
  3108. }
  3109. return traffics, err
  3110. }
  3111. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  3112. db := database.GetDB()
  3113. inbound := &model.Inbound{}
  3114. traffic = &xray.ClientTraffic{}
  3115. // Search for inbound settings that contain the query
  3116. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  3117. if err != nil {
  3118. if err == gorm.ErrRecordNotFound {
  3119. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  3120. return nil, err
  3121. }
  3122. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  3123. return nil, err
  3124. }
  3125. traffic.InboundId = inbound.Id
  3126. // Unmarshal settings to get clients
  3127. settings := map[string][]model.Client{}
  3128. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  3129. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  3130. return nil, err
  3131. }
  3132. clients := settings["clients"]
  3133. for _, client := range clients {
  3134. if (client.ID == query || client.Password == query) && client.Email != "" {
  3135. traffic.Email = client.Email
  3136. break
  3137. }
  3138. }
  3139. if traffic.Email == "" {
  3140. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  3141. return nil, gorm.ErrRecordNotFound
  3142. }
  3143. // Retrieve ClientTraffic based on the found email
  3144. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  3145. if err != nil {
  3146. if err == gorm.ErrRecordNotFound {
  3147. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  3148. return nil, err
  3149. }
  3150. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  3151. return nil, err
  3152. }
  3153. return traffic, nil
  3154. }
  3155. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  3156. db := database.GetDB()
  3157. InboundClientIps := &model.InboundClientIps{}
  3158. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  3159. if err != nil {
  3160. return "", err
  3161. }
  3162. if InboundClientIps.Ips == "" {
  3163. return "", nil
  3164. }
  3165. // Try to parse as new format (with timestamps)
  3166. type IPWithTimestamp struct {
  3167. IP string `json:"ip"`
  3168. Timestamp int64 `json:"timestamp"`
  3169. }
  3170. var ipsWithTime []IPWithTimestamp
  3171. err = json.Unmarshal([]byte(InboundClientIps.Ips), &ipsWithTime)
  3172. // If successfully parsed as new format, return with timestamps
  3173. if err == nil && len(ipsWithTime) > 0 {
  3174. return InboundClientIps.Ips, nil
  3175. }
  3176. // Otherwise, assume it's old format (simple string array)
  3177. // Try to parse as simple array and convert to new format
  3178. var oldIps []string
  3179. err = json.Unmarshal([]byte(InboundClientIps.Ips), &oldIps)
  3180. if err == nil && len(oldIps) > 0 {
  3181. // Convert old format to new format with current timestamp
  3182. newIpsWithTime := make([]IPWithTimestamp, len(oldIps))
  3183. for i, ip := range oldIps {
  3184. newIpsWithTime[i] = IPWithTimestamp{
  3185. IP: ip,
  3186. Timestamp: time.Now().Unix(),
  3187. }
  3188. }
  3189. result, _ := json.Marshal(newIpsWithTime)
  3190. return string(result), nil
  3191. }
  3192. // Return as-is if parsing fails
  3193. return InboundClientIps.Ips, nil
  3194. }
  3195. func (s *InboundService) ClearClientIps(clientEmail string) error {
  3196. db := database.GetDB()
  3197. result := db.Model(model.InboundClientIps{}).
  3198. Where("client_email = ?", clientEmail).
  3199. Update("ips", "")
  3200. err := result.Error
  3201. if err != nil {
  3202. return err
  3203. }
  3204. return nil
  3205. }
  3206. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  3207. db := database.GetDB()
  3208. var inbounds []*model.Inbound
  3209. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  3210. if err != nil && err != gorm.ErrRecordNotFound {
  3211. return nil, err
  3212. }
  3213. return inbounds, nil
  3214. }
  3215. func (s *InboundService) MigrationRequirements() {
  3216. db := database.GetDB()
  3217. tx := db.Begin()
  3218. var err error
  3219. defer func() {
  3220. if err == nil {
  3221. tx.Commit()
  3222. if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
  3223. logger.Warningf("VACUUM failed: %v", dbErr)
  3224. }
  3225. } else {
  3226. tx.Rollback()
  3227. }
  3228. }()
  3229. // Calculate and backfill all_time from up+down for inbounds and clients
  3230. err = tx.Exec(`
  3231. UPDATE inbounds
  3232. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  3233. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  3234. `).Error
  3235. if err != nil {
  3236. return
  3237. }
  3238. err = tx.Exec(`
  3239. UPDATE client_traffics
  3240. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  3241. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  3242. `).Error
  3243. if err != nil {
  3244. return
  3245. }
  3246. // Fix inbounds based problems
  3247. var inbounds []*model.Inbound
  3248. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan"}).Find(&inbounds).Error
  3249. if err != nil && err != gorm.ErrRecordNotFound {
  3250. return
  3251. }
  3252. for inbound_index := range inbounds {
  3253. settings := map[string]any{}
  3254. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  3255. clients, ok := settings["clients"].([]any)
  3256. if ok {
  3257. // Fix Client configuration problems
  3258. var newClients []any
  3259. hasVisionFlow := false
  3260. for client_index := range clients {
  3261. c := clients[client_index].(map[string]any)
  3262. // Add email='' if it is not exists
  3263. if _, ok := c["email"]; !ok {
  3264. c["email"] = ""
  3265. }
  3266. // Convert string tgId to int64
  3267. if _, ok := c["tgId"]; ok {
  3268. var tgId any = c["tgId"]
  3269. if tgIdStr, ok2 := tgId.(string); ok2 {
  3270. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  3271. if err == nil {
  3272. c["tgId"] = tgIdInt64
  3273. }
  3274. }
  3275. }
  3276. // Remove "flow": "xtls-rprx-direct"
  3277. if _, ok := c["flow"]; ok {
  3278. if c["flow"] == "xtls-rprx-direct" {
  3279. c["flow"] = ""
  3280. }
  3281. }
  3282. if flow, _ := c["flow"].(string); flow == "xtls-rprx-vision" {
  3283. hasVisionFlow = true
  3284. }
  3285. // Backfill created_at and updated_at
  3286. if _, ok := c["created_at"]; !ok {
  3287. c["created_at"] = time.Now().Unix() * 1000
  3288. }
  3289. c["updated_at"] = time.Now().Unix() * 1000
  3290. newClients = append(newClients, any(c))
  3291. }
  3292. settings["clients"] = newClients
  3293. // Drop orphaned testseed: VLESS-only field, only meaningful when at least
  3294. // one client uses the exact xtls-rprx-vision flow. Older versions saved it
  3295. // for any non-empty flow (including the UDP variant) or kept it after the
  3296. // flow was cleared from the client modal — clean those up here.
  3297. if inbounds[inbound_index].Protocol == model.VLESS && !hasVisionFlow {
  3298. delete(settings, "testseed")
  3299. }
  3300. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  3301. if err != nil {
  3302. return
  3303. }
  3304. inbounds[inbound_index].Settings = string(modifiedSettings)
  3305. }
  3306. // Add client traffic row for all clients which has email
  3307. modelClients, err := s.GetClients(inbounds[inbound_index])
  3308. if err != nil {
  3309. return
  3310. }
  3311. for _, modelClient := range modelClients {
  3312. if len(modelClient.Email) > 0 {
  3313. var count int64
  3314. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  3315. if count == 0 {
  3316. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  3317. }
  3318. }
  3319. }
  3320. }
  3321. tx.Save(inbounds)
  3322. // Remove orphaned traffics
  3323. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  3324. // Migrate old MultiDomain to External Proxy
  3325. var externalProxy []struct {
  3326. Id int
  3327. Port int
  3328. StreamSettings []byte
  3329. }
  3330. err = tx.Raw(`select id, port, stream_settings
  3331. from inbounds
  3332. WHERE protocol in ('vmess','vless','trojan')
  3333. AND json_extract(stream_settings, '$.security') = 'tls'
  3334. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  3335. if err != nil || len(externalProxy) == 0 {
  3336. return
  3337. }
  3338. for _, ep := range externalProxy {
  3339. var reverses any
  3340. var stream map[string]any
  3341. json.Unmarshal(ep.StreamSettings, &stream)
  3342. if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
  3343. if settings, ok := tlsSettings["settings"].(map[string]any); ok {
  3344. if domains, ok := settings["domains"].([]any); ok {
  3345. for _, domain := range domains {
  3346. if domainMap, ok := domain.(map[string]any); ok {
  3347. domainMap["forceTls"] = "same"
  3348. domainMap["port"] = ep.Port
  3349. domainMap["dest"] = domainMap["domain"].(string)
  3350. delete(domainMap, "domain")
  3351. }
  3352. }
  3353. }
  3354. reverses = settings["domains"]
  3355. delete(settings, "domains")
  3356. }
  3357. }
  3358. stream["externalProxy"] = reverses
  3359. newStream, _ := json.MarshalIndent(stream, " ", " ")
  3360. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  3361. }
  3362. err = tx.Raw(`UPDATE inbounds
  3363. SET tag = REPLACE(tag, '0.0.0.0:', '')
  3364. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  3365. if err != nil {
  3366. return
  3367. }
  3368. }
  3369. func (s *InboundService) MigrateDB() {
  3370. s.MigrationRequirements()
  3371. s.MigrationRemoveOrphanedTraffics()
  3372. }
  3373. func (s *InboundService) GetOnlineClients() []string {
  3374. return p.GetOnlineClients()
  3375. }
  3376. func (s *InboundService) SetNodeOnlineClients(nodeID int, emails []string) {
  3377. if p != nil {
  3378. p.SetNodeOnlineClients(nodeID, emails)
  3379. }
  3380. }
  3381. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  3382. if p != nil {
  3383. p.ClearNodeOnlineClients(nodeID)
  3384. }
  3385. }
  3386. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  3387. db := database.GetDB()
  3388. var rows []xray.ClientTraffic
  3389. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  3390. if err != nil && err != gorm.ErrRecordNotFound {
  3391. return nil, err
  3392. }
  3393. result := make(map[string]int64, len(rows))
  3394. for _, r := range rows {
  3395. result[r.Email] = r.LastOnline
  3396. }
  3397. return result, nil
  3398. }
  3399. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  3400. db := database.GetDB()
  3401. // Step 1: Get ClientTraffic records for emails in the input list.
  3402. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  3403. uniqEmails := uniqueNonEmptyStrings(emails)
  3404. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  3405. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  3406. var page []xray.ClientTraffic
  3407. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && err != gorm.ErrRecordNotFound {
  3408. return nil, nil, err
  3409. }
  3410. clients = append(clients, page...)
  3411. }
  3412. // Step 2: Sort clients by (Up + Down) descending
  3413. sort.Slice(clients, func(i, j int) bool {
  3414. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  3415. })
  3416. // Step 3: Extract sorted valid emails and track found ones
  3417. validEmails := make([]string, 0, len(clients))
  3418. found := make(map[string]bool)
  3419. for _, client := range clients {
  3420. validEmails = append(validEmails, client.Email)
  3421. found[client.Email] = true
  3422. }
  3423. // Step 4: Identify emails that were not found in the database
  3424. extraEmails := make([]string, 0)
  3425. for _, email := range emails {
  3426. if !found[email] {
  3427. extraEmails = append(extraEmails, email)
  3428. }
  3429. }
  3430. return validEmails, extraEmails, nil
  3431. }
  3432. func (s *InboundService) DelInboundClientByEmail(inboundId int, email string) (bool, error) {
  3433. oldInbound, err := s.GetInbound(inboundId)
  3434. if err != nil {
  3435. logger.Error("Load Old Data Error")
  3436. return false, err
  3437. }
  3438. var settings map[string]any
  3439. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  3440. return false, err
  3441. }
  3442. interfaceClients, ok := settings["clients"].([]any)
  3443. if !ok {
  3444. return false, common.NewError("invalid clients format in inbound settings")
  3445. }
  3446. var newClients []any
  3447. needApiDel := false
  3448. found := false
  3449. for _, client := range interfaceClients {
  3450. c, ok := client.(map[string]any)
  3451. if !ok {
  3452. continue
  3453. }
  3454. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  3455. // matched client, drop it
  3456. found = true
  3457. needApiDel, _ = c["enable"].(bool)
  3458. } else {
  3459. newClients = append(newClients, client)
  3460. }
  3461. }
  3462. if !found {
  3463. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  3464. }
  3465. if len(newClients) == 0 {
  3466. return false, common.NewError("no client remained in Inbound")
  3467. }
  3468. settings["clients"] = newClients
  3469. newSettings, err := json.MarshalIndent(settings, "", " ")
  3470. if err != nil {
  3471. return false, err
  3472. }
  3473. oldInbound.Settings = string(newSettings)
  3474. db := database.GetDB()
  3475. // Drop the row and IPs only when this was the last inbound referencing
  3476. // the email — siblings still need the shared accounting state.
  3477. emailShared, err := s.emailUsedByOtherInbounds(email, inboundId)
  3478. if err != nil {
  3479. return false, err
  3480. }
  3481. if !emailShared {
  3482. if err := s.DelClientIPs(db, email); err != nil {
  3483. logger.Error("Error in delete client IPs")
  3484. return false, err
  3485. }
  3486. }
  3487. needRestart := false
  3488. // remove stats too
  3489. if len(email) > 0 && !emailShared {
  3490. traffic, err := s.GetClientTrafficByEmail(email)
  3491. if err != nil {
  3492. return false, err
  3493. }
  3494. if traffic != nil {
  3495. if err := s.DelClientStat(db, email); err != nil {
  3496. logger.Error("Delete stats Data Error")
  3497. return false, err
  3498. }
  3499. }
  3500. if needApiDel {
  3501. rt, rterr := s.runtimeFor(oldInbound)
  3502. if rterr != nil {
  3503. if oldInbound.NodeID != nil {
  3504. return false, rterr
  3505. }
  3506. needRestart = true
  3507. } else if oldInbound.NodeID == nil {
  3508. if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 == nil {
  3509. logger.Debug("Client deleted on", rt.Name(), ":", email)
  3510. needRestart = false
  3511. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  3512. logger.Debug("User is already deleted. Nothing to do more...")
  3513. } else {
  3514. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  3515. needRestart = true
  3516. }
  3517. } else {
  3518. if err1 := rt.UpdateInbound(context.Background(), oldInbound, oldInbound); err1 != nil {
  3519. return false, err1
  3520. }
  3521. }
  3522. }
  3523. }
  3524. return needRestart, db.Save(oldInbound).Error
  3525. }