inbound.go 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100
  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) writeBackClientSubID(sourceInboundID int, client model.Client, subID string) (bool, error) {
  1305. client.SubID = subID
  1306. client.UpdatedAt = time.Now().UnixMilli()
  1307. if client.Email == "" {
  1308. return false, common.NewError("empty client email")
  1309. }
  1310. settingsBytes, err := json.Marshal(map[string][]model.Client{
  1311. "clients": {client},
  1312. })
  1313. if err != nil {
  1314. return false, err
  1315. }
  1316. updatePayload := &model.Inbound{
  1317. Id: sourceInboundID,
  1318. Settings: string(settingsBytes),
  1319. }
  1320. return s.clientService.UpdateInboundClient(s, updatePayload, client.Email)
  1321. }
  1322. func (s *InboundService) generateRandomCredential(targetProtocol model.Protocol) string {
  1323. switch targetProtocol {
  1324. case model.VMESS, model.VLESS:
  1325. return uuid.NewString()
  1326. default:
  1327. return strings.ReplaceAll(uuid.NewString(), "-", "")
  1328. }
  1329. }
  1330. func (s *InboundService) buildTargetClientFromSource(source model.Client, targetInbound *model.Inbound, email string, flow string) (model.Client, error) {
  1331. nowTs := time.Now().UnixMilli()
  1332. target := source
  1333. target.Email = email
  1334. target.CreatedAt = nowTs
  1335. target.UpdatedAt = nowTs
  1336. target.ID = ""
  1337. target.Password = ""
  1338. target.Auth = ""
  1339. target.Flow = ""
  1340. targetProtocol := targetInbound.Protocol
  1341. switch targetProtocol {
  1342. case model.VMESS:
  1343. target.ID = s.generateRandomCredential(targetProtocol)
  1344. case model.VLESS:
  1345. target.ID = s.generateRandomCredential(targetProtocol)
  1346. if (flow == "xtls-rprx-vision" || flow == "xtls-rprx-vision-udp443") &&
  1347. inboundCanEnableTlsFlow(string(targetProtocol), targetInbound.StreamSettings) {
  1348. target.Flow = flow
  1349. }
  1350. case model.Trojan, model.Shadowsocks:
  1351. target.Password = s.generateRandomCredential(targetProtocol)
  1352. case model.Hysteria:
  1353. target.Auth = s.generateRandomCredential(targetProtocol)
  1354. default:
  1355. target.ID = s.generateRandomCredential(targetProtocol)
  1356. }
  1357. return target, nil
  1358. }
  1359. func (s *InboundService) nextAvailableCopiedEmail(originalEmail string, targetID int, occupied map[string]struct{}) string {
  1360. base := fmt.Sprintf("%s_%d", originalEmail, targetID)
  1361. candidate := base
  1362. suffix := 0
  1363. for {
  1364. if _, exists := occupied[strings.ToLower(candidate)]; !exists {
  1365. occupied[strings.ToLower(candidate)] = struct{}{}
  1366. return candidate
  1367. }
  1368. suffix++
  1369. candidate = fmt.Sprintf("%s_%d", base, suffix)
  1370. }
  1371. }
  1372. func (s *InboundService) CopyInboundClients(targetInboundID int, sourceInboundID int, clientEmails []string, flow string) (*CopyClientsResult, bool, error) {
  1373. result := &CopyClientsResult{
  1374. Added: []string{},
  1375. Skipped: []string{},
  1376. Errors: []string{},
  1377. }
  1378. if targetInboundID == sourceInboundID {
  1379. return result, false, common.NewError("source and target inbounds must be different")
  1380. }
  1381. targetInbound, err := s.GetInbound(targetInboundID)
  1382. if err != nil {
  1383. return result, false, err
  1384. }
  1385. sourceInbound, err := s.GetInbound(sourceInboundID)
  1386. if err != nil {
  1387. return result, false, err
  1388. }
  1389. sourceClients, err := s.GetClients(sourceInbound)
  1390. if err != nil {
  1391. return result, false, err
  1392. }
  1393. if len(sourceClients) == 0 {
  1394. return result, false, nil
  1395. }
  1396. allowedEmails := map[string]struct{}{}
  1397. if len(clientEmails) > 0 {
  1398. for _, email := range clientEmails {
  1399. allowedEmails[strings.ToLower(strings.TrimSpace(email))] = struct{}{}
  1400. }
  1401. }
  1402. occupiedEmails := map[string]struct{}{}
  1403. allEmails, err := s.getAllEmails()
  1404. if err != nil {
  1405. return result, false, err
  1406. }
  1407. for _, email := range allEmails {
  1408. clean := strings.Trim(email, "\"")
  1409. if clean != "" {
  1410. occupiedEmails[strings.ToLower(clean)] = struct{}{}
  1411. }
  1412. }
  1413. newClients := make([]model.Client, 0)
  1414. needRestart := false
  1415. for _, sourceClient := range sourceClients {
  1416. originalEmail := strings.TrimSpace(sourceClient.Email)
  1417. if originalEmail == "" {
  1418. continue
  1419. }
  1420. if len(allowedEmails) > 0 {
  1421. if _, ok := allowedEmails[strings.ToLower(originalEmail)]; !ok {
  1422. continue
  1423. }
  1424. }
  1425. if sourceClient.SubID == "" {
  1426. newSubID := uuid.NewString()
  1427. subNeedRestart, subErr := s.writeBackClientSubID(sourceInbound.Id, sourceClient, newSubID)
  1428. if subErr != nil {
  1429. result.Errors = append(result.Errors, fmt.Sprintf("%s: failed to write source subId: %v", originalEmail, subErr))
  1430. continue
  1431. }
  1432. if subNeedRestart {
  1433. needRestart = true
  1434. }
  1435. sourceClient.SubID = newSubID
  1436. }
  1437. targetEmail := s.nextAvailableCopiedEmail(originalEmail, targetInboundID, occupiedEmails)
  1438. targetClient, buildErr := s.buildTargetClientFromSource(sourceClient, targetInbound, targetEmail, flow)
  1439. if buildErr != nil {
  1440. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", originalEmail, buildErr))
  1441. continue
  1442. }
  1443. newClients = append(newClients, targetClient)
  1444. result.Added = append(result.Added, targetEmail)
  1445. }
  1446. if len(newClients) == 0 {
  1447. return result, needRestart, nil
  1448. }
  1449. settingsPayload, err := json.Marshal(map[string][]model.Client{
  1450. "clients": newClients,
  1451. })
  1452. if err != nil {
  1453. return result, needRestart, err
  1454. }
  1455. addNeedRestart, err := s.clientService.AddInboundClient(s, &model.Inbound{
  1456. Id: targetInboundID,
  1457. Settings: string(settingsPayload),
  1458. })
  1459. if err != nil {
  1460. return result, needRestart, err
  1461. }
  1462. if addNeedRestart {
  1463. needRestart = true
  1464. }
  1465. return result, needRestart, nil
  1466. }
  1467. const resetGracePeriodMs int64 = 30000
  1468. // onlineGracePeriodMs must comfortably exceed the 5s traffic-poll interval —
  1469. // Xray's stats counters often report a zero delta for an active session across
  1470. // a single poll, so a 5s grace would still drop the client on the next tick.
  1471. // ~4 polls of slack keeps idle-but-connected clients visible without lingering
  1472. // long after a real disconnect.
  1473. const onlineGracePeriodMs int64 = 20000
  1474. type nodeTrafficCounter struct {
  1475. Up int64
  1476. Down int64
  1477. }
  1478. func (s *InboundService) upsertNodeBaseline(tx *gorm.DB, nodeID int, email string, up, down int64) error {
  1479. return tx.Clauses(clause.OnConflict{
  1480. Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}},
  1481. DoUpdates: clause.AssignmentColumns([]string{"up", "down"}),
  1482. }).Create(&model.NodeClientTraffic{NodeId: nodeID, Email: email, Up: up, Down: down}).Error
  1483. }
  1484. func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot, dirty bool) (bool, error) {
  1485. var structuralChange bool
  1486. err := submitTrafficWrite(func() error {
  1487. var inner error
  1488. structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap, dirty)
  1489. return inner
  1490. })
  1491. return structuralChange, err
  1492. }
  1493. func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.TrafficSnapshot, dirty bool) (bool, error) {
  1494. if snap == nil || nodeID <= 0 {
  1495. return false, nil
  1496. }
  1497. db := database.GetDB()
  1498. now := time.Now().UnixMilli()
  1499. // originGuidFor attributes a synced inbound to the panel that physically
  1500. // hosts it: inbounds the node forwards from its own sub-nodes already carry
  1501. // a non-empty OriginNodeGuid (kept as-is across hops); the node's own local
  1502. // inbounds report empty, so they are attributed to the node's own GUID. An
  1503. // empty result (old-build node with no GUID yet) leaves attribution to the
  1504. // node_id fallback downstream (#4983).
  1505. var nodeRow model.Node
  1506. db.Select("guid").Where("id = ?", nodeID).First(&nodeRow)
  1507. originGuidFor := func(snapIb *model.Inbound) string {
  1508. if snapIb.OriginNodeGuid != "" {
  1509. return snapIb.OriginNodeGuid
  1510. }
  1511. return nodeRow.Guid
  1512. }
  1513. var central []model.Inbound
  1514. if err := db.Model(model.Inbound{}).
  1515. Where("node_id = ?", nodeID).
  1516. Find(&central).Error; err != nil {
  1517. return false, err
  1518. }
  1519. // Index under the stored tag and its prefix-flipped form so a snap matches
  1520. // whether the n<id>- prefix lives on the node side, the central side, or
  1521. // neither — a mismatch must never spawn a duplicate central inbound.
  1522. tagToCentral := make(map[string]*model.Inbound, len(central)*2)
  1523. prefix := nodeTagPrefix(&nodeID)
  1524. for i := range central {
  1525. tagToCentral[central[i].Tag] = &central[i]
  1526. if prefix != "" {
  1527. if stripped, found := strings.CutPrefix(central[i].Tag, prefix); found {
  1528. tagToCentral[stripped] = &central[i]
  1529. } else {
  1530. tagToCentral[prefix+central[i].Tag] = &central[i]
  1531. }
  1532. }
  1533. }
  1534. var centralClientStats []xray.ClientTraffic
  1535. if len(central) > 0 {
  1536. ids := make([]int, 0, len(central))
  1537. for i := range central {
  1538. ids = append(ids, central[i].Id)
  1539. }
  1540. if err := db.Model(xray.ClientTraffic{}).
  1541. Where("inbound_id IN ?", ids).
  1542. Find(&centralClientStats).Error; err != nil {
  1543. return false, err
  1544. }
  1545. }
  1546. type csKey struct {
  1547. inboundID int
  1548. email string
  1549. }
  1550. centralCS := make(map[csKey]*xray.ClientTraffic, len(centralClientStats))
  1551. centralCSByEmail := make(map[string]*xray.ClientTraffic, len(centralClientStats))
  1552. for i := range centralClientStats {
  1553. centralCS[csKey{centralClientStats[i].InboundId, centralClientStats[i].Email}] = &centralClientStats[i]
  1554. centralCSByEmail[centralClientStats[i].Email] = &centralClientStats[i]
  1555. }
  1556. nodeBaselines := make(map[string]nodeTrafficCounter)
  1557. var baselineRows []model.NodeClientTraffic
  1558. if err := db.Model(&model.NodeClientTraffic{}).
  1559. Where("node_id = ?", nodeID).
  1560. Find(&baselineRows).Error; err != nil {
  1561. return false, err
  1562. }
  1563. for i := range baselineRows {
  1564. nodeBaselines[baselineRows[i].Email] = nodeTrafficCounter{Up: baselineRows[i].Up, Down: baselineRows[i].Down}
  1565. }
  1566. var existingEmailsList []string
  1567. if err := db.Model(xray.ClientTraffic{}).Pluck("email", &existingEmailsList).Error; err != nil {
  1568. return false, err
  1569. }
  1570. existingEmails := make(map[string]struct{}, len(existingEmailsList))
  1571. for _, e := range existingEmailsList {
  1572. existingEmails[e] = struct{}{}
  1573. }
  1574. var defaultUserId int
  1575. if len(central) > 0 {
  1576. defaultUserId = central[0].UserId
  1577. } else {
  1578. var u model.User
  1579. if err := db.Model(model.User{}).Order("id asc").First(&u).Error; err == nil {
  1580. defaultUserId = u.Id
  1581. } else {
  1582. defaultUserId = 1
  1583. }
  1584. }
  1585. tx := db.Begin()
  1586. committed := false
  1587. defer func() {
  1588. if !committed {
  1589. tx.Rollback()
  1590. }
  1591. }()
  1592. structuralChange := false
  1593. snapTags := make(map[string]struct{}, len(snap.Inbounds))
  1594. for _, snapIb := range snap.Inbounds {
  1595. if snapIb == nil {
  1596. continue
  1597. }
  1598. snapTags[snapIb.Tag] = struct{}{}
  1599. // Record the prefix-flipped form too so the orphan sweep below keeps a
  1600. // central inbound whether its tag carries the n<id>- prefix or not.
  1601. if prefix != "" {
  1602. if stripped, found := strings.CutPrefix(snapIb.Tag, prefix); found {
  1603. snapTags[stripped] = struct{}{}
  1604. } else {
  1605. snapTags[prefix+snapIb.Tag] = struct{}{}
  1606. }
  1607. }
  1608. c, ok := tagToCentral[snapIb.Tag]
  1609. if !ok {
  1610. if dirty {
  1611. continue
  1612. }
  1613. // Try snap.Tag first; on collision fall back to the n<id>-
  1614. // prefixed form so local+node can both own the same port.
  1615. pickFreeTag := func() (string, error) {
  1616. candidates := []string{snapIb.Tag}
  1617. if prefix != "" && !strings.HasPrefix(snapIb.Tag, prefix) {
  1618. candidates = append(candidates, prefix+snapIb.Tag)
  1619. }
  1620. for _, t := range candidates {
  1621. var owner model.Inbound
  1622. err := tx.Where("tag = ?", t).First(&owner).Error
  1623. if errors.Is(err, gorm.ErrRecordNotFound) {
  1624. return t, nil
  1625. }
  1626. if err != nil {
  1627. return "", err
  1628. }
  1629. }
  1630. return "", nil
  1631. }
  1632. chosenTag, err := pickFreeTag()
  1633. if err != nil {
  1634. logger.Warningf("setRemoteTraffic: check tag %q failed: %v", snapIb.Tag, err)
  1635. continue
  1636. }
  1637. if chosenTag == "" {
  1638. key := fmt.Sprintf("%d:%s", nodeID, snapIb.Tag)
  1639. if _, seen := reportedRemoteTagConflict.LoadOrStore(key, struct{}{}); !seen {
  1640. logger.Warningf(
  1641. "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)",
  1642. snapIb.Tag, nodeID, nodeID,
  1643. )
  1644. }
  1645. continue
  1646. }
  1647. newIb := model.Inbound{
  1648. UserId: defaultUserId,
  1649. NodeID: &nodeID,
  1650. OriginNodeGuid: originGuidFor(snapIb),
  1651. Tag: chosenTag,
  1652. Listen: snapIb.Listen,
  1653. Port: snapIb.Port,
  1654. Protocol: snapIb.Protocol,
  1655. Settings: snapIb.Settings,
  1656. StreamSettings: snapIb.StreamSettings,
  1657. Sniffing: snapIb.Sniffing,
  1658. TrafficReset: snapIb.TrafficReset,
  1659. LastTrafficResetTime: snapIb.LastTrafficResetTime,
  1660. Enable: snapIb.Enable,
  1661. Remark: snapIb.Remark,
  1662. Total: snapIb.Total,
  1663. ExpiryTime: snapIb.ExpiryTime,
  1664. Up: snapIb.Up,
  1665. Down: snapIb.Down,
  1666. }
  1667. if err := tx.Create(&newIb).Error; err != nil {
  1668. logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err)
  1669. continue
  1670. }
  1671. tagToCentral[snapIb.Tag] = &newIb
  1672. if newIb.Tag != snapIb.Tag {
  1673. tagToCentral[newIb.Tag] = &newIb
  1674. }
  1675. structuralChange = true
  1676. continue
  1677. }
  1678. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  1679. updates := map[string]any{}
  1680. if !dirty {
  1681. updates["enable"] = snapIb.Enable
  1682. updates["remark"] = snapIb.Remark
  1683. updates["listen"] = snapIb.Listen
  1684. updates["port"] = snapIb.Port
  1685. updates["protocol"] = snapIb.Protocol
  1686. updates["total"] = snapIb.Total
  1687. updates["expiry_time"] = snapIb.ExpiryTime
  1688. updates["settings"] = snapIb.Settings
  1689. updates["stream_settings"] = snapIb.StreamSettings
  1690. updates["sniffing"] = snapIb.Sniffing
  1691. updates["traffic_reset"] = snapIb.TrafficReset
  1692. updates["last_traffic_reset_time"] = snapIb.LastTrafficResetTime
  1693. }
  1694. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  1695. updates["up"] = snapIb.Up
  1696. updates["down"] = snapIb.Down
  1697. }
  1698. // Physical-home attribution is independent of config-dirty state, so
  1699. // keep it current even while the node has pending offline edits. Writes
  1700. // once to backfill an existing row, then stays equal (#4983).
  1701. if og := originGuidFor(snapIb); c.OriginNodeGuid != og {
  1702. updates["origin_node_guid"] = og
  1703. }
  1704. if !dirty && (c.Settings != snapIb.Settings ||
  1705. c.Remark != snapIb.Remark ||
  1706. c.Listen != snapIb.Listen ||
  1707. c.Port != snapIb.Port ||
  1708. c.Total != snapIb.Total ||
  1709. c.ExpiryTime != snapIb.ExpiryTime ||
  1710. c.Enable != snapIb.Enable) {
  1711. structuralChange = true
  1712. }
  1713. if len(updates) > 0 {
  1714. if err := tx.Model(model.Inbound{}).
  1715. Where("id = ?", c.Id).
  1716. Updates(updates).Error; err != nil {
  1717. return false, err
  1718. }
  1719. }
  1720. }
  1721. for _, c := range central {
  1722. if dirty {
  1723. continue
  1724. }
  1725. if _, kept := snapTags[c.Tag]; kept {
  1726. continue
  1727. }
  1728. var goneEmails []string
  1729. if err := tx.Model(xray.ClientTraffic{}).
  1730. Where("inbound_id = ?", c.Id).
  1731. Pluck("email", &goneEmails).Error; err != nil {
  1732. return false, err
  1733. }
  1734. if len(goneEmails) > 0 {
  1735. // Chunk to avoid SQLite bind var limit when a node has many clients
  1736. // removed (e.g. after API bulk delete or structural change on node inbound).
  1737. for _, batch := range chunkStrings(goneEmails, sqliteMaxVars) {
  1738. if err := tx.Where("node_id = ? AND email IN ?", nodeID, batch).
  1739. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  1740. return false, err
  1741. }
  1742. }
  1743. }
  1744. if err := tx.Where("inbound_id = ?", c.Id).
  1745. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1746. return false, err
  1747. }
  1748. if err := s.clientService.DetachInbound(tx, c.Id); err != nil {
  1749. return false, err
  1750. }
  1751. if err := tx.Where("id = ?", c.Id).
  1752. Delete(&model.Inbound{}).Error; err != nil {
  1753. return false, err
  1754. }
  1755. delete(tagToCentral, c.Tag)
  1756. structuralChange = true
  1757. }
  1758. for _, snapIb := range snap.Inbounds {
  1759. if snapIb == nil {
  1760. continue
  1761. }
  1762. c, ok := tagToCentral[snapIb.Tag]
  1763. if !ok {
  1764. continue
  1765. }
  1766. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  1767. for _, cs := range snapIb.ClientStats {
  1768. snapEmails[cs.Email] = struct{}{}
  1769. base, seen := nodeBaselines[cs.Email]
  1770. var deltaUp, deltaDown int64
  1771. if seen {
  1772. if deltaUp = cs.Up - base.Up; deltaUp < 0 {
  1773. deltaUp = cs.Up
  1774. }
  1775. if deltaDown = cs.Down - base.Down; deltaDown < 0 {
  1776. deltaDown = cs.Down
  1777. }
  1778. }
  1779. if _, rowExists := existingEmails[cs.Email]; !rowExists {
  1780. if dirty {
  1781. continue
  1782. }
  1783. row := &xray.ClientTraffic{
  1784. InboundId: c.Id,
  1785. Email: cs.Email,
  1786. Enable: cs.Enable,
  1787. Total: cs.Total,
  1788. ExpiryTime: cs.ExpiryTime,
  1789. Reset: cs.Reset,
  1790. Up: cs.Up,
  1791. Down: cs.Down,
  1792. LastOnline: cs.LastOnline,
  1793. }
  1794. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  1795. Create(row).Error; err != nil {
  1796. return false, err
  1797. }
  1798. centralCS[csKey{c.Id, cs.Email}] = row
  1799. centralCSByEmail[cs.Email] = row
  1800. existingEmails[cs.Email] = struct{}{}
  1801. structuralChange = true
  1802. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, cs.Up, cs.Down); err != nil {
  1803. return false, err
  1804. }
  1805. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: cs.Up, Down: cs.Down}
  1806. continue
  1807. }
  1808. if existing := centralCSByEmail[cs.Email]; existing != nil &&
  1809. (existing.Enable != cs.Enable ||
  1810. existing.Total != cs.Total ||
  1811. existing.ExpiryTime != cs.ExpiryTime ||
  1812. existing.Reset != cs.Reset) {
  1813. structuralChange = true
  1814. }
  1815. enableExpr := database.ClientTrafficEnableMergeExpr()
  1816. if err := tx.Exec(
  1817. fmt.Sprintf(
  1818. `UPDATE client_traffics
  1819. SET up = up + ?, down = down + ?, enable = %s, total = ?, expiry_time = ?, reset = ?,
  1820. last_online = %s
  1821. WHERE email = ?`,
  1822. enableExpr,
  1823. database.GreatestExpr("last_online", "?"),
  1824. ),
  1825. deltaUp, deltaDown, cs.Enable, cs.Total, cs.ExpiryTime, cs.Reset,
  1826. cs.LastOnline, cs.Email,
  1827. ).Error; err != nil {
  1828. return false, err
  1829. }
  1830. if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, cs.Up, cs.Down); err != nil {
  1831. return false, err
  1832. }
  1833. nodeBaselines[cs.Email] = nodeTrafficCounter{Up: cs.Up, Down: cs.Down}
  1834. }
  1835. for k, existing := range centralCS {
  1836. if dirty {
  1837. continue
  1838. }
  1839. if k.inboundID != c.Id {
  1840. continue
  1841. }
  1842. if _, kept := snapEmails[k.email]; kept {
  1843. continue
  1844. }
  1845. if err := tx.Where("node_id = ? AND email = ?", nodeID, existing.Email).
  1846. Delete(&model.NodeClientTraffic{}).Error; err != nil {
  1847. return false, err
  1848. }
  1849. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  1850. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1851. return false, err
  1852. }
  1853. structuralChange = true
  1854. }
  1855. }
  1856. type oldSet struct {
  1857. inboundID int
  1858. emails map[string]struct{}
  1859. }
  1860. var perInboundOld []oldSet
  1861. for _, snapIb := range snap.Inbounds {
  1862. if snapIb == nil {
  1863. continue
  1864. }
  1865. c, ok := tagToCentral[snapIb.Tag]
  1866. if !ok {
  1867. continue
  1868. }
  1869. if dirty {
  1870. continue
  1871. }
  1872. var oldEmailsRows []string
  1873. if err := tx.Table("clients").
  1874. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1875. Where("client_inbounds.inbound_id = ?", c.Id).
  1876. Pluck("email", &oldEmailsRows).Error; err == nil {
  1877. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  1878. for _, e := range oldEmailsRows {
  1879. if e != "" {
  1880. oldEmails[e] = struct{}{}
  1881. }
  1882. }
  1883. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  1884. }
  1885. clients, gcErr := s.GetClients(snapIb)
  1886. if gcErr != nil {
  1887. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  1888. continue
  1889. }
  1890. csEnableByEmail := make(map[string]bool, len(snapIb.ClientStats))
  1891. for _, cs := range snapIb.ClientStats {
  1892. csEnableByEmail[cs.Email] = cs.Enable
  1893. }
  1894. filtered := clients[:0]
  1895. for i := range clients {
  1896. if isClientEmailTombstoned(clients[i].Email) {
  1897. continue
  1898. }
  1899. if cse, hit := csEnableByEmail[clients[i].Email]; hit && !cse {
  1900. clients[i].Enable = false
  1901. }
  1902. filtered = append(filtered, clients[i])
  1903. }
  1904. localEmails := make([]string, 0, len(filtered))
  1905. for i := range filtered {
  1906. if filtered[i].Email != "" {
  1907. localEmails = append(localEmails, filtered[i].Email)
  1908. }
  1909. }
  1910. if len(localEmails) > 0 {
  1911. var localMeta []struct {
  1912. Email string
  1913. Comment string `gorm:"column:comment"`
  1914. }
  1915. if err := tx.Table("clients").
  1916. Select("email, comment").
  1917. Where("email IN ?", localEmails).
  1918. Find(&localMeta).Error; err == nil {
  1919. commentByEmail := make(map[string]string, len(localMeta))
  1920. for _, m := range localMeta {
  1921. commentByEmail[m.Email] = m.Comment
  1922. }
  1923. for i := range filtered {
  1924. if cmt, ok := commentByEmail[filtered[i].Email]; ok {
  1925. filtered[i].Comment = cmt
  1926. }
  1927. }
  1928. }
  1929. }
  1930. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  1931. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  1932. }
  1933. }
  1934. for _, old := range perInboundOld {
  1935. var stillAttached []string
  1936. if err := tx.Table("clients").
  1937. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1938. Where("client_inbounds.inbound_id = ?", old.inboundID).
  1939. Pluck("email", &stillAttached).Error; err != nil {
  1940. continue
  1941. }
  1942. stillSet := make(map[string]struct{}, len(stillAttached))
  1943. for _, e := range stillAttached {
  1944. stillSet[e] = struct{}{}
  1945. }
  1946. for email := range old.emails {
  1947. if _, kept := stillSet[email]; kept {
  1948. continue
  1949. }
  1950. var attachmentCount int64
  1951. if err := tx.Table("client_inbounds").
  1952. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1953. Where("clients.email = ?", email).
  1954. Count(&attachmentCount).Error; err != nil {
  1955. continue
  1956. }
  1957. if attachmentCount > 0 {
  1958. continue
  1959. }
  1960. if err := tx.Where("email = ?", email).Delete(&model.ClientRecord{}).Error; err != nil {
  1961. logger.Warningf("setRemoteTraffic: delete ClientRecord %q failed: %v", email, err)
  1962. }
  1963. if err := tx.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  1964. logger.Warningf("setRemoteTraffic: delete ClientTraffic %q failed: %v", email, err)
  1965. }
  1966. if err := tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  1967. logger.Warningf("setRemoteTraffic: delete NodeClientTraffic %q failed: %v", email, err)
  1968. }
  1969. structuralChange = true
  1970. }
  1971. }
  1972. if err := tx.Commit().Error; err != nil {
  1973. return false, err
  1974. }
  1975. committed = true
  1976. if p != nil {
  1977. tree := snap.OnlineTree
  1978. if len(tree) == 0 && len(snap.OnlineEmails) > 0 {
  1979. // Old-build node (no GUID tree): key its flat online list under its
  1980. // own effective identity so attribution still works for that branch.
  1981. effectiveGuid := nodeRow.Guid
  1982. if effectiveGuid == "" {
  1983. effectiveGuid = synthNodeGuid(nodeID)
  1984. }
  1985. tree = map[string][]string{effectiveGuid: snap.OnlineEmails}
  1986. }
  1987. p.SetNodeOnlineTree(nodeID, tree)
  1988. }
  1989. return structuralChange, nil
  1990. }
  1991. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (needRestart bool, clientsDisabled bool, err error) {
  1992. var disabledNodeIDs []int
  1993. err = submitTrafficWrite(func() error {
  1994. var inner error
  1995. needRestart, clientsDisabled, disabledNodeIDs, inner = s.addTrafficLocked(inboundTraffics, clientTraffics)
  1996. return inner
  1997. })
  1998. if err == nil && len(disabledNodeIDs) > 0 {
  1999. s.restartRemoteNodesOnDisable(disabledNodeIDs)
  2000. }
  2001. return
  2002. }
  2003. func (s *InboundService) addTrafficLocked(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (bool, bool, []int, error) {
  2004. var err error
  2005. db := database.GetDB()
  2006. tx := db.Begin()
  2007. defer func() {
  2008. if err != nil {
  2009. tx.Rollback()
  2010. } else {
  2011. tx.Commit()
  2012. }
  2013. }()
  2014. err = s.addInboundTraffic(tx, inboundTraffics)
  2015. if err != nil {
  2016. return false, false, nil, err
  2017. }
  2018. err = s.addClientTraffic(tx, clientTraffics)
  2019. if err != nil {
  2020. return false, false, nil, err
  2021. }
  2022. needRestart0, count, err := s.autoRenewClients(tx)
  2023. if err != nil {
  2024. logger.Warning("Error in renew clients:", err)
  2025. } else if count > 0 {
  2026. logger.Debugf("%v clients renewed", count)
  2027. }
  2028. disabledClientsCount := int64(0)
  2029. needRestart1, count, disabledNodeIDs, err := s.disableInvalidClients(tx)
  2030. if err != nil {
  2031. logger.Warning("Error in disabling invalid clients:", err)
  2032. } else if count > 0 {
  2033. logger.Debugf("%v clients disabled", count)
  2034. disabledClientsCount = count
  2035. }
  2036. needRestart2, count, err := s.disableInvalidInbounds(tx)
  2037. if err != nil {
  2038. logger.Warning("Error in disabling invalid inbounds:", err)
  2039. } else if count > 0 {
  2040. logger.Debugf("%v inbounds disabled", count)
  2041. }
  2042. return needRestart0 || needRestart1 || needRestart2, disabledClientsCount > 0, disabledNodeIDs, nil
  2043. }
  2044. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  2045. if len(traffics) == 0 {
  2046. return nil
  2047. }
  2048. var err error
  2049. for _, traffic := range traffics {
  2050. if traffic.IsInbound {
  2051. err = tx.Model(&model.Inbound{}).Where("tag = ? AND node_id IS NULL", traffic.Tag).
  2052. Updates(map[string]any{
  2053. "up": gorm.Expr("up + ?", traffic.Up),
  2054. "down": gorm.Expr("down + ?", traffic.Down),
  2055. }).Error
  2056. if err != nil {
  2057. return err
  2058. }
  2059. }
  2060. }
  2061. return nil
  2062. }
  2063. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  2064. if len(traffics) == 0 {
  2065. return nil
  2066. }
  2067. emails := make([]string, 0, len(traffics))
  2068. for _, traffic := range traffics {
  2069. emails = append(emails, traffic.Email)
  2070. }
  2071. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  2072. // Match purely by email. client_traffics is email-keyed (one shared row per
  2073. // email regardless of how many inbounds the client is attached to), and these
  2074. // emails come from the local xray's report, so they always belong to a client
  2075. // attached to a local inbound. The old `inbound_id NOT IN (node inbounds)`
  2076. // filter dropped the local traffic of a client attached to both a node and the
  2077. // mother inbound whenever the node inbound happened to be attached first — its
  2078. // shared row then carried the node inbound's id (AddClientStat uses OnConflict
  2079. // DoNothing and never refreshes it), so the local poll skipped it entirely.
  2080. err = tx.Model(xray.ClientTraffic{}).
  2081. Where("email IN (?)", emails).
  2082. Find(&dbClientTraffics).Error
  2083. if err != nil {
  2084. return err
  2085. }
  2086. // Avoid empty slice error
  2087. if len(dbClientTraffics) == 0 {
  2088. return nil
  2089. }
  2090. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  2091. if err != nil {
  2092. return err
  2093. }
  2094. // Index by email for O(N) merge — the previous nested loop was O(N²)
  2095. // and dominated each cron tick on inbounds with thousands of active
  2096. // clients (7500 × 7500 = 56M string comparisons every 10 seconds).
  2097. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  2098. for i := range traffics {
  2099. if traffics[i] != nil {
  2100. trafficByEmail[traffics[i].Email] = traffics[i]
  2101. }
  2102. }
  2103. now := time.Now().UnixMilli()
  2104. for dbTraffic_index := range dbClientTraffics {
  2105. t, ok := trafficByEmail[dbClientTraffics[dbTraffic_index].Email]
  2106. if !ok {
  2107. continue
  2108. }
  2109. dbClientTraffics[dbTraffic_index].Up += t.Up
  2110. dbClientTraffics[dbTraffic_index].Down += t.Down
  2111. if t.Up+t.Down > 0 {
  2112. dbClientTraffics[dbTraffic_index].LastOnline = now
  2113. }
  2114. }
  2115. err = tx.Save(dbClientTraffics).Error
  2116. if err != nil {
  2117. logger.Warning("AddClientTraffic update data ", err)
  2118. }
  2119. return nil
  2120. }
  2121. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  2122. now := time.Now().UnixMilli()
  2123. // "Start After First Use" stores a negative expiry (the duration). On the
  2124. // first traffic tick it becomes an absolute deadline of now+duration. Compute
  2125. // it once per email so every inbound the client is attached to lands on the
  2126. // same value (recomputing per inbound would skip all but the first one).
  2127. newExpiryByEmail := make(map[string]int64, len(dbClientTraffics))
  2128. for traffic_index := range dbClientTraffics {
  2129. if dbClientTraffics[traffic_index].ExpiryTime < 0 {
  2130. newExpiryByEmail[dbClientTraffics[traffic_index].Email] = now - dbClientTraffics[traffic_index].ExpiryTime
  2131. }
  2132. }
  2133. if len(newExpiryByEmail) == 0 {
  2134. return dbClientTraffics, nil
  2135. }
  2136. delayedEmails := make([]string, 0, len(newExpiryByEmail))
  2137. for email := range newExpiryByEmail {
  2138. delayedEmails = append(delayedEmails, email)
  2139. }
  2140. // Resolve the owning inbounds through the client_inbounds link, which is
  2141. // authoritative. client_traffics.inbound_id goes stale when an inbound is
  2142. // deleted and recreated, which would leave the negative expiry unconverted.
  2143. var inboundIds []int
  2144. err := tx.Table("client_inbounds").
  2145. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  2146. Where("clients.email IN (?)", delayedEmails).
  2147. Distinct().
  2148. Pluck("client_inbounds.inbound_id", &inboundIds).Error
  2149. if err != nil {
  2150. return nil, err
  2151. }
  2152. if len(inboundIds) == 0 {
  2153. return dbClientTraffics, nil
  2154. }
  2155. var inbounds []*model.Inbound
  2156. err = tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  2157. if err != nil {
  2158. return nil, err
  2159. }
  2160. for inbound_index := range inbounds {
  2161. settings := map[string]any{}
  2162. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  2163. clients, ok := settings["clients"].([]any)
  2164. if ok {
  2165. var newClients []any
  2166. for client_index := range clients {
  2167. c := clients[client_index].(map[string]any)
  2168. email, _ := c["email"].(string)
  2169. if newExpiry, ok := newExpiryByEmail[email]; ok {
  2170. c["expiryTime"] = newExpiry
  2171. c["updated_at"] = now
  2172. }
  2173. if _, ok := c["created_at"]; !ok {
  2174. c["created_at"] = now
  2175. }
  2176. if _, ok := c["updated_at"]; !ok {
  2177. c["updated_at"] = now
  2178. }
  2179. newClients = append(newClients, any(c))
  2180. }
  2181. settings["clients"] = newClients
  2182. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2183. if err != nil {
  2184. return nil, err
  2185. }
  2186. inbounds[inbound_index].Settings = string(modifiedSettings)
  2187. }
  2188. }
  2189. for traffic_index := range dbClientTraffics {
  2190. if newExpiry, ok := newExpiryByEmail[dbClientTraffics[traffic_index].Email]; ok {
  2191. dbClientTraffics[traffic_index].ExpiryTime = newExpiry
  2192. }
  2193. }
  2194. err = tx.Save(inbounds).Error
  2195. if err != nil {
  2196. logger.Warning("AddClientTraffic update inbounds ", err)
  2197. logger.Error(inbounds)
  2198. } else {
  2199. for _, ib := range inbounds {
  2200. if ib == nil {
  2201. continue
  2202. }
  2203. cs, gcErr := s.GetClients(ib)
  2204. if gcErr != nil {
  2205. logger.Warning("AddClientTraffic sync clients: GetClients failed", gcErr)
  2206. continue
  2207. }
  2208. if syncErr := s.clientService.SyncInbound(tx, ib.Id, cs); syncErr != nil {
  2209. logger.Warning("AddClientTraffic sync clients: SyncInbound failed", syncErr)
  2210. }
  2211. }
  2212. }
  2213. return dbClientTraffics, nil
  2214. }
  2215. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  2216. // check for time expired
  2217. var traffics []*xray.ClientTraffic
  2218. now := time.Now().Unix() * 1000
  2219. var err, err1 error
  2220. err = tx.Model(xray.ClientTraffic{}).
  2221. Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).
  2222. Where("inbound_id NOT IN (?)", tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NOT NULL")).
  2223. Find(&traffics).Error
  2224. if err != nil {
  2225. return false, 0, err
  2226. }
  2227. // return if there is no client to renew
  2228. if len(traffics) == 0 {
  2229. return false, 0, nil
  2230. }
  2231. var inbound_ids []int
  2232. var inbounds []*model.Inbound
  2233. needRestart := false
  2234. var clientsToAdd []struct {
  2235. protocol string
  2236. tag string
  2237. client map[string]any
  2238. }
  2239. // Resolve the inbounds to renew through the client_inbounds link rather than
  2240. // client_traffics.inbound_id, which goes stale after an inbound is deleted and
  2241. // recreated and would otherwise skip the renew entirely.
  2242. renewEmails := make([]string, 0, len(traffics))
  2243. for _, traffic := range traffics {
  2244. renewEmails = append(renewEmails, traffic.Email)
  2245. }
  2246. for _, batch := range chunkStrings(renewEmails, sqliteMaxVars) {
  2247. var ids []int
  2248. if err = tx.Table("client_inbounds").
  2249. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  2250. Where("clients.email IN ?", batch).
  2251. Distinct().
  2252. Pluck("client_inbounds.inbound_id", &ids).Error; err != nil {
  2253. return false, 0, err
  2254. }
  2255. inbound_ids = append(inbound_ids, ids...)
  2256. }
  2257. // Dedupe so an inbound hosting N expired clients is fetched and saved once
  2258. // per tick instead of N times across chunk boundaries.
  2259. inbound_ids = uniqueInts(inbound_ids)
  2260. // Chunked to stay under SQLite's bind-variable limit when many inbounds
  2261. // are touched in a single tick.
  2262. for _, batch := range chunkInts(inbound_ids, sqliteMaxVars) {
  2263. var page []*model.Inbound
  2264. if err = tx.Model(model.Inbound{}).Where("id IN ?", batch).Find(&page).Error; err != nil {
  2265. return false, 0, err
  2266. }
  2267. inbounds = append(inbounds, page...)
  2268. }
  2269. for inbound_index := range inbounds {
  2270. settings := map[string]any{}
  2271. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  2272. clients := settings["clients"].([]any)
  2273. for client_index := range clients {
  2274. c := clients[client_index].(map[string]any)
  2275. for traffic_index, traffic := range traffics {
  2276. if traffic.Email == c["email"].(string) {
  2277. newExpiryTime := traffic.ExpiryTime
  2278. for newExpiryTime < now {
  2279. newExpiryTime += (int64(traffic.Reset) * 86400000)
  2280. }
  2281. c["expiryTime"] = newExpiryTime
  2282. traffics[traffic_index].ExpiryTime = newExpiryTime
  2283. traffics[traffic_index].Down = 0
  2284. traffics[traffic_index].Up = 0
  2285. if !traffic.Enable {
  2286. traffics[traffic_index].Enable = true
  2287. c["enable"] = true
  2288. clientsToAdd = append(clientsToAdd,
  2289. struct {
  2290. protocol string
  2291. tag string
  2292. client map[string]any
  2293. }{
  2294. protocol: string(inbounds[inbound_index].Protocol),
  2295. tag: inbounds[inbound_index].Tag,
  2296. client: c,
  2297. })
  2298. }
  2299. clients[client_index] = any(c)
  2300. break
  2301. }
  2302. }
  2303. }
  2304. settings["clients"] = clients
  2305. newSettings, err := json.MarshalIndent(settings, "", " ")
  2306. if err != nil {
  2307. return false, 0, err
  2308. }
  2309. inbounds[inbound_index].Settings = string(newSettings)
  2310. }
  2311. err = tx.Save(inbounds).Error
  2312. if err != nil {
  2313. return false, 0, err
  2314. }
  2315. for _, ib := range inbounds {
  2316. if ib == nil {
  2317. continue
  2318. }
  2319. cs, gcErr := s.GetClients(ib)
  2320. if gcErr != nil {
  2321. logger.Warning("autoRenewClients sync clients: GetClients failed", gcErr)
  2322. continue
  2323. }
  2324. if syncErr := s.clientService.SyncInbound(tx, ib.Id, cs); syncErr != nil {
  2325. logger.Warning("autoRenewClients sync clients: SyncInbound failed", syncErr)
  2326. }
  2327. }
  2328. err = tx.Save(traffics).Error
  2329. if err != nil {
  2330. return false, 0, err
  2331. }
  2332. if p != nil {
  2333. err1 = s.xrayApi.Init(p.GetAPIPort())
  2334. if err1 != nil {
  2335. return true, int64(len(traffics)), nil
  2336. }
  2337. for _, clientToAdd := range clientsToAdd {
  2338. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  2339. if err1 != nil {
  2340. needRestart = true
  2341. }
  2342. }
  2343. s.xrayApi.Close()
  2344. }
  2345. return needRestart, int64(len(traffics)), nil
  2346. }
  2347. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  2348. now := time.Now().Unix() * 1000
  2349. needRestart := false
  2350. if p != nil {
  2351. var tags []string
  2352. err := tx.Table("inbounds").
  2353. Select("inbounds.tag").
  2354. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ? and node_id IS NULL", now, true).
  2355. Scan(&tags).Error
  2356. if err != nil {
  2357. return false, 0, err
  2358. }
  2359. s.xrayApi.Init(p.GetAPIPort())
  2360. for _, tag := range tags {
  2361. err1 := s.xrayApi.DelInbound(tag)
  2362. if err1 == nil {
  2363. logger.Debug("Inbound disabled by api:", tag)
  2364. } else {
  2365. logger.Debug("Error in disabling inbound by api:", err1)
  2366. needRestart = true
  2367. }
  2368. }
  2369. s.xrayApi.Close()
  2370. }
  2371. result := tx.Model(model.Inbound{}).
  2372. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ? and node_id IS NULL", now, true).
  2373. Update("enable", false)
  2374. err := result.Error
  2375. count := result.RowsAffected
  2376. return needRestart, count, err
  2377. }
  2378. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, []int, error) {
  2379. now := time.Now().Unix() * 1000
  2380. needRestart := false
  2381. var depletedRows []xray.ClientTraffic
  2382. err := tx.Model(xray.ClientTraffic{}).
  2383. Where("((total > 0 AND up + down >= total) OR (expiry_time > 0 AND expiry_time <= ?)) AND enable = ?", now, true).
  2384. Find(&depletedRows).Error
  2385. if err != nil {
  2386. return false, 0, nil, err
  2387. }
  2388. if len(depletedRows) == 0 {
  2389. return false, 0, nil, nil
  2390. }
  2391. depletedEmails := make([]string, 0, len(depletedRows))
  2392. for i := range depletedRows {
  2393. if depletedRows[i].Email == "" {
  2394. continue
  2395. }
  2396. depletedEmails = append(depletedEmails, depletedRows[i].Email)
  2397. }
  2398. type target struct {
  2399. InboundID int `gorm:"column:inbound_id"`
  2400. NodeID *int `gorm:"column:node_id"`
  2401. Tag string
  2402. Email string
  2403. }
  2404. var targets []target
  2405. if len(depletedEmails) > 0 {
  2406. err = tx.Raw(`
  2407. SELECT inbounds.id AS inbound_id, inbounds.node_id AS node_id,
  2408. inbounds.tag AS tag, clients.email AS email
  2409. FROM clients
  2410. JOIN client_inbounds ON client_inbounds.client_id = clients.id
  2411. JOIN inbounds ON inbounds.id = client_inbounds.inbound_id
  2412. WHERE clients.email IN ?
  2413. `, depletedEmails).Scan(&targets).Error
  2414. if err != nil {
  2415. return false, 0, nil, err
  2416. }
  2417. }
  2418. var localTargets []target
  2419. localByInbound := make(map[int]map[string]struct{})
  2420. remoteByInbound := make(map[int][]target)
  2421. for _, t := range targets {
  2422. if t.NodeID == nil {
  2423. localTargets = append(localTargets, t)
  2424. if localByInbound[t.InboundID] == nil {
  2425. localByInbound[t.InboundID] = make(map[string]struct{})
  2426. }
  2427. localByInbound[t.InboundID][t.Email] = struct{}{}
  2428. } else {
  2429. remoteByInbound[t.InboundID] = append(remoteByInbound[t.InboundID], t)
  2430. }
  2431. }
  2432. if p != nil && len(localTargets) > 0 {
  2433. s.xrayApi.Init(p.GetAPIPort())
  2434. for _, t := range localTargets {
  2435. err1 := s.xrayApi.RemoveUser(t.Tag, t.Email)
  2436. if err1 == nil {
  2437. logger.Debug("Client disabled by api:", t.Email)
  2438. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.Email)) {
  2439. logger.Debug("User is already disabled. Nothing to do more...")
  2440. } else {
  2441. logger.Debug("Error in disabling client by api:", err1)
  2442. needRestart = true
  2443. }
  2444. }
  2445. s.xrayApi.Close()
  2446. }
  2447. for inboundID, emails := range localByInbound {
  2448. if _, _, mErr := s.markClientsDisabledInSettings(tx, inboundID, emails); mErr != nil {
  2449. logger.Warning("disableInvalidClients: settings.JSON sync failed for inbound", inboundID, ":", mErr)
  2450. }
  2451. }
  2452. result := tx.Model(xray.ClientTraffic{}).
  2453. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  2454. Update("enable", false)
  2455. err = result.Error
  2456. count := result.RowsAffected
  2457. if err != nil {
  2458. return needRestart, count, nil, err
  2459. }
  2460. if len(depletedEmails) > 0 {
  2461. if err := tx.Model(&model.ClientRecord{}).
  2462. Where("email IN ?", depletedEmails).
  2463. Updates(map[string]any{"enable": false, "updated_at": now}).Error; err != nil {
  2464. logger.Warning("disableInvalidClients update clients.enable:", err)
  2465. }
  2466. }
  2467. disabledNodeIDs := make(map[int]struct{})
  2468. for inboundID, group := range remoteByInbound {
  2469. emails := make(map[string]struct{}, len(group))
  2470. for _, t := range group {
  2471. emails[t.Email] = struct{}{}
  2472. }
  2473. if pushErr := s.disableRemoteClients(tx, inboundID, emails); pushErr != nil {
  2474. logger.Warning("disableInvalidClients: push to remote failed for inbound", inboundID, ":", pushErr)
  2475. needRestart = true
  2476. } else {
  2477. for _, t := range group {
  2478. if t.NodeID != nil {
  2479. disabledNodeIDs[*t.NodeID] = struct{}{}
  2480. }
  2481. }
  2482. }
  2483. }
  2484. nodeIDs := make([]int, 0, len(disabledNodeIDs))
  2485. for nodeID := range disabledNodeIDs {
  2486. nodeIDs = append(nodeIDs, nodeID)
  2487. }
  2488. return needRestart, count, nodeIDs, nil
  2489. }
  2490. func (s *InboundService) restartRemoteNodesOnDisable(nodeIDs []int) {
  2491. restartOnDisable, err := (&SettingService{}).GetRestartXrayOnClientDisable()
  2492. if err != nil {
  2493. logger.Warning("disableInvalidClients: get RestartXrayOnClientDisable failed:", err)
  2494. return
  2495. }
  2496. if !restartOnDisable {
  2497. return
  2498. }
  2499. for _, nodeID := range nodeIDs {
  2500. nodeIDCopy := nodeID
  2501. rt, rtErr := runtime.GetManager().RuntimeFor(&nodeIDCopy)
  2502. if rtErr != nil {
  2503. logger.Warning("disableInvalidClients: get runtime for node", nodeID, "failed:", rtErr)
  2504. continue
  2505. }
  2506. if rtErr = rt.RestartXray(context.Background()); rtErr != nil {
  2507. logger.Warning("disableInvalidClients: restart xray on node", nodeID, "failed:", rtErr)
  2508. }
  2509. }
  2510. }
  2511. // markClientsDisabledInSettings flips client.enable=false in the inbound's
  2512. // stored settings JSON for the given emails and returns both the pre and
  2513. // post snapshots so a caller pushing to a remote node has the diff to hand.
  2514. func (s *InboundService) markClientsDisabledInSettings(tx *gorm.DB, inboundID int, emails map[string]struct{}) (oldIb, newIb *model.Inbound, err error) {
  2515. var ib model.Inbound
  2516. if err := tx.Model(&model.Inbound{}).Where("id = ?", inboundID).First(&ib).Error; err != nil {
  2517. return nil, nil, err
  2518. }
  2519. snapshot := ib
  2520. settings := map[string]any{}
  2521. if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
  2522. return nil, nil, err
  2523. }
  2524. clients, _ := settings["clients"].([]any)
  2525. now := time.Now().Unix() * 1000
  2526. mutated := false
  2527. for i := range clients {
  2528. entry, ok := clients[i].(map[string]any)
  2529. if !ok {
  2530. continue
  2531. }
  2532. email, _ := entry["email"].(string)
  2533. if _, hit := emails[email]; !hit {
  2534. continue
  2535. }
  2536. if cur, _ := entry["enable"].(bool); cur == false {
  2537. continue
  2538. }
  2539. entry["enable"] = false
  2540. entry["updated_at"] = now
  2541. clients[i] = entry
  2542. mutated = true
  2543. }
  2544. if !mutated {
  2545. return &snapshot, &ib, nil
  2546. }
  2547. settings["clients"] = clients
  2548. bs, marshalErr := json.MarshalIndent(settings, "", " ")
  2549. if marshalErr != nil {
  2550. return nil, nil, marshalErr
  2551. }
  2552. ib.Settings = string(bs)
  2553. if err := tx.Model(&model.Inbound{}).Where("id = ?", inboundID).
  2554. Update("settings", ib.Settings).Error; err != nil {
  2555. return nil, nil, err
  2556. }
  2557. return &snapshot, &ib, nil
  2558. }
  2559. func (s *InboundService) disableRemoteClients(tx *gorm.DB, inboundID int, emails map[string]struct{}) error {
  2560. oldSnapshot, ib, err := s.markClientsDisabledInSettings(tx, inboundID, emails)
  2561. if err != nil {
  2562. return err
  2563. }
  2564. rt, err := s.runtimeFor(ib)
  2565. if err != nil {
  2566. return err
  2567. }
  2568. if err := rt.UpdateInbound(context.Background(), oldSnapshot, ib); err != nil {
  2569. return err
  2570. }
  2571. return nil
  2572. }
  2573. func (s *InboundService) GetInboundTags() (string, error) {
  2574. db := database.GetDB()
  2575. var inboundTags []string
  2576. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  2577. if err != nil && err != gorm.ErrRecordNotFound {
  2578. return "", err
  2579. }
  2580. tags, _ := json.Marshal(inboundTags)
  2581. return string(tags), nil
  2582. }
  2583. func (s *InboundService) GetClientReverseTags() (string, error) {
  2584. db := database.GetDB()
  2585. var inbounds []model.Inbound
  2586. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  2587. if err != nil && err != gorm.ErrRecordNotFound {
  2588. return "[]", err
  2589. }
  2590. tagSet := make(map[string]struct{})
  2591. for _, inbound := range inbounds {
  2592. var settings map[string]any
  2593. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2594. continue
  2595. }
  2596. clients, ok := settings["clients"].([]any)
  2597. if !ok {
  2598. continue
  2599. }
  2600. for _, client := range clients {
  2601. clientMap, ok := client.(map[string]any)
  2602. if !ok {
  2603. continue
  2604. }
  2605. reverse, ok := clientMap["reverse"].(map[string]any)
  2606. if !ok {
  2607. continue
  2608. }
  2609. tag, _ := reverse["tag"].(string)
  2610. tag = strings.TrimSpace(tag)
  2611. if tag != "" {
  2612. tagSet[tag] = struct{}{}
  2613. }
  2614. }
  2615. }
  2616. rawTags := make([]string, 0, len(tagSet))
  2617. for tag := range tagSet {
  2618. rawTags = append(rawTags, tag)
  2619. }
  2620. sort.Strings(rawTags)
  2621. result, _ := json.Marshal(rawTags)
  2622. return string(result), nil
  2623. }
  2624. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  2625. db := database.GetDB()
  2626. query := fmt.Sprintf(
  2627. "DELETE FROM client_traffics WHERE email NOT IN (SELECT %s %s)",
  2628. database.JSONFieldText("client.value", "email"),
  2629. database.JSONClientsFromInbound(),
  2630. )
  2631. db.Exec(query)
  2632. }
  2633. // AddClientStat inserts a per-client accounting row, no-op on email
  2634. // conflict. Xray reports traffic per email, so the surviving row acts as
  2635. // the shared accumulator for inbounds that re-use the same identity.
  2636. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  2637. clientTraffic := xray.ClientTraffic{
  2638. InboundId: inboundId,
  2639. Email: client.Email,
  2640. Total: client.TotalGB,
  2641. ExpiryTime: client.ExpiryTime,
  2642. Enable: client.Enable,
  2643. Reset: client.Reset,
  2644. }
  2645. return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  2646. Create(&clientTraffic).Error
  2647. }
  2648. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  2649. result := tx.Model(xray.ClientTraffic{}).
  2650. Where("email = ?", email).
  2651. Updates(map[string]any{
  2652. "enable": client.Enable,
  2653. "email": client.Email,
  2654. "total": client.TotalGB,
  2655. "expiry_time": client.ExpiryTime,
  2656. "reset": client.Reset,
  2657. })
  2658. err := result.Error
  2659. return err
  2660. }
  2661. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  2662. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  2663. }
  2664. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  2665. if err := tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error; err != nil {
  2666. return err
  2667. }
  2668. return tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error
  2669. }
  2670. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  2671. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  2672. }
  2673. func (s *InboundService) delClientStatsByEmails(tx *gorm.DB, emails []string) error {
  2674. const chunk = 400
  2675. for start := 0; start < len(emails); start += chunk {
  2676. end := min(start+chunk, len(emails))
  2677. batch := emails[start:end]
  2678. if err := tx.Where("email IN ?", batch).Delete(xray.ClientTraffic{}).Error; err != nil {
  2679. return err
  2680. }
  2681. if err := tx.Where("email IN ?", batch).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  2682. return err
  2683. }
  2684. }
  2685. return nil
  2686. }
  2687. func (s *InboundService) delClientIPsByEmails(tx *gorm.DB, emails []string) error {
  2688. const chunk = 400
  2689. for start := 0; start < len(emails); start += chunk {
  2690. end := min(start+chunk, len(emails))
  2691. if err := tx.Where("client_email IN ?", emails[start:end]).Delete(model.InboundClientIps{}).Error; err != nil {
  2692. return err
  2693. }
  2694. }
  2695. return nil
  2696. }
  2697. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  2698. db := database.GetDB()
  2699. var traffics []*xray.ClientTraffic
  2700. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  2701. if err != nil {
  2702. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  2703. return nil, nil, err
  2704. }
  2705. if len(traffics) == 0 {
  2706. return nil, nil, nil
  2707. }
  2708. traffic = traffics[0]
  2709. inbound, err = s.GetInbound(traffic.InboundId)
  2710. if errors.Is(err, gorm.ErrRecordNotFound) {
  2711. // client_traffics.inbound_id goes stale when an inbound is deleted and
  2712. // recreated; fall back to the authoritative client_inbounds link by email.
  2713. ids, idErr := s.clientService.GetInboundIdsForEmail(db, traffic.Email)
  2714. if idErr != nil {
  2715. return traffic, nil, idErr
  2716. }
  2717. if len(ids) > 0 {
  2718. inbound, err = s.GetInbound(ids[0])
  2719. }
  2720. }
  2721. return traffic, inbound, err
  2722. }
  2723. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  2724. db := database.GetDB()
  2725. var traffics []*xray.ClientTraffic
  2726. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  2727. if err != nil {
  2728. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  2729. return nil, nil, err
  2730. }
  2731. if len(traffics) == 0 {
  2732. return nil, nil, nil
  2733. }
  2734. traffic = traffics[0]
  2735. inbound, err = s.GetInbound(traffic.InboundId)
  2736. if errors.Is(err, gorm.ErrRecordNotFound) {
  2737. // client_traffics.inbound_id is a legacy single-inbound pointer that goes
  2738. // stale when an inbound is deleted and recreated: the email-keyed traffic
  2739. // row survives but still references the missing inbound. Fall back to the
  2740. // authoritative client_inbounds link so email lookups (reset, info, …) work.
  2741. ids, idErr := s.clientService.GetInboundIdsForEmail(db, email)
  2742. if idErr != nil {
  2743. return traffic, nil, idErr
  2744. }
  2745. if len(ids) > 0 {
  2746. inbound, err = s.GetInbound(ids[0])
  2747. }
  2748. }
  2749. return traffic, inbound, err
  2750. }
  2751. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  2752. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2753. if err != nil {
  2754. return nil, nil, err
  2755. }
  2756. if inbound == nil {
  2757. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  2758. }
  2759. clients, err := s.GetClients(inbound)
  2760. if err != nil {
  2761. return nil, nil, err
  2762. }
  2763. for _, client := range clients {
  2764. if client.Email == clientEmail {
  2765. return traffic, &client, nil
  2766. }
  2767. }
  2768. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  2769. }
  2770. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  2771. return submitTrafficWrite(func() error {
  2772. db := database.GetDB()
  2773. return db.Model(xray.ClientTraffic{}).
  2774. Where("email = ?", clientEmail).
  2775. Updates(map[string]any{"enable": true, "up": 0, "down": 0}).Error
  2776. })
  2777. }
  2778. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (needRestart bool, err error) {
  2779. err = submitTrafficWrite(func() error {
  2780. var inner error
  2781. needRestart, inner = s.resetClientTrafficLocked(id, clientEmail)
  2782. return inner
  2783. })
  2784. return
  2785. }
  2786. func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (bool, error) {
  2787. needRestart := false
  2788. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  2789. if err != nil {
  2790. return false, err
  2791. }
  2792. if !traffic.Enable {
  2793. inbound, err := s.GetInbound(id)
  2794. if err != nil {
  2795. return false, err
  2796. }
  2797. clients, err := s.GetClients(inbound)
  2798. if err != nil {
  2799. return false, err
  2800. }
  2801. for _, client := range clients {
  2802. if client.Email == clientEmail && client.Enable {
  2803. rt, push, dirty, perr := s.nodePushPlan(inbound)
  2804. if perr != nil {
  2805. return false, perr
  2806. }
  2807. if !push {
  2808. if inbound.NodeID != nil {
  2809. if dirty {
  2810. if dErr := (&NodeService{}).MarkNodeDirty(*inbound.NodeID); dErr != nil {
  2811. logger.Warning("mark node dirty failed:", dErr)
  2812. }
  2813. }
  2814. } else {
  2815. needRestart = true
  2816. }
  2817. break
  2818. }
  2819. cipher := ""
  2820. if string(inbound.Protocol) == "shadowsocks" {
  2821. var oldSettings map[string]any
  2822. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  2823. if err != nil {
  2824. return false, err
  2825. }
  2826. cipher = oldSettings["method"].(string)
  2827. }
  2828. err1 := rt.AddUser(context.Background(), inbound, map[string]any{
  2829. "email": client.Email,
  2830. "id": client.ID,
  2831. "auth": client.Auth,
  2832. "security": client.Security,
  2833. "flow": client.Flow,
  2834. "password": client.Password,
  2835. "cipher": cipher,
  2836. })
  2837. if err1 == nil {
  2838. logger.Debug("Client enabled on", rt.Name(), "due to reset traffic:", clientEmail)
  2839. } else if inbound.NodeID != nil {
  2840. logger.Warning("Error in enabling client on", rt.Name(), ":", err1)
  2841. if dErr := (&NodeService{}).MarkNodeDirty(*inbound.NodeID); dErr != nil {
  2842. logger.Warning("mark node dirty failed:", dErr)
  2843. }
  2844. } else {
  2845. logger.Debug("Error in enabling client on", rt.Name(), ":", err1)
  2846. needRestart = true
  2847. }
  2848. break
  2849. }
  2850. }
  2851. }
  2852. traffic.Up = 0
  2853. traffic.Down = 0
  2854. traffic.Enable = true
  2855. db := database.GetDB()
  2856. err = db.Save(traffic).Error
  2857. if err != nil {
  2858. return false, err
  2859. }
  2860. now := time.Now().UnixMilli()
  2861. _ = db.Model(model.Inbound{}).
  2862. Where("id = ?", id).
  2863. Update("last_traffic_reset_time", now).Error
  2864. inbound, err := s.GetInbound(id)
  2865. if err == nil && inbound != nil && inbound.NodeID != nil {
  2866. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  2867. if e := rt.ResetClientTraffic(context.Background(), inbound, clientEmail); e != nil {
  2868. logger.Warning("ResetClientTraffic: remote propagation to", rt.Name(), "failed:", e)
  2869. }
  2870. } else {
  2871. logger.Warning("ResetClientTraffic: runtime lookup failed:", rterr)
  2872. }
  2873. }
  2874. return needRestart, nil
  2875. }
  2876. func (s *InboundService) ResetAllTraffics() error {
  2877. return submitTrafficWrite(func() error {
  2878. return s.resetAllTrafficsLocked()
  2879. })
  2880. }
  2881. func (s *InboundService) resetAllTrafficsLocked() error {
  2882. db := database.GetDB()
  2883. now := time.Now().UnixMilli()
  2884. if err := db.Model(model.Inbound{}).
  2885. Where("user_id > ?", 0).
  2886. Updates(map[string]any{
  2887. "up": 0,
  2888. "down": 0,
  2889. "last_traffic_reset_time": now,
  2890. }).Error; err != nil {
  2891. return err
  2892. }
  2893. nodes, err := (&NodeService{}).GetAll()
  2894. if err == nil {
  2895. for _, node := range nodes {
  2896. if rt, err := runtime.GetManager().RuntimeFor(&node.Id); err == nil {
  2897. if e := rt.ResetAllTraffics(context.Background()); e != nil {
  2898. logger.Warning("ResetAllTraffics: remote propagation to", rt.Name(), "failed:", e)
  2899. }
  2900. }
  2901. }
  2902. }
  2903. return nil
  2904. }
  2905. func (s *InboundService) ResetInboundTraffic(id int) error {
  2906. return submitTrafficWrite(func() error {
  2907. db := database.GetDB()
  2908. if err := db.Model(model.Inbound{}).
  2909. Where("id = ?", id).
  2910. Updates(map[string]any{"up": 0, "down": 0}).Error; err != nil {
  2911. return err
  2912. }
  2913. inbound, err := s.GetInbound(id)
  2914. if err == nil && inbound != nil && inbound.NodeID != nil {
  2915. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  2916. if e := rt.ResetInboundTraffic(context.Background(), inbound); e != nil {
  2917. logger.Warning("ResetInboundTraffic: remote propagation to", rt.Name(), "failed:", e)
  2918. }
  2919. } else {
  2920. logger.Warning("ResetInboundTraffic: runtime lookup failed:", rterr)
  2921. }
  2922. }
  2923. return nil
  2924. })
  2925. }
  2926. // EmailsByInbound returns the list of client emails currently configured on
  2927. // an inbound's settings.clients[]. Used by the "delete all clients" flow on
  2928. // the inbounds page, which then feeds the list into ClientService.BulkDelete.
  2929. func (s *InboundService) EmailsByInbound(inboundId int) ([]string, error) {
  2930. inbound, err := s.GetInbound(inboundId)
  2931. if err != nil {
  2932. return nil, err
  2933. }
  2934. clients, err := s.GetClients(inbound)
  2935. if err != nil {
  2936. return nil, err
  2937. }
  2938. emails := make([]string, 0, len(clients))
  2939. for _, c := range clients {
  2940. if e := strings.TrimSpace(c.Email); e != "" {
  2941. emails = append(emails, e)
  2942. }
  2943. }
  2944. return emails, nil
  2945. }
  2946. func (s *InboundService) DelDepletedClients(id int) (err error) {
  2947. db := database.GetDB()
  2948. tx := db.Begin()
  2949. defer func() {
  2950. if err == nil {
  2951. tx.Commit()
  2952. } else {
  2953. tx.Rollback()
  2954. }
  2955. }()
  2956. // Collect depleted emails globally — a shared-email row owned by one
  2957. // inbound depletes every sibling that lists the email.
  2958. now := time.Now().Unix() * 1000
  2959. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  2960. var depletedRows []xray.ClientTraffic
  2961. err = db.Model(xray.ClientTraffic{}).
  2962. Where(depletedClause, now).
  2963. Find(&depletedRows).Error
  2964. if err != nil {
  2965. return err
  2966. }
  2967. if len(depletedRows) == 0 {
  2968. return nil
  2969. }
  2970. depletedEmails := make(map[string]struct{}, len(depletedRows))
  2971. for _, r := range depletedRows {
  2972. if r.Email == "" {
  2973. continue
  2974. }
  2975. depletedEmails[strings.ToLower(r.Email)] = struct{}{}
  2976. }
  2977. if len(depletedEmails) == 0 {
  2978. return nil
  2979. }
  2980. var inbounds []*model.Inbound
  2981. inboundQuery := db.Model(model.Inbound{})
  2982. if id >= 0 {
  2983. inboundQuery = inboundQuery.Where("id = ?", id)
  2984. }
  2985. if err = inboundQuery.Find(&inbounds).Error; err != nil {
  2986. return err
  2987. }
  2988. for _, inbound := range inbounds {
  2989. var settings map[string]any
  2990. if err = json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2991. return err
  2992. }
  2993. rawClients, ok := settings["clients"].([]any)
  2994. if !ok {
  2995. continue
  2996. }
  2997. newClients := make([]any, 0, len(rawClients))
  2998. removed := 0
  2999. for _, client := range rawClients {
  3000. c, ok := client.(map[string]any)
  3001. if !ok {
  3002. newClients = append(newClients, client)
  3003. continue
  3004. }
  3005. email, _ := c["email"].(string)
  3006. if _, isDepleted := depletedEmails[strings.ToLower(email)]; isDepleted {
  3007. removed++
  3008. continue
  3009. }
  3010. newClients = append(newClients, client)
  3011. }
  3012. if removed == 0 {
  3013. continue
  3014. }
  3015. if len(newClients) == 0 {
  3016. s.DelInbound(inbound.Id)
  3017. continue
  3018. }
  3019. settings["clients"] = newClients
  3020. ns, mErr := json.MarshalIndent(settings, "", " ")
  3021. if mErr != nil {
  3022. return mErr
  3023. }
  3024. inbound.Settings = string(ns)
  3025. if err = tx.Save(inbound).Error; err != nil {
  3026. return err
  3027. }
  3028. survivingClients, gcErr := s.GetClients(inbound)
  3029. if gcErr != nil {
  3030. err = gcErr
  3031. return err
  3032. }
  3033. if err = s.clientService.SyncInbound(tx, inbound.Id, survivingClients); err != nil {
  3034. return err
  3035. }
  3036. }
  3037. // Drop now-orphaned rows. With id >= 0, a row is safe to drop only when
  3038. // no out-of-scope inbound still references the email.
  3039. if id < 0 {
  3040. err = tx.Where(depletedClause, now).Delete(xray.ClientTraffic{}).Error
  3041. return err
  3042. }
  3043. emails := make([]string, 0, len(depletedEmails))
  3044. for e := range depletedEmails {
  3045. emails = append(emails, e)
  3046. }
  3047. var stillReferenced []string
  3048. emailExpr := database.JSONFieldText("client.value", "email")
  3049. stillQuery := fmt.Sprintf(
  3050. "SELECT DISTINCT LOWER(%s) %s WHERE LOWER(%s) IN ?",
  3051. emailExpr,
  3052. database.JSONClientsFromInbound(),
  3053. emailExpr,
  3054. )
  3055. if err = tx.Raw(stillQuery, emails).Scan(&stillReferenced).Error; err != nil {
  3056. return err
  3057. }
  3058. stillSet := make(map[string]struct{}, len(stillReferenced))
  3059. for _, e := range stillReferenced {
  3060. stillSet[e] = struct{}{}
  3061. }
  3062. toDelete := make([]string, 0, len(emails))
  3063. for _, e := range emails {
  3064. if _, kept := stillSet[e]; !kept {
  3065. toDelete = append(toDelete, e)
  3066. }
  3067. }
  3068. if len(toDelete) > 0 {
  3069. if err = tx.Where("LOWER(email) IN ?", toDelete).Delete(xray.ClientTraffic{}).Error; err != nil {
  3070. return err
  3071. }
  3072. }
  3073. return nil
  3074. }
  3075. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  3076. db := database.GetDB()
  3077. var inbounds []*model.Inbound
  3078. // Retrieve inbounds where settings contain the given tgId
  3079. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  3080. if err != nil && err != gorm.ErrRecordNotFound {
  3081. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  3082. return nil, err
  3083. }
  3084. var emails []string
  3085. for _, inbound := range inbounds {
  3086. clients, err := s.GetClients(inbound)
  3087. if err != nil {
  3088. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  3089. continue
  3090. }
  3091. for _, client := range clients {
  3092. if client.TgID == tgId {
  3093. emails = append(emails, client.Email)
  3094. }
  3095. }
  3096. }
  3097. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  3098. // account owns thousands of clients across inbounds.
  3099. uniqEmails := uniqueNonEmptyStrings(emails)
  3100. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  3101. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  3102. var page []*xray.ClientTraffic
  3103. if err = db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  3104. if err == gorm.ErrRecordNotFound {
  3105. continue
  3106. }
  3107. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  3108. return nil, err
  3109. }
  3110. traffics = append(traffics, page...)
  3111. }
  3112. if len(traffics) == 0 {
  3113. logger.Warning("No ClientTraffic records found for emails:", emails)
  3114. return nil, nil
  3115. }
  3116. // Populate UUID and other client data for each traffic record
  3117. for i := range traffics {
  3118. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  3119. traffics[i].Enable = client.Enable
  3120. traffics[i].UUID = client.ID
  3121. traffics[i].SubId = client.SubID
  3122. }
  3123. }
  3124. return traffics, nil
  3125. }
  3126. // sqliteMaxVars is a safe ceiling for the number of bind parameters in a
  3127. // single SQL statement. SQLite's SQLITE_MAX_VARIABLE_NUMBER is 999 on builds
  3128. // before 3.32 and 32766 after; staying under 999 keeps queries portable
  3129. // across forks/old binaries and also bounds per-query memory on truly large
  3130. // installs (>32k clients) where even modern SQLite would refuse a single IN.
  3131. const sqliteMaxVars = 900
  3132. // uniqueNonEmptyStrings returns a deduplicated copy of in with empty strings
  3133. // removed, preserving the order of first occurrence.
  3134. func uniqueNonEmptyStrings(in []string) []string {
  3135. if len(in) == 0 {
  3136. return nil
  3137. }
  3138. seen := make(map[string]struct{}, len(in))
  3139. out := make([]string, 0, len(in))
  3140. for _, v := range in {
  3141. if v == "" {
  3142. continue
  3143. }
  3144. if _, ok := seen[v]; ok {
  3145. continue
  3146. }
  3147. seen[v] = struct{}{}
  3148. out = append(out, v)
  3149. }
  3150. return out
  3151. }
  3152. // uniqueInts returns a deduplicated copy of in, preserving order of first occurrence.
  3153. func uniqueInts(in []int) []int {
  3154. if len(in) == 0 {
  3155. return nil
  3156. }
  3157. seen := make(map[int]struct{}, len(in))
  3158. out := make([]int, 0, len(in))
  3159. for _, v := range in {
  3160. if _, ok := seen[v]; ok {
  3161. continue
  3162. }
  3163. seen[v] = struct{}{}
  3164. out = append(out, v)
  3165. }
  3166. return out
  3167. }
  3168. // chunkStrings splits s into consecutive sub-slices of at most size elements.
  3169. // Returns nil for an empty input or non-positive size.
  3170. func chunkStrings(s []string, size int) [][]string {
  3171. if size <= 0 || len(s) == 0 {
  3172. return nil
  3173. }
  3174. out := make([][]string, 0, (len(s)+size-1)/size)
  3175. for i := 0; i < len(s); i += size {
  3176. end := min(i+size, len(s))
  3177. out = append(out, s[i:end])
  3178. }
  3179. return out
  3180. }
  3181. // chunkInts splits s into consecutive sub-slices of at most size elements.
  3182. // Returns nil for an empty input or non-positive size.
  3183. func chunkInts(s []int, size int) [][]int {
  3184. if size <= 0 || len(s) == 0 {
  3185. return nil
  3186. }
  3187. out := make([][]int, 0, (len(s)+size-1)/size)
  3188. for i := 0; i < len(s); i += size {
  3189. end := min(i+size, len(s))
  3190. out = append(out, s[i:end])
  3191. }
  3192. return out
  3193. }
  3194. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  3195. uniq := uniqueNonEmptyStrings(emails)
  3196. if len(uniq) == 0 {
  3197. return nil, nil
  3198. }
  3199. db := database.GetDB()
  3200. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  3201. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  3202. var page []*xray.ClientTraffic
  3203. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  3204. return nil, err
  3205. }
  3206. traffics = append(traffics, page...)
  3207. }
  3208. return traffics, nil
  3209. }
  3210. // GetAllClientTraffics returns the full set of client_traffics rows so the
  3211. // websocket broadcasters can ship a complete snapshot every cycle. The old
  3212. // delta-only path (GetActiveClientTraffics on activeEmails) silently dropped
  3213. // the per-client section whenever no client moved bytes in the cycle or a
  3214. // node sync failed, leaving client rows in the UI stuck at stale numbers.
  3215. func (s *InboundService) GetAllClientTraffics() ([]*xray.ClientTraffic, error) {
  3216. db := database.GetDB()
  3217. var traffics []*xray.ClientTraffic
  3218. if err := db.Model(xray.ClientTraffic{}).Find(&traffics).Error; err != nil {
  3219. return nil, err
  3220. }
  3221. return traffics, nil
  3222. }
  3223. type InboundTrafficSummary struct {
  3224. Id int `json:"id"`
  3225. Up int64 `json:"up"`
  3226. Down int64 `json:"down"`
  3227. Total int64 `json:"total"`
  3228. Enable bool `json:"enable"`
  3229. }
  3230. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  3231. db := database.GetDB()
  3232. var summaries []InboundTrafficSummary
  3233. if err := db.Model(&model.Inbound{}).
  3234. Select("id, up, down, total, enable").
  3235. Find(&summaries).Error; err != nil {
  3236. return nil, err
  3237. }
  3238. return summaries, nil
  3239. }
  3240. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  3241. db := database.GetDB()
  3242. var traffics []*xray.ClientTraffic
  3243. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error; err != nil {
  3244. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  3245. return nil, err
  3246. }
  3247. if len(traffics) == 0 {
  3248. return nil, nil
  3249. }
  3250. t := traffics[0]
  3251. if rec, rErr := s.clientService.GetRecordByEmail(db, email); rErr == nil && rec != nil {
  3252. c := rec.ToClient()
  3253. t.UUID = c.ID
  3254. t.SubId = c.SubID
  3255. return t, nil
  3256. }
  3257. t2, client, err := s.GetClientByEmail(email)
  3258. if err != nil {
  3259. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  3260. return nil, err
  3261. }
  3262. if t2 != nil && client != nil {
  3263. t2.UUID = client.ID
  3264. t2.SubId = client.SubID
  3265. return t2, nil
  3266. }
  3267. return nil, nil
  3268. }
  3269. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  3270. return submitTrafficWrite(func() error {
  3271. db := database.GetDB()
  3272. err := db.Model(xray.ClientTraffic{}).
  3273. Where("email = ?", email).
  3274. Updates(map[string]any{
  3275. "up": upload,
  3276. "down": download,
  3277. }).Error
  3278. if err != nil {
  3279. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  3280. }
  3281. return err
  3282. })
  3283. }
  3284. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  3285. db := database.GetDB()
  3286. inbound := &model.Inbound{}
  3287. traffic = &xray.ClientTraffic{}
  3288. // Search for inbound settings that contain the query
  3289. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  3290. if err != nil {
  3291. if err == gorm.ErrRecordNotFound {
  3292. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  3293. return nil, err
  3294. }
  3295. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  3296. return nil, err
  3297. }
  3298. traffic.InboundId = inbound.Id
  3299. // Unmarshal settings to get clients
  3300. settings := map[string][]model.Client{}
  3301. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  3302. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  3303. return nil, err
  3304. }
  3305. clients := settings["clients"]
  3306. for _, client := range clients {
  3307. if (client.ID == query || client.Password == query) && client.Email != "" {
  3308. traffic.Email = client.Email
  3309. break
  3310. }
  3311. }
  3312. if traffic.Email == "" {
  3313. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  3314. return nil, gorm.ErrRecordNotFound
  3315. }
  3316. // Retrieve ClientTraffic based on the found email
  3317. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  3318. if err != nil {
  3319. if err == gorm.ErrRecordNotFound {
  3320. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  3321. return nil, err
  3322. }
  3323. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  3324. return nil, err
  3325. }
  3326. return traffic, nil
  3327. }
  3328. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  3329. db := database.GetDB()
  3330. InboundClientIps := &model.InboundClientIps{}
  3331. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  3332. if err != nil {
  3333. return "", err
  3334. }
  3335. if InboundClientIps.Ips == "" {
  3336. return "", nil
  3337. }
  3338. // Try to parse as new format (with timestamps)
  3339. type IPWithTimestamp struct {
  3340. IP string `json:"ip"`
  3341. Timestamp int64 `json:"timestamp"`
  3342. }
  3343. var ipsWithTime []IPWithTimestamp
  3344. err = json.Unmarshal([]byte(InboundClientIps.Ips), &ipsWithTime)
  3345. // If successfully parsed as new format, return with timestamps
  3346. if err == nil && len(ipsWithTime) > 0 {
  3347. return InboundClientIps.Ips, nil
  3348. }
  3349. // Otherwise, assume it's old format (simple string array)
  3350. // Try to parse as simple array and convert to new format
  3351. var oldIps []string
  3352. err = json.Unmarshal([]byte(InboundClientIps.Ips), &oldIps)
  3353. if err == nil && len(oldIps) > 0 {
  3354. // Convert old format to new format with current timestamp
  3355. newIpsWithTime := make([]IPWithTimestamp, len(oldIps))
  3356. for i, ip := range oldIps {
  3357. newIpsWithTime[i] = IPWithTimestamp{
  3358. IP: ip,
  3359. Timestamp: time.Now().Unix(),
  3360. }
  3361. }
  3362. result, _ := json.Marshal(newIpsWithTime)
  3363. return string(result), nil
  3364. }
  3365. // Return as-is if parsing fails
  3366. return InboundClientIps.Ips, nil
  3367. }
  3368. func (s *InboundService) ClearClientIps(clientEmail string) error {
  3369. db := database.GetDB()
  3370. result := db.Model(model.InboundClientIps{}).
  3371. Where("client_email = ?", clientEmail).
  3372. Update("ips", "")
  3373. err := result.Error
  3374. if err != nil {
  3375. return err
  3376. }
  3377. return nil
  3378. }
  3379. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  3380. db := database.GetDB()
  3381. var inbounds []*model.Inbound
  3382. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  3383. if err != nil && err != gorm.ErrRecordNotFound {
  3384. return nil, err
  3385. }
  3386. return inbounds, nil
  3387. }
  3388. func (s *InboundService) MigrationRequirements() {
  3389. db := database.GetDB()
  3390. tx := db.Begin()
  3391. var err error
  3392. defer func() {
  3393. if err == nil {
  3394. tx.Commit()
  3395. if !database.IsPostgres() {
  3396. if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
  3397. logger.Warningf("VACUUM failed: %v", dbErr)
  3398. }
  3399. }
  3400. } else {
  3401. tx.Rollback()
  3402. }
  3403. }()
  3404. if tx.Migrator().HasColumn(&model.Inbound{}, "all_time") {
  3405. if err = tx.Migrator().DropColumn(&model.Inbound{}, "all_time"); err != nil {
  3406. return
  3407. }
  3408. }
  3409. if tx.Migrator().HasColumn(&xray.ClientTraffic{}, "all_time") {
  3410. if err = tx.Migrator().DropColumn(&xray.ClientTraffic{}, "all_time"); err != nil {
  3411. return
  3412. }
  3413. }
  3414. // Normalize "enable" columns to boolean on Postgres. Legacy SQLite data
  3415. // (0/1 integers), partial migrations, or mixed write paths (public API
  3416. // inbound updates that flow through UpdateClientStat + client syncs, plus
  3417. // node traffic merge deltas) can leave the column as integer or with mixed
  3418. // interpretation. This (combined with the dialect-aware
  3419. // ClientTrafficEnableMergeExpr) prevents type problems in the node traffic
  3420. // sync merge (SetRemoteTraffic) and makes the sync robust even when
  3421. // inbounds are updated via the public API (incl. ones carrying
  3422. // externalProxy in streamSettings). The same expression is also safe on
  3423. // SQLite (no PG :: casts).
  3424. if database.IsPostgres() {
  3425. // Use DO block so it is idempotent and doesn't fail if already boolean.
  3426. normalizeBool := func(table, col string) {
  3427. tx.Exec(fmt.Sprintf(`
  3428. DO $$
  3429. BEGIN
  3430. IF EXISTS (
  3431. SELECT 1 FROM information_schema.columns
  3432. WHERE table_name = '%s' AND column_name = '%s'
  3433. AND data_type <> 'boolean'
  3434. ) THEN
  3435. ALTER TABLE %s ALTER COLUMN %s
  3436. TYPE boolean USING (CASE WHEN %s::text IN ('1','true','t','yes') THEN true ELSE false END);
  3437. END IF;
  3438. END $$;`, table, col, table, col, col))
  3439. }
  3440. normalizeBool("inbounds", "enable")
  3441. normalizeBool("client_traffics", "enable")
  3442. normalizeBool("nodes", "enable")
  3443. normalizeBool("clients", "enable")
  3444. normalizeBool("api_tokens", "enabled")
  3445. normalizeBool("outbound_subscriptions", "enabled")
  3446. }
  3447. // Fix inbounds based problems
  3448. var inbounds []*model.Inbound
  3449. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan", "shadowsocks", "hysteria"}).Find(&inbounds).Error
  3450. if err != nil && err != gorm.ErrRecordNotFound {
  3451. return
  3452. }
  3453. for inbound_index := range inbounds {
  3454. settings := map[string]any{}
  3455. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  3456. if raw, exists := settings["clients"]; exists && raw == nil {
  3457. settings["clients"] = []any{}
  3458. }
  3459. clients, ok := settings["clients"].([]any)
  3460. if ok {
  3461. // Fix Client configuration problems
  3462. newClients := make([]any, 0, len(clients))
  3463. hasVisionFlow := false
  3464. for client_index := range clients {
  3465. c := clients[client_index].(map[string]any)
  3466. // Add email='' if it is not exists
  3467. if _, ok := c["email"]; !ok {
  3468. c["email"] = ""
  3469. }
  3470. // Convert string tgId to int64
  3471. if _, ok := c["tgId"]; ok {
  3472. var tgId any = c["tgId"]
  3473. if tgIdStr, ok2 := tgId.(string); ok2 {
  3474. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  3475. if err == nil {
  3476. c["tgId"] = tgIdInt64
  3477. }
  3478. }
  3479. }
  3480. // Remove "flow": "xtls-rprx-direct"
  3481. if _, ok := c["flow"]; ok {
  3482. if c["flow"] == "xtls-rprx-direct" {
  3483. c["flow"] = ""
  3484. }
  3485. }
  3486. if flow, _ := c["flow"].(string); flow == "xtls-rprx-vision" {
  3487. hasVisionFlow = true
  3488. }
  3489. // Backfill created_at and updated_at
  3490. if _, ok := c["created_at"]; !ok {
  3491. c["created_at"] = time.Now().Unix() * 1000
  3492. }
  3493. c["updated_at"] = time.Now().Unix() * 1000
  3494. newClients = append(newClients, any(c))
  3495. }
  3496. settings["clients"] = newClients
  3497. // Drop orphaned testseed: VLESS-only field, only meaningful when at least
  3498. // one client uses the exact xtls-rprx-vision flow. Older versions saved it
  3499. // for any non-empty flow (including the UDP variant) or kept it after the
  3500. // flow was cleared from the client modal — clean those up here.
  3501. if inbounds[inbound_index].Protocol == model.VLESS && !hasVisionFlow {
  3502. delete(settings, "testseed")
  3503. }
  3504. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  3505. if err != nil {
  3506. return
  3507. }
  3508. inbounds[inbound_index].Settings = string(modifiedSettings)
  3509. }
  3510. // Add client traffic row for all clients which has email
  3511. modelClients, err := s.GetClients(inbounds[inbound_index])
  3512. if err != nil {
  3513. return
  3514. }
  3515. for _, modelClient := range modelClients {
  3516. if len(modelClient.Email) > 0 {
  3517. var count int64
  3518. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  3519. if count == 0 {
  3520. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  3521. }
  3522. }
  3523. }
  3524. // Heal clients table for installs where the one-shot seeder
  3525. // skipped clients due to a tgId-string unmarshal error.
  3526. if syncErr := s.clientService.SyncInbound(tx, inbounds[inbound_index].Id, modelClients); syncErr != nil {
  3527. logger.Warning("MigrationRequirements sync clients failed:", syncErr)
  3528. }
  3529. }
  3530. tx.Save(inbounds)
  3531. // Remove orphaned traffics
  3532. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  3533. // Migrate old MultiDomain to External Proxy
  3534. var externalProxy []struct {
  3535. Id int
  3536. Port int
  3537. StreamSettings string // text column on both DBs; safer than []byte for cross-DB scan
  3538. }
  3539. externalProxyQuery := `select id, port, stream_settings
  3540. from inbounds
  3541. WHERE protocol in ('vmess','vless','trojan')
  3542. AND json_extract(stream_settings, '$.security') = 'tls'
  3543. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`
  3544. if database.IsPostgres() {
  3545. externalProxyQuery = `select id, port, stream_settings
  3546. from inbounds
  3547. WHERE protocol in ('vmess','vless','trojan')
  3548. AND NULLIF(stream_settings, '')::jsonb #>> '{security}' = 'tls'
  3549. AND NULLIF(stream_settings, '')::jsonb #> '{tlsSettings,settings,domains}' IS NOT NULL`
  3550. }
  3551. err = tx.Raw(externalProxyQuery).Scan(&externalProxy).Error
  3552. if err != nil || len(externalProxy) == 0 {
  3553. return
  3554. }
  3555. for _, ep := range externalProxy {
  3556. var reverses any
  3557. var stream map[string]any
  3558. json.Unmarshal([]byte(ep.StreamSettings), &stream)
  3559. if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
  3560. if settings, ok := tlsSettings["settings"].(map[string]any); ok {
  3561. if domains, ok := settings["domains"].([]any); ok {
  3562. for _, domain := range domains {
  3563. if domainMap, ok := domain.(map[string]any); ok {
  3564. domainMap["forceTls"] = "same"
  3565. domainMap["port"] = ep.Port
  3566. domainMap["dest"] = domainMap["domain"].(string)
  3567. delete(domainMap, "domain")
  3568. }
  3569. }
  3570. }
  3571. reverses = settings["domains"]
  3572. delete(settings, "domains")
  3573. }
  3574. }
  3575. stream["externalProxy"] = reverses
  3576. newStream, _ := json.MarshalIndent(stream, " ", " ")
  3577. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  3578. }
  3579. // Legacy tag cleanup for old auto-generated tags (e.g. "0.0.0.0:443-...").
  3580. // Must be cross-DB: INSTR/REPLACE work on SQLite; Postgres needs position().
  3581. tagCleanup := `UPDATE inbounds
  3582. SET tag = REPLACE(tag, '0.0.0.0:', '')
  3583. WHERE INSTR(tag, '0.0.0.0:') > 0;`
  3584. if database.IsPostgres() {
  3585. tagCleanup = `UPDATE inbounds
  3586. SET tag = REPLACE(tag, '0.0.0.0:', '')
  3587. WHERE position('0.0.0.0:' in tag) > 0;`
  3588. }
  3589. err = tx.Raw(tagCleanup).Error
  3590. if err != nil {
  3591. return
  3592. }
  3593. }
  3594. func (s *InboundService) MigrateDB() {
  3595. s.MigrationRequirements()
  3596. s.MigrationRemoveOrphanedTraffics()
  3597. }
  3598. func (s *InboundService) GetOnlineClients() []string {
  3599. if p == nil {
  3600. return []string{}
  3601. }
  3602. return p.GetOnlineClients()
  3603. }
  3604. // GetOnlineClientsByGuid returns online emails keyed by the panelGuid of the
  3605. // node that physically hosts each set: this panel's own clients under its own
  3606. // GUID, plus every node in the tree under its GUID (#4983). Replaces the old
  3607. // node-id keying so a client three hops down is attributed to its real node,
  3608. // not the intermediate one it was synced through.
  3609. func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
  3610. if p == nil {
  3611. return map[string][]string{}
  3612. }
  3613. out := p.GetMergedNodeTrees()
  3614. if local := p.GetLocalOnlineClients(); len(local) > 0 {
  3615. if guid := s.panelGuid(); guid != "" {
  3616. out[guid] = mergeEmails(out[guid], local)
  3617. }
  3618. }
  3619. return out
  3620. }
  3621. // GetActiveInboundsByGuid returns the inbound tags that carried traffic within
  3622. // the grace window for THIS panel, under its own GUID. Remote nodes don't
  3623. // report per-inbound activity, so a GUID missing from the map means "don't
  3624. // gate" for that node's inbounds.
  3625. func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
  3626. if p == nil {
  3627. return map[string][]string{}
  3628. }
  3629. active := p.GetLocalActiveInbounds()
  3630. if len(active) == 0 {
  3631. return map[string][]string{}
  3632. }
  3633. guid := s.panelGuid()
  3634. if guid == "" {
  3635. return map[string][]string{}
  3636. }
  3637. return map[string][]string{guid: active}
  3638. }
  3639. func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  3640. if p != nil {
  3641. p.SetNodeOnlineTree(nodeID, tree)
  3642. }
  3643. }
  3644. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  3645. if p != nil {
  3646. p.ClearNodeOnlineClients(nodeID)
  3647. }
  3648. }
  3649. // panelGuid returns this panel's stable self-identifier, used to key the local
  3650. // panel's own clients in the per-node online maps (#4983).
  3651. func (s *InboundService) panelGuid() string {
  3652. guid, _ := (&SettingService{}).GetPanelGuid()
  3653. return guid
  3654. }
  3655. // synthNodeGuid is the stable per-node fallback identity for a directly-attached
  3656. // node whose panel hasn't reported a panelGuid yet (old build). Node ids are
  3657. // master-local, so this only composes for direct nodes — exactly the pre-#4983
  3658. // flat-topology case where an old-build node appears.
  3659. func synthNodeGuid(nodeID int) string {
  3660. return fmt.Sprintf("node:%d", nodeID)
  3661. }
  3662. // mergeEmails returns the deduped union of two email slices.
  3663. func mergeEmails(a, b []string) []string {
  3664. if len(a) == 0 {
  3665. return b
  3666. }
  3667. seen := make(map[string]struct{}, len(a)+len(b))
  3668. out := make([]string, 0, len(a)+len(b))
  3669. for _, e := range a {
  3670. if _, ok := seen[e]; !ok {
  3671. seen[e] = struct{}{}
  3672. out = append(out, e)
  3673. }
  3674. }
  3675. for _, e := range b {
  3676. if _, ok := seen[e]; !ok {
  3677. seen[e] = struct{}{}
  3678. out = append(out, e)
  3679. }
  3680. }
  3681. return out
  3682. }
  3683. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  3684. db := database.GetDB()
  3685. var rows []xray.ClientTraffic
  3686. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  3687. if err != nil && err != gorm.ErrRecordNotFound {
  3688. return nil, err
  3689. }
  3690. result := make(map[string]int64, len(rows))
  3691. for _, r := range rows {
  3692. result[r.Email] = r.LastOnline
  3693. }
  3694. return result, nil
  3695. }
  3696. // RefreshLocalOnlineClients folds the emails and inbound tags active on this
  3697. // panel's own xray this poll into the local online/active sets, applying the
  3698. // grace window and pruning stale entries. Pass nil to only prune. See
  3699. // xray.Process for why the local sets are kept separate from the shared
  3700. // last_online column.
  3701. func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
  3702. if p != nil {
  3703. p.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
  3704. }
  3705. }
  3706. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  3707. db := database.GetDB()
  3708. // Step 1: Get ClientTraffic records for emails in the input list.
  3709. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  3710. uniqEmails := uniqueNonEmptyStrings(emails)
  3711. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  3712. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  3713. var page []xray.ClientTraffic
  3714. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && err != gorm.ErrRecordNotFound {
  3715. return nil, nil, err
  3716. }
  3717. clients = append(clients, page...)
  3718. }
  3719. // Step 2: Sort clients by (Up + Down) descending
  3720. sort.Slice(clients, func(i, j int) bool {
  3721. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  3722. })
  3723. // Step 3: Extract sorted valid emails and track found ones
  3724. validEmails := make([]string, 0, len(clients))
  3725. found := make(map[string]bool)
  3726. for _, client := range clients {
  3727. validEmails = append(validEmails, client.Email)
  3728. found[client.Email] = true
  3729. }
  3730. // Step 4: Identify emails that were not found in the database
  3731. extraEmails := make([]string, 0)
  3732. for _, email := range emails {
  3733. if !found[email] {
  3734. extraEmails = append(extraEmails, email)
  3735. }
  3736. }
  3737. return validEmails, extraEmails, nil
  3738. }
  3739. type SubLinkProvider interface {
  3740. SubLinksForSubId(host, subId string) ([]string, error)
  3741. LinksForClient(host string, inbound *model.Inbound, email string) []string
  3742. }
  3743. var registeredSubLinkProvider SubLinkProvider
  3744. func RegisterSubLinkProvider(p SubLinkProvider) {
  3745. registeredSubLinkProvider = p
  3746. }
  3747. func (s *InboundService) GetSubLinks(host, subId string) ([]string, error) {
  3748. if registeredSubLinkProvider == nil {
  3749. return nil, common.NewError("sub link provider not registered")
  3750. }
  3751. return registeredSubLinkProvider.SubLinksForSubId(host, subId)
  3752. }
  3753. func (s *InboundService) GetAllClientLinks(host string, email string) ([]string, error) {
  3754. if email == "" {
  3755. return nil, common.NewError("client email is required")
  3756. }
  3757. if registeredSubLinkProvider == nil {
  3758. return nil, common.NewError("sub link provider not registered")
  3759. }
  3760. rec, err := s.clientService.GetRecordByEmail(nil, email)
  3761. if err != nil {
  3762. return nil, err
  3763. }
  3764. inboundIds, err := s.clientService.GetInboundIdsForRecord(rec.Id)
  3765. if err != nil {
  3766. return nil, err
  3767. }
  3768. var links []string
  3769. for _, ibId := range inboundIds {
  3770. inbound, getErr := s.GetInbound(ibId)
  3771. if getErr != nil {
  3772. return nil, getErr
  3773. }
  3774. links = append(links, registeredSubLinkProvider.LinksForClient(host, inbound, email)...)
  3775. }
  3776. return links, nil
  3777. }