inbound.go 109 KB

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