1
0

inbound.go 120 KB

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