inbound.go 100 KB

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