inbound.go 114 KB

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