inbound.go 109 KB

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