inbound.go 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224
  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).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).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)
  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. return needRestart, db.Delete(model.Inbound{}, id).Error
  577. }
  578. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  579. db := database.GetDB()
  580. inbound := &model.Inbound{}
  581. err := db.Model(model.Inbound{}).First(inbound, id).Error
  582. if err != nil {
  583. return nil, err
  584. }
  585. return inbound, nil
  586. }
  587. func (s *InboundService) GetInboundDetail(id int) (*model.Inbound, error) {
  588. db := database.GetDB()
  589. inbound := &model.Inbound{}
  590. err := db.Model(model.Inbound{}).Preload("ClientStats").First(inbound, id).Error
  591. if err != nil {
  592. return nil, err
  593. }
  594. s.enrichClientStats(db, []*model.Inbound{inbound})
  595. return inbound, nil
  596. }
  597. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  598. inbound, err := s.GetInbound(id)
  599. if err != nil {
  600. return false, err
  601. }
  602. if inbound.Enable == enable {
  603. return false, nil
  604. }
  605. db := database.GetDB()
  606. if err := db.Model(model.Inbound{}).Where("id = ?", id).
  607. Update("enable", enable).Error; err != nil {
  608. return false, err
  609. }
  610. inbound.Enable = enable
  611. needRestart := false
  612. rt, rterr := s.runtimeFor(inbound)
  613. if rterr != nil {
  614. if inbound.NodeID != nil {
  615. return false, rterr
  616. }
  617. return true, nil
  618. }
  619. // Remote nodes interpret DelInbound as a real row delete (it hits
  620. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  621. // switch on a remote inbound used to wipe the row entirely (#4402).
  622. // PATCH the remote row via UpdateInbound instead — preserves the
  623. // settings/client history and just flips the enable flag.
  624. if inbound.NodeID != nil {
  625. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  626. logger.Debug("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  627. return false, err
  628. }
  629. return false, nil
  630. }
  631. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  632. !strings.Contains(err.Error(), "not found") {
  633. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  634. needRestart = true
  635. }
  636. if !enable {
  637. return needRestart, nil
  638. }
  639. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  640. if err != nil {
  641. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  642. return true, nil
  643. }
  644. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  645. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  646. needRestart = true
  647. }
  648. return needRestart, nil
  649. }
  650. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  651. // Normalize streamSettings based on protocol
  652. s.normalizeStreamSettings(inbound)
  653. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  654. if err != nil {
  655. return inbound, false, err
  656. }
  657. if conflict != nil {
  658. return inbound, false, common.NewError(conflict.String())
  659. }
  660. oldInbound, err := s.GetInbound(inbound.Id)
  661. if err != nil {
  662. return inbound, false, err
  663. }
  664. tag := oldInbound.Tag
  665. db := database.GetDB()
  666. tx := db.Begin()
  667. defer func() {
  668. if err != nil {
  669. tx.Rollback()
  670. } else {
  671. tx.Commit()
  672. }
  673. }()
  674. err = s.updateClientTraffics(tx, oldInbound, inbound)
  675. if err != nil {
  676. return inbound, false, err
  677. }
  678. // Ensure created_at and updated_at exist in inbound.Settings clients
  679. {
  680. var oldSettings map[string]any
  681. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  682. emailToCreated := map[string]int64{}
  683. emailToUpdated := map[string]int64{}
  684. if oldSettings != nil {
  685. if oc, ok := oldSettings["clients"].([]any); ok {
  686. for _, it := range oc {
  687. if m, ok2 := it.(map[string]any); ok2 {
  688. if email, ok3 := m["email"].(string); ok3 {
  689. switch v := m["created_at"].(type) {
  690. case float64:
  691. emailToCreated[email] = int64(v)
  692. case int64:
  693. emailToCreated[email] = v
  694. }
  695. switch v := m["updated_at"].(type) {
  696. case float64:
  697. emailToUpdated[email] = int64(v)
  698. case int64:
  699. emailToUpdated[email] = v
  700. }
  701. }
  702. }
  703. }
  704. }
  705. }
  706. var newSettings map[string]any
  707. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  708. now := time.Now().Unix() * 1000
  709. if nSlice, ok := newSettings["clients"].([]any); ok {
  710. for i := range nSlice {
  711. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  712. email, _ := m["email"].(string)
  713. if _, ok3 := m["created_at"]; !ok3 {
  714. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  715. m["created_at"] = v
  716. } else {
  717. m["created_at"] = now
  718. }
  719. }
  720. // Preserve client's updated_at if present; do not bump on parent inbound update
  721. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  722. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  723. m["updated_at"] = v
  724. }
  725. }
  726. nSlice[i] = m
  727. }
  728. }
  729. newSettings["clients"] = nSlice
  730. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  731. inbound.Settings = string(bs)
  732. }
  733. }
  734. }
  735. }
  736. oldInbound.Total = inbound.Total
  737. oldInbound.Remark = inbound.Remark
  738. oldInbound.Enable = inbound.Enable
  739. oldInbound.ExpiryTime = inbound.ExpiryTime
  740. oldInbound.TrafficReset = inbound.TrafficReset
  741. oldInbound.Listen = inbound.Listen
  742. oldInbound.Port = inbound.Port
  743. oldInbound.Protocol = inbound.Protocol
  744. oldInbound.Settings = inbound.Settings
  745. oldInbound.StreamSettings = inbound.StreamSettings
  746. oldInbound.Sniffing = inbound.Sniffing
  747. oldInbound.Tag, err = s.resolveInboundTag(inbound, inbound.Id)
  748. if err != nil {
  749. return inbound, false, err
  750. }
  751. needRestart := false
  752. rt, rterr := s.runtimeFor(oldInbound)
  753. if rterr != nil {
  754. if oldInbound.NodeID != nil {
  755. err = rterr
  756. return inbound, false, err
  757. }
  758. needRestart = true
  759. } else {
  760. oldSnapshot := *oldInbound
  761. oldSnapshot.Tag = tag
  762. if oldInbound.NodeID == nil {
  763. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  764. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  765. }
  766. if inbound.Enable {
  767. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  768. if err2 != nil {
  769. logger.Debug("Unable to prepare runtime inbound config:", err2)
  770. needRestart = true
  771. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  772. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  773. } else {
  774. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  775. needRestart = true
  776. }
  777. }
  778. } else {
  779. if !inbound.Enable {
  780. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  781. err = err2
  782. return inbound, false, err
  783. }
  784. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  785. err = err2
  786. return inbound, false, err
  787. }
  788. }
  789. }
  790. if err = tx.Save(oldInbound).Error; err != nil {
  791. return inbound, false, err
  792. }
  793. newClients, gcErr := s.GetClients(oldInbound)
  794. if gcErr != nil {
  795. err = gcErr
  796. return inbound, false, err
  797. }
  798. if err = s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  799. return inbound, false, err
  800. }
  801. return inbound, needRestart, nil
  802. }
  803. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  804. if inbound == nil {
  805. return nil, fmt.Errorf("inbound is nil")
  806. }
  807. runtimeInbound := *inbound
  808. settings := map[string]any{}
  809. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  810. return nil, err
  811. }
  812. clients, ok := settings["clients"].([]any)
  813. if !ok {
  814. return &runtimeInbound, nil
  815. }
  816. var clientStats []xray.ClientTraffic
  817. err := tx.Model(xray.ClientTraffic{}).
  818. Where("inbound_id = ?", inbound.Id).
  819. Select("email", "enable").
  820. Find(&clientStats).Error
  821. if err != nil {
  822. return nil, err
  823. }
  824. enableMap := make(map[string]bool, len(clientStats))
  825. for _, clientTraffic := range clientStats {
  826. enableMap[clientTraffic.Email] = clientTraffic.Enable
  827. }
  828. finalClients := make([]any, 0, len(clients))
  829. for _, client := range clients {
  830. c, ok := client.(map[string]any)
  831. if !ok {
  832. continue
  833. }
  834. email, _ := c["email"].(string)
  835. if enable, exists := enableMap[email]; exists && !enable {
  836. continue
  837. }
  838. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  839. continue
  840. }
  841. finalClients = append(finalClients, c)
  842. }
  843. settings["clients"] = finalClients
  844. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  845. if err != nil {
  846. return nil, err
  847. }
  848. runtimeInbound.Settings = string(modifiedSettings)
  849. return &runtimeInbound, nil
  850. }
  851. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  852. // list: removes rows for emails that disappeared, inserts rows for newly-added
  853. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  854. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  855. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  856. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  857. oldClients, err := s.GetClients(oldInbound)
  858. if err != nil {
  859. return err
  860. }
  861. newClients, err := s.GetClients(newInbound)
  862. if err != nil {
  863. return err
  864. }
  865. // Email is the unique key for ClientTraffic rows. Clients without an
  866. // email have no stats row to sync — skip them on both sides instead of
  867. // risking a unique-constraint hit or accidental delete of an unrelated row.
  868. oldEmails := make(map[string]struct{}, len(oldClients))
  869. for i := range oldClients {
  870. if oldClients[i].Email == "" {
  871. continue
  872. }
  873. oldEmails[oldClients[i].Email] = struct{}{}
  874. }
  875. newEmails := make(map[string]struct{}, len(newClients))
  876. for i := range newClients {
  877. if newClients[i].Email == "" {
  878. continue
  879. }
  880. newEmails[newClients[i].Email] = struct{}{}
  881. }
  882. // Drop stats rows for removed emails — but not when a sibling inbound
  883. // still references the email, since the row is the shared accumulator.
  884. for i := range oldClients {
  885. email := oldClients[i].Email
  886. if email == "" {
  887. continue
  888. }
  889. if _, kept := newEmails[email]; kept {
  890. continue
  891. }
  892. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  893. if err != nil {
  894. return err
  895. }
  896. if stillUsed {
  897. continue
  898. }
  899. if err := s.DelClientStat(tx, email); err != nil {
  900. return err
  901. }
  902. }
  903. for i := range newClients {
  904. email := newClients[i].Email
  905. if email == "" {
  906. continue
  907. }
  908. if _, existed := oldEmails[email]; existed {
  909. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  910. return err
  911. }
  912. continue
  913. }
  914. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  915. return err
  916. }
  917. }
  918. return nil
  919. }
  920. func (s *InboundService) getClientPrimaryKey(protocol model.Protocol, client model.Client) string {
  921. switch protocol {
  922. case model.Trojan:
  923. return client.Password
  924. case model.Shadowsocks:
  925. return client.Email
  926. case model.Hysteria:
  927. return client.Auth
  928. default:
  929. return client.ID
  930. }
  931. }
  932. func (s *InboundService) writeBackClientSubID(sourceInboundID int, sourceProtocol model.Protocol, client model.Client, subID string) (bool, error) {
  933. client.SubID = subID
  934. client.UpdatedAt = time.Now().UnixMilli()
  935. clientID := s.getClientPrimaryKey(sourceProtocol, client)
  936. if clientID == "" {
  937. return false, common.NewError("empty client ID")
  938. }
  939. settingsBytes, err := json.Marshal(map[string][]model.Client{
  940. "clients": {client},
  941. })
  942. if err != nil {
  943. return false, err
  944. }
  945. updatePayload := &model.Inbound{
  946. Id: sourceInboundID,
  947. Settings: string(settingsBytes),
  948. }
  949. return s.clientService.UpdateInboundClient(s, updatePayload, clientID)
  950. }
  951. func (s *InboundService) generateRandomCredential(targetProtocol model.Protocol) string {
  952. switch targetProtocol {
  953. case model.VMESS, model.VLESS:
  954. return uuid.NewString()
  955. default:
  956. return strings.ReplaceAll(uuid.NewString(), "-", "")
  957. }
  958. }
  959. func (s *InboundService) buildTargetClientFromSource(source model.Client, targetInbound *model.Inbound, email string, flow string) (model.Client, error) {
  960. nowTs := time.Now().UnixMilli()
  961. target := source
  962. target.Email = email
  963. target.CreatedAt = nowTs
  964. target.UpdatedAt = nowTs
  965. target.ID = ""
  966. target.Password = ""
  967. target.Auth = ""
  968. target.Flow = ""
  969. targetProtocol := targetInbound.Protocol
  970. switch targetProtocol {
  971. case model.VMESS:
  972. target.ID = s.generateRandomCredential(targetProtocol)
  973. case model.VLESS:
  974. target.ID = s.generateRandomCredential(targetProtocol)
  975. if (flow == "xtls-rprx-vision" || flow == "xtls-rprx-vision-udp443") &&
  976. inboundCanEnableTlsFlow(string(targetProtocol), targetInbound.StreamSettings) {
  977. target.Flow = flow
  978. }
  979. case model.Trojan, model.Shadowsocks:
  980. target.Password = s.generateRandomCredential(targetProtocol)
  981. case model.Hysteria:
  982. target.Auth = s.generateRandomCredential(targetProtocol)
  983. default:
  984. target.ID = s.generateRandomCredential(targetProtocol)
  985. }
  986. return target, nil
  987. }
  988. func (s *InboundService) nextAvailableCopiedEmail(originalEmail string, targetID int, occupied map[string]struct{}) string {
  989. base := fmt.Sprintf("%s_%d", originalEmail, targetID)
  990. candidate := base
  991. suffix := 0
  992. for {
  993. if _, exists := occupied[strings.ToLower(candidate)]; !exists {
  994. occupied[strings.ToLower(candidate)] = struct{}{}
  995. return candidate
  996. }
  997. suffix++
  998. candidate = fmt.Sprintf("%s_%d", base, suffix)
  999. }
  1000. }
  1001. func (s *InboundService) CopyInboundClients(targetInboundID int, sourceInboundID int, clientEmails []string, flow string) (*CopyClientsResult, bool, error) {
  1002. result := &CopyClientsResult{
  1003. Added: []string{},
  1004. Skipped: []string{},
  1005. Errors: []string{},
  1006. }
  1007. if targetInboundID == sourceInboundID {
  1008. return result, false, common.NewError("source and target inbounds must be different")
  1009. }
  1010. targetInbound, err := s.GetInbound(targetInboundID)
  1011. if err != nil {
  1012. return result, false, err
  1013. }
  1014. sourceInbound, err := s.GetInbound(sourceInboundID)
  1015. if err != nil {
  1016. return result, false, err
  1017. }
  1018. sourceClients, err := s.GetClients(sourceInbound)
  1019. if err != nil {
  1020. return result, false, err
  1021. }
  1022. if len(sourceClients) == 0 {
  1023. return result, false, nil
  1024. }
  1025. allowedEmails := map[string]struct{}{}
  1026. if len(clientEmails) > 0 {
  1027. for _, email := range clientEmails {
  1028. allowedEmails[strings.ToLower(strings.TrimSpace(email))] = struct{}{}
  1029. }
  1030. }
  1031. occupiedEmails := map[string]struct{}{}
  1032. allEmails, err := s.getAllEmails()
  1033. if err != nil {
  1034. return result, false, err
  1035. }
  1036. for _, email := range allEmails {
  1037. clean := strings.Trim(email, "\"")
  1038. if clean != "" {
  1039. occupiedEmails[strings.ToLower(clean)] = struct{}{}
  1040. }
  1041. }
  1042. newClients := make([]model.Client, 0)
  1043. needRestart := false
  1044. for _, sourceClient := range sourceClients {
  1045. originalEmail := strings.TrimSpace(sourceClient.Email)
  1046. if originalEmail == "" {
  1047. continue
  1048. }
  1049. if len(allowedEmails) > 0 {
  1050. if _, ok := allowedEmails[strings.ToLower(originalEmail)]; !ok {
  1051. continue
  1052. }
  1053. }
  1054. if sourceClient.SubID == "" {
  1055. newSubID := uuid.NewString()
  1056. subNeedRestart, subErr := s.writeBackClientSubID(sourceInbound.Id, sourceInbound.Protocol, sourceClient, newSubID)
  1057. if subErr != nil {
  1058. result.Errors = append(result.Errors, fmt.Sprintf("%s: failed to write source subId: %v", originalEmail, subErr))
  1059. continue
  1060. }
  1061. if subNeedRestart {
  1062. needRestart = true
  1063. }
  1064. sourceClient.SubID = newSubID
  1065. }
  1066. targetEmail := s.nextAvailableCopiedEmail(originalEmail, targetInboundID, occupiedEmails)
  1067. targetClient, buildErr := s.buildTargetClientFromSource(sourceClient, targetInbound, targetEmail, flow)
  1068. if buildErr != nil {
  1069. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", originalEmail, buildErr))
  1070. continue
  1071. }
  1072. newClients = append(newClients, targetClient)
  1073. result.Added = append(result.Added, targetEmail)
  1074. }
  1075. if len(newClients) == 0 {
  1076. return result, needRestart, nil
  1077. }
  1078. settingsPayload, err := json.Marshal(map[string][]model.Client{
  1079. "clients": newClients,
  1080. })
  1081. if err != nil {
  1082. return result, needRestart, err
  1083. }
  1084. addNeedRestart, err := s.clientService.AddInboundClient(s, &model.Inbound{
  1085. Id: targetInboundID,
  1086. Settings: string(settingsPayload),
  1087. })
  1088. if err != nil {
  1089. return result, needRestart, err
  1090. }
  1091. if addNeedRestart {
  1092. needRestart = true
  1093. }
  1094. return result, needRestart, nil
  1095. }
  1096. const resetGracePeriodMs int64 = 30000
  1097. // onlineGracePeriodMs must comfortably exceed the 5s traffic-poll interval —
  1098. // Xray's stats counters often report a zero delta for an active session across
  1099. // a single poll, so a 5s grace would still drop the client on the next tick.
  1100. // ~4 polls of slack keeps idle-but-connected clients visible without lingering
  1101. // long after a real disconnect.
  1102. const onlineGracePeriodMs int64 = 20000
  1103. func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot) (bool, error) {
  1104. var structuralChange bool
  1105. err := submitTrafficWrite(func() error {
  1106. var inner error
  1107. structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap)
  1108. return inner
  1109. })
  1110. return structuralChange, err
  1111. }
  1112. func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.TrafficSnapshot) (bool, error) {
  1113. if snap == nil || nodeID <= 0 {
  1114. return false, nil
  1115. }
  1116. db := database.GetDB()
  1117. now := time.Now().UnixMilli()
  1118. var central []model.Inbound
  1119. if err := db.Model(model.Inbound{}).
  1120. Where("node_id = ?", nodeID).
  1121. Find(&central).Error; err != nil {
  1122. return false, err
  1123. }
  1124. // Index under both stored tag and the prefix-stripped form so a snap's
  1125. // bare tag resolves whether or not we rewrote it with n<id>- at create.
  1126. tagToCentral := make(map[string]*model.Inbound, len(central)*2)
  1127. prefix := nodeTagPrefix(&nodeID)
  1128. for i := range central {
  1129. tagToCentral[central[i].Tag] = &central[i]
  1130. if prefix != "" && strings.HasPrefix(central[i].Tag, prefix) {
  1131. tagToCentral[strings.TrimPrefix(central[i].Tag, prefix)] = &central[i]
  1132. }
  1133. }
  1134. var centralClientStats []xray.ClientTraffic
  1135. if len(central) > 0 {
  1136. ids := make([]int, 0, len(central))
  1137. for i := range central {
  1138. ids = append(ids, central[i].Id)
  1139. }
  1140. if err := db.Model(xray.ClientTraffic{}).
  1141. Where("inbound_id IN ?", ids).
  1142. Find(&centralClientStats).Error; err != nil {
  1143. return false, err
  1144. }
  1145. }
  1146. type csKey struct {
  1147. inboundID int
  1148. email string
  1149. }
  1150. centralCS := make(map[csKey]*xray.ClientTraffic, len(centralClientStats))
  1151. centralCSByEmail := make(map[string]*xray.ClientTraffic, len(centralClientStats))
  1152. for i := range centralClientStats {
  1153. centralCS[csKey{centralClientStats[i].InboundId, centralClientStats[i].Email}] = &centralClientStats[i]
  1154. centralCSByEmail[centralClientStats[i].Email] = &centralClientStats[i]
  1155. }
  1156. var defaultUserId int
  1157. if len(central) > 0 {
  1158. defaultUserId = central[0].UserId
  1159. } else {
  1160. var u model.User
  1161. if err := db.Model(model.User{}).Order("id asc").First(&u).Error; err == nil {
  1162. defaultUserId = u.Id
  1163. } else {
  1164. defaultUserId = 1
  1165. }
  1166. }
  1167. tx := db.Begin()
  1168. committed := false
  1169. defer func() {
  1170. if !committed {
  1171. tx.Rollback()
  1172. }
  1173. }()
  1174. structuralChange := false
  1175. snapTags := make(map[string]struct{}, len(snap.Inbounds))
  1176. for _, snapIb := range snap.Inbounds {
  1177. if snapIb == nil {
  1178. continue
  1179. }
  1180. snapTags[snapIb.Tag] = struct{}{}
  1181. c, ok := tagToCentral[snapIb.Tag]
  1182. if !ok {
  1183. // Try snap.Tag first; on collision fall back to the n<id>-
  1184. // prefixed form so local+node can both own the same port.
  1185. pickFreeTag := func() (string, error) {
  1186. candidates := []string{snapIb.Tag}
  1187. if prefix != "" && !strings.HasPrefix(snapIb.Tag, prefix) {
  1188. candidates = append(candidates, prefix+snapIb.Tag)
  1189. }
  1190. for _, t := range candidates {
  1191. var owner model.Inbound
  1192. err := tx.Where("tag = ?", t).First(&owner).Error
  1193. if errors.Is(err, gorm.ErrRecordNotFound) {
  1194. return t, nil
  1195. }
  1196. if err != nil {
  1197. return "", err
  1198. }
  1199. }
  1200. return "", nil
  1201. }
  1202. chosenTag, err := pickFreeTag()
  1203. if err != nil {
  1204. logger.Warningf("setRemoteTraffic: check tag %q failed: %v", snapIb.Tag, err)
  1205. continue
  1206. }
  1207. if chosenTag == "" {
  1208. key := fmt.Sprintf("%d:%s", nodeID, snapIb.Tag)
  1209. if _, seen := reportedRemoteTagConflict.LoadOrStore(key, struct{}{}); !seen {
  1210. logger.Warningf(
  1211. "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)",
  1212. snapIb.Tag, nodeID, nodeID,
  1213. )
  1214. }
  1215. continue
  1216. }
  1217. newIb := model.Inbound{
  1218. UserId: defaultUserId,
  1219. NodeID: &nodeID,
  1220. Tag: chosenTag,
  1221. Listen: snapIb.Listen,
  1222. Port: snapIb.Port,
  1223. Protocol: snapIb.Protocol,
  1224. Settings: snapIb.Settings,
  1225. StreamSettings: snapIb.StreamSettings,
  1226. Sniffing: snapIb.Sniffing,
  1227. TrafficReset: snapIb.TrafficReset,
  1228. Enable: snapIb.Enable,
  1229. Remark: snapIb.Remark,
  1230. Total: snapIb.Total,
  1231. ExpiryTime: snapIb.ExpiryTime,
  1232. Up: snapIb.Up,
  1233. Down: snapIb.Down,
  1234. }
  1235. if err := tx.Create(&newIb).Error; err != nil {
  1236. logger.Warningf("setRemoteTraffic: create central inbound for tag %q failed: %v", snapIb.Tag, err)
  1237. continue
  1238. }
  1239. tagToCentral[snapIb.Tag] = &newIb
  1240. if newIb.Tag != snapIb.Tag {
  1241. tagToCentral[newIb.Tag] = &newIb
  1242. }
  1243. structuralChange = true
  1244. continue
  1245. }
  1246. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  1247. updates := map[string]any{
  1248. "enable": snapIb.Enable,
  1249. "remark": snapIb.Remark,
  1250. "listen": snapIb.Listen,
  1251. "port": snapIb.Port,
  1252. "protocol": snapIb.Protocol,
  1253. "total": snapIb.Total,
  1254. "expiry_time": snapIb.ExpiryTime,
  1255. "settings": snapIb.Settings,
  1256. "stream_settings": snapIb.StreamSettings,
  1257. "sniffing": snapIb.Sniffing,
  1258. "traffic_reset": snapIb.TrafficReset,
  1259. }
  1260. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  1261. updates["up"] = snapIb.Up
  1262. updates["down"] = snapIb.Down
  1263. }
  1264. if c.Settings != snapIb.Settings ||
  1265. c.Remark != snapIb.Remark ||
  1266. c.Listen != snapIb.Listen ||
  1267. c.Port != snapIb.Port ||
  1268. c.Total != snapIb.Total ||
  1269. c.ExpiryTime != snapIb.ExpiryTime ||
  1270. c.Enable != snapIb.Enable {
  1271. structuralChange = true
  1272. }
  1273. if err := tx.Model(model.Inbound{}).
  1274. Where("id = ?", c.Id).
  1275. Updates(updates).Error; err != nil {
  1276. return false, err
  1277. }
  1278. }
  1279. for _, c := range central {
  1280. if _, kept := snapTags[c.Tag]; kept {
  1281. continue
  1282. }
  1283. if err := tx.Where("inbound_id = ?", c.Id).
  1284. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1285. return false, err
  1286. }
  1287. if err := s.clientService.DetachInbound(tx, c.Id); err != nil {
  1288. return false, err
  1289. }
  1290. if err := tx.Where("id = ?", c.Id).
  1291. Delete(&model.Inbound{}).Error; err != nil {
  1292. return false, err
  1293. }
  1294. delete(tagToCentral, c.Tag)
  1295. structuralChange = true
  1296. }
  1297. for _, snapIb := range snap.Inbounds {
  1298. if snapIb == nil {
  1299. continue
  1300. }
  1301. c, ok := tagToCentral[snapIb.Tag]
  1302. if !ok {
  1303. continue
  1304. }
  1305. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  1306. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  1307. for _, cs := range snapIb.ClientStats {
  1308. snapEmails[cs.Email] = struct{}{}
  1309. existing := centralCS[csKey{c.Id, cs.Email}]
  1310. if existing == nil {
  1311. existing = centralCSByEmail[cs.Email]
  1312. }
  1313. if existing == nil {
  1314. row := &xray.ClientTraffic{
  1315. InboundId: c.Id,
  1316. Email: cs.Email,
  1317. Enable: cs.Enable,
  1318. Total: cs.Total,
  1319. ExpiryTime: cs.ExpiryTime,
  1320. Reset: cs.Reset,
  1321. Up: cs.Up,
  1322. Down: cs.Down,
  1323. LastOnline: cs.LastOnline,
  1324. }
  1325. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  1326. Create(row).Error; err != nil {
  1327. return false, err
  1328. }
  1329. centralCS[csKey{c.Id, cs.Email}] = row
  1330. centralCSByEmail[cs.Email] = row
  1331. structuralChange = true
  1332. continue
  1333. }
  1334. if existing.Enable != cs.Enable ||
  1335. existing.Total != cs.Total ||
  1336. existing.ExpiryTime != cs.ExpiryTime ||
  1337. existing.Reset != cs.Reset {
  1338. structuralChange = true
  1339. }
  1340. if inGrace && cs.Up+cs.Down > 0 {
  1341. if err := tx.Exec(
  1342. `UPDATE client_traffics
  1343. SET enable = ?, total = ?, expiry_time = ?, reset = ?
  1344. WHERE email = ?`,
  1345. cs.Enable, cs.Total, cs.ExpiryTime, cs.Reset, cs.Email,
  1346. ).Error; err != nil {
  1347. return false, err
  1348. }
  1349. continue
  1350. }
  1351. if err := tx.Exec(
  1352. fmt.Sprintf(
  1353. `UPDATE client_traffics
  1354. SET up = ?, down = ?, enable = ?, total = ?, expiry_time = ?, reset = ?,
  1355. last_online = %s
  1356. WHERE email = ?`,
  1357. database.GreatestExpr("last_online", "?"),
  1358. ),
  1359. cs.Up, cs.Down, cs.Enable, cs.Total, cs.ExpiryTime, cs.Reset,
  1360. cs.LastOnline, cs.Email,
  1361. ).Error; err != nil {
  1362. return false, err
  1363. }
  1364. }
  1365. for k, existing := range centralCS {
  1366. if k.inboundID != c.Id {
  1367. continue
  1368. }
  1369. if _, kept := snapEmails[k.email]; kept {
  1370. continue
  1371. }
  1372. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  1373. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1374. return false, err
  1375. }
  1376. structuralChange = true
  1377. }
  1378. }
  1379. type oldSet struct {
  1380. inboundID int
  1381. emails map[string]struct{}
  1382. }
  1383. var perInboundOld []oldSet
  1384. for _, snapIb := range snap.Inbounds {
  1385. if snapIb == nil {
  1386. continue
  1387. }
  1388. c, ok := tagToCentral[snapIb.Tag]
  1389. if !ok {
  1390. continue
  1391. }
  1392. var oldEmailsRows []string
  1393. if err := tx.Table("clients").
  1394. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1395. Where("client_inbounds.inbound_id = ?", c.Id).
  1396. Pluck("email", &oldEmailsRows).Error; err == nil {
  1397. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  1398. for _, e := range oldEmailsRows {
  1399. if e != "" {
  1400. oldEmails[e] = struct{}{}
  1401. }
  1402. }
  1403. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  1404. }
  1405. clients, gcErr := s.GetClients(snapIb)
  1406. if gcErr != nil {
  1407. logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
  1408. continue
  1409. }
  1410. csEnableByEmail := make(map[string]bool, len(snapIb.ClientStats))
  1411. for _, cs := range snapIb.ClientStats {
  1412. csEnableByEmail[cs.Email] = cs.Enable
  1413. }
  1414. filtered := clients[:0]
  1415. for i := range clients {
  1416. if isClientEmailTombstoned(clients[i].Email) {
  1417. continue
  1418. }
  1419. if cse, hit := csEnableByEmail[clients[i].Email]; hit && !cse {
  1420. clients[i].Enable = false
  1421. }
  1422. filtered = append(filtered, clients[i])
  1423. }
  1424. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  1425. logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
  1426. }
  1427. }
  1428. for _, old := range perInboundOld {
  1429. var stillAttached []string
  1430. if err := tx.Table("clients").
  1431. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1432. Where("client_inbounds.inbound_id = ?", old.inboundID).
  1433. Pluck("email", &stillAttached).Error; err != nil {
  1434. continue
  1435. }
  1436. stillSet := make(map[string]struct{}, len(stillAttached))
  1437. for _, e := range stillAttached {
  1438. stillSet[e] = struct{}{}
  1439. }
  1440. for email := range old.emails {
  1441. if _, kept := stillSet[email]; kept {
  1442. continue
  1443. }
  1444. var attachmentCount int64
  1445. if err := tx.Table("client_inbounds").
  1446. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1447. Where("clients.email = ?", email).
  1448. Count(&attachmentCount).Error; err != nil {
  1449. continue
  1450. }
  1451. if attachmentCount > 0 {
  1452. continue
  1453. }
  1454. if err := tx.Where("email = ?", email).Delete(&model.ClientRecord{}).Error; err != nil {
  1455. logger.Warningf("setRemoteTraffic: delete ClientRecord %q failed: %v", email, err)
  1456. }
  1457. if err := tx.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  1458. logger.Warningf("setRemoteTraffic: delete ClientTraffic %q failed: %v", email, err)
  1459. }
  1460. structuralChange = true
  1461. }
  1462. }
  1463. if err := tx.Commit().Error; err != nil {
  1464. return false, err
  1465. }
  1466. committed = true
  1467. if p != nil {
  1468. p.SetNodeOnlineClients(nodeID, snap.OnlineEmails)
  1469. }
  1470. return structuralChange, nil
  1471. }
  1472. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (needRestart bool, clientsDisabled bool, err error) {
  1473. err = submitTrafficWrite(func() error {
  1474. var inner error
  1475. needRestart, clientsDisabled, inner = s.addTrafficLocked(inboundTraffics, clientTraffics)
  1476. return inner
  1477. })
  1478. return
  1479. }
  1480. func (s *InboundService) addTrafficLocked(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (bool, bool, error) {
  1481. var err error
  1482. db := database.GetDB()
  1483. tx := db.Begin()
  1484. defer func() {
  1485. if err != nil {
  1486. tx.Rollback()
  1487. } else {
  1488. tx.Commit()
  1489. }
  1490. }()
  1491. err = s.addInboundTraffic(tx, inboundTraffics)
  1492. if err != nil {
  1493. return false, false, err
  1494. }
  1495. err = s.addClientTraffic(tx, clientTraffics)
  1496. if err != nil {
  1497. return false, false, err
  1498. }
  1499. needRestart0, count, err := s.autoRenewClients(tx)
  1500. if err != nil {
  1501. logger.Warning("Error in renew clients:", err)
  1502. } else if count > 0 {
  1503. logger.Debugf("%v clients renewed", count)
  1504. }
  1505. disabledClientsCount := int64(0)
  1506. needRestart1, count, err := s.disableInvalidClients(tx)
  1507. if err != nil {
  1508. logger.Warning("Error in disabling invalid clients:", err)
  1509. } else if count > 0 {
  1510. logger.Debugf("%v clients disabled", count)
  1511. disabledClientsCount = count
  1512. }
  1513. needRestart2, count, err := s.disableInvalidInbounds(tx)
  1514. if err != nil {
  1515. logger.Warning("Error in disabling invalid inbounds:", err)
  1516. } else if count > 0 {
  1517. logger.Debugf("%v inbounds disabled", count)
  1518. }
  1519. return needRestart0 || needRestart1 || needRestart2, disabledClientsCount > 0, nil
  1520. }
  1521. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  1522. if len(traffics) == 0 {
  1523. return nil
  1524. }
  1525. var err error
  1526. for _, traffic := range traffics {
  1527. if traffic.IsInbound {
  1528. err = tx.Model(&model.Inbound{}).Where("tag = ? AND node_id IS NULL", traffic.Tag).
  1529. Updates(map[string]any{
  1530. "up": gorm.Expr("up + ?", traffic.Up),
  1531. "down": gorm.Expr("down + ?", traffic.Down),
  1532. }).Error
  1533. if err != nil {
  1534. return err
  1535. }
  1536. }
  1537. }
  1538. return nil
  1539. }
  1540. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  1541. if len(traffics) == 0 {
  1542. return nil
  1543. }
  1544. emails := make([]string, 0, len(traffics))
  1545. for _, traffic := range traffics {
  1546. emails = append(emails, traffic.Email)
  1547. }
  1548. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  1549. err = tx.Model(xray.ClientTraffic{}).
  1550. Where("email IN (?) AND inbound_id IN (?)", emails,
  1551. tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NULL")).
  1552. Find(&dbClientTraffics).Error
  1553. if err != nil {
  1554. return err
  1555. }
  1556. // Avoid empty slice error
  1557. if len(dbClientTraffics) == 0 {
  1558. return nil
  1559. }
  1560. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  1561. if err != nil {
  1562. return err
  1563. }
  1564. // Index by email for O(N) merge — the previous nested loop was O(N²)
  1565. // and dominated each cron tick on inbounds with thousands of active
  1566. // clients (7500 × 7500 = 56M string comparisons every 10 seconds).
  1567. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  1568. for i := range traffics {
  1569. if traffics[i] != nil {
  1570. trafficByEmail[traffics[i].Email] = traffics[i]
  1571. }
  1572. }
  1573. now := time.Now().UnixMilli()
  1574. for dbTraffic_index := range dbClientTraffics {
  1575. t, ok := trafficByEmail[dbClientTraffics[dbTraffic_index].Email]
  1576. if !ok {
  1577. continue
  1578. }
  1579. dbClientTraffics[dbTraffic_index].Up += t.Up
  1580. dbClientTraffics[dbTraffic_index].Down += t.Down
  1581. if t.Up+t.Down > 0 {
  1582. dbClientTraffics[dbTraffic_index].LastOnline = now
  1583. }
  1584. }
  1585. err = tx.Save(dbClientTraffics).Error
  1586. if err != nil {
  1587. logger.Warning("AddClientTraffic update data ", err)
  1588. }
  1589. return nil
  1590. }
  1591. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  1592. inboundIds := make([]int, 0, len(dbClientTraffics))
  1593. for _, dbClientTraffic := range dbClientTraffics {
  1594. if dbClientTraffic.ExpiryTime < 0 {
  1595. inboundIds = append(inboundIds, dbClientTraffic.InboundId)
  1596. }
  1597. }
  1598. if len(inboundIds) > 0 {
  1599. var inbounds []*model.Inbound
  1600. err := tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  1601. if err != nil {
  1602. return nil, err
  1603. }
  1604. for inbound_index := range inbounds {
  1605. settings := map[string]any{}
  1606. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1607. clients, ok := settings["clients"].([]any)
  1608. if ok {
  1609. var newClients []any
  1610. for client_index := range clients {
  1611. c := clients[client_index].(map[string]any)
  1612. for traffic_index := range dbClientTraffics {
  1613. if dbClientTraffics[traffic_index].ExpiryTime < 0 && c["email"] == dbClientTraffics[traffic_index].Email {
  1614. oldExpiryTime := c["expiryTime"].(float64)
  1615. newExpiryTime := (time.Now().Unix() * 1000) - int64(oldExpiryTime)
  1616. c["expiryTime"] = newExpiryTime
  1617. c["updated_at"] = time.Now().Unix() * 1000
  1618. dbClientTraffics[traffic_index].ExpiryTime = newExpiryTime
  1619. break
  1620. }
  1621. }
  1622. if _, ok := c["created_at"]; !ok {
  1623. c["created_at"] = time.Now().Unix() * 1000
  1624. }
  1625. if _, ok := c["updated_at"]; !ok {
  1626. c["updated_at"] = time.Now().Unix() * 1000
  1627. }
  1628. newClients = append(newClients, any(c))
  1629. }
  1630. settings["clients"] = newClients
  1631. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1632. if err != nil {
  1633. return nil, err
  1634. }
  1635. inbounds[inbound_index].Settings = string(modifiedSettings)
  1636. }
  1637. }
  1638. err = tx.Save(inbounds).Error
  1639. if err != nil {
  1640. logger.Warning("AddClientTraffic update inbounds ", err)
  1641. logger.Error(inbounds)
  1642. } else {
  1643. for _, ib := range inbounds {
  1644. if ib == nil {
  1645. continue
  1646. }
  1647. cs, gcErr := s.GetClients(ib)
  1648. if gcErr != nil {
  1649. logger.Warning("AddClientTraffic sync clients: GetClients failed", gcErr)
  1650. continue
  1651. }
  1652. if syncErr := s.clientService.SyncInbound(tx, ib.Id, cs); syncErr != nil {
  1653. logger.Warning("AddClientTraffic sync clients: SyncInbound failed", syncErr)
  1654. }
  1655. }
  1656. }
  1657. }
  1658. return dbClientTraffics, nil
  1659. }
  1660. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  1661. // check for time expired
  1662. var traffics []*xray.ClientTraffic
  1663. now := time.Now().Unix() * 1000
  1664. var err, err1 error
  1665. err = tx.Model(xray.ClientTraffic{}).
  1666. Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).
  1667. Where("inbound_id IN (?)", tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NULL")).
  1668. Find(&traffics).Error
  1669. if err != nil {
  1670. return false, 0, err
  1671. }
  1672. // return if there is no client to renew
  1673. if len(traffics) == 0 {
  1674. return false, 0, nil
  1675. }
  1676. var inbound_ids []int
  1677. var inbounds []*model.Inbound
  1678. needRestart := false
  1679. var clientsToAdd []struct {
  1680. protocol string
  1681. tag string
  1682. client map[string]any
  1683. }
  1684. for _, traffic := range traffics {
  1685. inbound_ids = append(inbound_ids, traffic.InboundId)
  1686. }
  1687. // Dedupe so an inbound hosting N expired clients is fetched and saved once
  1688. // per tick instead of N times across chunk boundaries.
  1689. inbound_ids = uniqueInts(inbound_ids)
  1690. // Chunked to stay under SQLite's bind-variable limit when many inbounds
  1691. // are touched in a single tick.
  1692. for _, batch := range chunkInts(inbound_ids, sqliteMaxVars) {
  1693. var page []*model.Inbound
  1694. if err = tx.Model(model.Inbound{}).Where("id IN ?", batch).Find(&page).Error; err != nil {
  1695. return false, 0, err
  1696. }
  1697. inbounds = append(inbounds, page...)
  1698. }
  1699. for inbound_index := range inbounds {
  1700. settings := map[string]any{}
  1701. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1702. clients := settings["clients"].([]any)
  1703. for client_index := range clients {
  1704. c := clients[client_index].(map[string]any)
  1705. for traffic_index, traffic := range traffics {
  1706. if traffic.Email == c["email"].(string) {
  1707. newExpiryTime := traffic.ExpiryTime
  1708. for newExpiryTime < now {
  1709. newExpiryTime += (int64(traffic.Reset) * 86400000)
  1710. }
  1711. c["expiryTime"] = newExpiryTime
  1712. traffics[traffic_index].ExpiryTime = newExpiryTime
  1713. traffics[traffic_index].Down = 0
  1714. traffics[traffic_index].Up = 0
  1715. if !traffic.Enable {
  1716. traffics[traffic_index].Enable = true
  1717. c["enable"] = true
  1718. clientsToAdd = append(clientsToAdd,
  1719. struct {
  1720. protocol string
  1721. tag string
  1722. client map[string]any
  1723. }{
  1724. protocol: string(inbounds[inbound_index].Protocol),
  1725. tag: inbounds[inbound_index].Tag,
  1726. client: c,
  1727. })
  1728. }
  1729. clients[client_index] = any(c)
  1730. break
  1731. }
  1732. }
  1733. }
  1734. settings["clients"] = clients
  1735. newSettings, err := json.MarshalIndent(settings, "", " ")
  1736. if err != nil {
  1737. return false, 0, err
  1738. }
  1739. inbounds[inbound_index].Settings = string(newSettings)
  1740. }
  1741. err = tx.Save(inbounds).Error
  1742. if err != nil {
  1743. return false, 0, err
  1744. }
  1745. for _, ib := range inbounds {
  1746. if ib == nil {
  1747. continue
  1748. }
  1749. cs, gcErr := s.GetClients(ib)
  1750. if gcErr != nil {
  1751. logger.Warning("autoRenewClients sync clients: GetClients failed", gcErr)
  1752. continue
  1753. }
  1754. if syncErr := s.clientService.SyncInbound(tx, ib.Id, cs); syncErr != nil {
  1755. logger.Warning("autoRenewClients sync clients: SyncInbound failed", syncErr)
  1756. }
  1757. }
  1758. err = tx.Save(traffics).Error
  1759. if err != nil {
  1760. return false, 0, err
  1761. }
  1762. if p != nil {
  1763. err1 = s.xrayApi.Init(p.GetAPIPort())
  1764. if err1 != nil {
  1765. return true, int64(len(traffics)), nil
  1766. }
  1767. for _, clientToAdd := range clientsToAdd {
  1768. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  1769. if err1 != nil {
  1770. needRestart = true
  1771. }
  1772. }
  1773. s.xrayApi.Close()
  1774. }
  1775. return needRestart, int64(len(traffics)), nil
  1776. }
  1777. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  1778. now := time.Now().Unix() * 1000
  1779. needRestart := false
  1780. if p != nil {
  1781. var tags []string
  1782. err := tx.Table("inbounds").
  1783. Select("inbounds.tag").
  1784. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ? and node_id IS NULL", now, true).
  1785. Scan(&tags).Error
  1786. if err != nil {
  1787. return false, 0, err
  1788. }
  1789. s.xrayApi.Init(p.GetAPIPort())
  1790. for _, tag := range tags {
  1791. err1 := s.xrayApi.DelInbound(tag)
  1792. if err1 == nil {
  1793. logger.Debug("Inbound disabled by api:", tag)
  1794. } else {
  1795. logger.Debug("Error in disabling inbound by api:", err1)
  1796. needRestart = true
  1797. }
  1798. }
  1799. s.xrayApi.Close()
  1800. }
  1801. result := tx.Model(model.Inbound{}).
  1802. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ? and node_id IS NULL", now, true).
  1803. Update("enable", false)
  1804. err := result.Error
  1805. count := result.RowsAffected
  1806. return needRestart, count, err
  1807. }
  1808. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error) {
  1809. now := time.Now().Unix() * 1000
  1810. needRestart := false
  1811. var depletedRows []xray.ClientTraffic
  1812. err := tx.Model(xray.ClientTraffic{}).
  1813. Where("((total > 0 AND up + down >= total) OR (expiry_time > 0 AND expiry_time <= ?)) AND enable = ?", now, true).
  1814. Find(&depletedRows).Error
  1815. if err != nil {
  1816. return false, 0, err
  1817. }
  1818. if len(depletedRows) == 0 {
  1819. return false, 0, nil
  1820. }
  1821. depletedEmails := make([]string, 0, len(depletedRows))
  1822. for i := range depletedRows {
  1823. if depletedRows[i].Email == "" {
  1824. continue
  1825. }
  1826. depletedEmails = append(depletedEmails, depletedRows[i].Email)
  1827. }
  1828. type target struct {
  1829. InboundID int `gorm:"column:inbound_id"`
  1830. NodeID *int `gorm:"column:node_id"`
  1831. Tag string
  1832. Email string
  1833. }
  1834. var targets []target
  1835. if len(depletedEmails) > 0 {
  1836. err = tx.Raw(`
  1837. SELECT inbounds.id AS inbound_id, inbounds.node_id AS node_id,
  1838. inbounds.tag AS tag, clients.email AS email
  1839. FROM clients
  1840. JOIN client_inbounds ON client_inbounds.client_id = clients.id
  1841. JOIN inbounds ON inbounds.id = client_inbounds.inbound_id
  1842. WHERE clients.email IN ?
  1843. `, depletedEmails).Scan(&targets).Error
  1844. if err != nil {
  1845. return false, 0, err
  1846. }
  1847. }
  1848. var localTargets []target
  1849. localByInbound := make(map[int]map[string]struct{})
  1850. remoteByInbound := make(map[int][]target)
  1851. for _, t := range targets {
  1852. if t.NodeID == nil {
  1853. localTargets = append(localTargets, t)
  1854. if localByInbound[t.InboundID] == nil {
  1855. localByInbound[t.InboundID] = make(map[string]struct{})
  1856. }
  1857. localByInbound[t.InboundID][t.Email] = struct{}{}
  1858. } else {
  1859. remoteByInbound[t.InboundID] = append(remoteByInbound[t.InboundID], t)
  1860. }
  1861. }
  1862. if p != nil && len(localTargets) > 0 {
  1863. s.xrayApi.Init(p.GetAPIPort())
  1864. for _, t := range localTargets {
  1865. err1 := s.xrayApi.RemoveUser(t.Tag, t.Email)
  1866. if err1 == nil {
  1867. logger.Debug("Client disabled by api:", t.Email)
  1868. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.Email)) {
  1869. logger.Debug("User is already disabled. Nothing to do more...")
  1870. } else {
  1871. logger.Debug("Error in disabling client by api:", err1)
  1872. needRestart = true
  1873. }
  1874. }
  1875. s.xrayApi.Close()
  1876. }
  1877. for inboundID, emails := range localByInbound {
  1878. if _, _, mErr := s.markClientsDisabledInSettings(tx, inboundID, emails); mErr != nil {
  1879. logger.Warning("disableInvalidClients: settings.JSON sync failed for inbound", inboundID, ":", mErr)
  1880. }
  1881. }
  1882. result := tx.Model(xray.ClientTraffic{}).
  1883. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1884. Update("enable", false)
  1885. err = result.Error
  1886. count := result.RowsAffected
  1887. if err != nil {
  1888. return needRestart, count, err
  1889. }
  1890. if len(depletedEmails) > 0 {
  1891. if err := tx.Model(&model.ClientRecord{}).
  1892. Where("email IN ?", depletedEmails).
  1893. Updates(map[string]any{"enable": false, "updated_at": now}).Error; err != nil {
  1894. logger.Warning("disableInvalidClients update clients.enable:", err)
  1895. }
  1896. }
  1897. for inboundID, group := range remoteByInbound {
  1898. emails := make(map[string]struct{}, len(group))
  1899. for _, t := range group {
  1900. emails[t.Email] = struct{}{}
  1901. }
  1902. if pushErr := s.disableRemoteClients(tx, inboundID, emails); pushErr != nil {
  1903. logger.Warning("disableInvalidClients: push to remote failed for inbound", inboundID, ":", pushErr)
  1904. needRestart = true
  1905. }
  1906. }
  1907. return needRestart, count, nil
  1908. }
  1909. // markClientsDisabledInSettings flips client.enable=false in the inbound's
  1910. // stored settings JSON for the given emails and returns both the pre and
  1911. // post snapshots so a caller pushing to a remote node has the diff to hand.
  1912. func (s *InboundService) markClientsDisabledInSettings(tx *gorm.DB, inboundID int, emails map[string]struct{}) (oldIb, newIb *model.Inbound, err error) {
  1913. var ib model.Inbound
  1914. if err := tx.Model(&model.Inbound{}).Where("id = ?", inboundID).First(&ib).Error; err != nil {
  1915. return nil, nil, err
  1916. }
  1917. snapshot := ib
  1918. settings := map[string]any{}
  1919. if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
  1920. return nil, nil, err
  1921. }
  1922. clients, _ := settings["clients"].([]any)
  1923. now := time.Now().Unix() * 1000
  1924. mutated := false
  1925. for i := range clients {
  1926. entry, ok := clients[i].(map[string]any)
  1927. if !ok {
  1928. continue
  1929. }
  1930. email, _ := entry["email"].(string)
  1931. if _, hit := emails[email]; !hit {
  1932. continue
  1933. }
  1934. if cur, _ := entry["enable"].(bool); cur == false {
  1935. continue
  1936. }
  1937. entry["enable"] = false
  1938. entry["updated_at"] = now
  1939. clients[i] = entry
  1940. mutated = true
  1941. }
  1942. if !mutated {
  1943. return &snapshot, &ib, nil
  1944. }
  1945. settings["clients"] = clients
  1946. bs, marshalErr := json.MarshalIndent(settings, "", " ")
  1947. if marshalErr != nil {
  1948. return nil, nil, marshalErr
  1949. }
  1950. ib.Settings = string(bs)
  1951. if err := tx.Model(&model.Inbound{}).Where("id = ?", inboundID).
  1952. Update("settings", ib.Settings).Error; err != nil {
  1953. return nil, nil, err
  1954. }
  1955. return &snapshot, &ib, nil
  1956. }
  1957. func (s *InboundService) disableRemoteClients(tx *gorm.DB, inboundID int, emails map[string]struct{}) error {
  1958. oldSnapshot, ib, err := s.markClientsDisabledInSettings(tx, inboundID, emails)
  1959. if err != nil {
  1960. return err
  1961. }
  1962. rt, err := s.runtimeFor(ib)
  1963. if err != nil {
  1964. return err
  1965. }
  1966. if err := rt.UpdateInbound(context.Background(), oldSnapshot, ib); err != nil {
  1967. return err
  1968. }
  1969. return nil
  1970. }
  1971. func (s *InboundService) GetInboundTags() (string, error) {
  1972. db := database.GetDB()
  1973. var inboundTags []string
  1974. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1975. if err != nil && err != gorm.ErrRecordNotFound {
  1976. return "", err
  1977. }
  1978. tags, _ := json.Marshal(inboundTags)
  1979. return string(tags), nil
  1980. }
  1981. func (s *InboundService) GetClientReverseTags() (string, error) {
  1982. db := database.GetDB()
  1983. var inbounds []model.Inbound
  1984. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  1985. if err != nil && err != gorm.ErrRecordNotFound {
  1986. return "[]", err
  1987. }
  1988. tagSet := make(map[string]struct{})
  1989. for _, inbound := range inbounds {
  1990. var settings map[string]any
  1991. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1992. continue
  1993. }
  1994. clients, ok := settings["clients"].([]any)
  1995. if !ok {
  1996. continue
  1997. }
  1998. for _, client := range clients {
  1999. clientMap, ok := client.(map[string]any)
  2000. if !ok {
  2001. continue
  2002. }
  2003. reverse, ok := clientMap["reverse"].(map[string]any)
  2004. if !ok {
  2005. continue
  2006. }
  2007. tag, _ := reverse["tag"].(string)
  2008. tag = strings.TrimSpace(tag)
  2009. if tag != "" {
  2010. tagSet[tag] = struct{}{}
  2011. }
  2012. }
  2013. }
  2014. rawTags := make([]string, 0, len(tagSet))
  2015. for tag := range tagSet {
  2016. rawTags = append(rawTags, tag)
  2017. }
  2018. sort.Strings(rawTags)
  2019. result, _ := json.Marshal(rawTags)
  2020. return string(result), nil
  2021. }
  2022. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  2023. db := database.GetDB()
  2024. query := fmt.Sprintf(
  2025. "DELETE FROM client_traffics WHERE email NOT IN (SELECT %s %s)",
  2026. database.JSONFieldText("client.value", "email"),
  2027. database.JSONClientsFromInbound(),
  2028. )
  2029. db.Exec(query)
  2030. }
  2031. // AddClientStat inserts a per-client accounting row, no-op on email
  2032. // conflict. Xray reports traffic per email, so the surviving row acts as
  2033. // the shared accumulator for inbounds that re-use the same identity.
  2034. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  2035. clientTraffic := xray.ClientTraffic{
  2036. InboundId: inboundId,
  2037. Email: client.Email,
  2038. Total: client.TotalGB,
  2039. ExpiryTime: client.ExpiryTime,
  2040. Enable: client.Enable,
  2041. Reset: client.Reset,
  2042. }
  2043. return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  2044. Create(&clientTraffic).Error
  2045. }
  2046. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  2047. result := tx.Model(xray.ClientTraffic{}).
  2048. Where("email = ?", email).
  2049. Updates(map[string]any{
  2050. "enable": client.Enable,
  2051. "email": client.Email,
  2052. "total": client.TotalGB,
  2053. "expiry_time": client.ExpiryTime,
  2054. "reset": client.Reset,
  2055. })
  2056. err := result.Error
  2057. return err
  2058. }
  2059. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  2060. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  2061. }
  2062. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  2063. return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error
  2064. }
  2065. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  2066. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  2067. }
  2068. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  2069. db := database.GetDB()
  2070. var traffics []*xray.ClientTraffic
  2071. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  2072. if err != nil {
  2073. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  2074. return nil, nil, err
  2075. }
  2076. if len(traffics) > 0 {
  2077. inbound, err = s.GetInbound(traffics[0].InboundId)
  2078. return traffics[0], inbound, err
  2079. }
  2080. return nil, nil, nil
  2081. }
  2082. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  2083. db := database.GetDB()
  2084. var traffics []*xray.ClientTraffic
  2085. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  2086. if err != nil {
  2087. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  2088. return nil, nil, err
  2089. }
  2090. if len(traffics) > 0 {
  2091. inbound, err = s.GetInbound(traffics[0].InboundId)
  2092. return traffics[0], inbound, err
  2093. }
  2094. return nil, nil, nil
  2095. }
  2096. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  2097. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2098. if err != nil {
  2099. return nil, nil, err
  2100. }
  2101. if inbound == nil {
  2102. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  2103. }
  2104. clients, err := s.GetClients(inbound)
  2105. if err != nil {
  2106. return nil, nil, err
  2107. }
  2108. for _, client := range clients {
  2109. if client.Email == clientEmail {
  2110. return traffic, &client, nil
  2111. }
  2112. }
  2113. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  2114. }
  2115. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  2116. return submitTrafficWrite(func() error {
  2117. db := database.GetDB()
  2118. return db.Model(xray.ClientTraffic{}).
  2119. Where("email = ?", clientEmail).
  2120. Updates(map[string]any{"enable": true, "up": 0, "down": 0}).Error
  2121. })
  2122. }
  2123. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (needRestart bool, err error) {
  2124. err = submitTrafficWrite(func() error {
  2125. var inner error
  2126. needRestart, inner = s.resetClientTrafficLocked(id, clientEmail)
  2127. return inner
  2128. })
  2129. return
  2130. }
  2131. func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (bool, error) {
  2132. needRestart := false
  2133. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  2134. if err != nil {
  2135. return false, err
  2136. }
  2137. if !traffic.Enable {
  2138. inbound, err := s.GetInbound(id)
  2139. if err != nil {
  2140. return false, err
  2141. }
  2142. clients, err := s.GetClients(inbound)
  2143. if err != nil {
  2144. return false, err
  2145. }
  2146. for _, client := range clients {
  2147. if client.Email == clientEmail && client.Enable {
  2148. rt, rterr := s.runtimeFor(inbound)
  2149. if rterr != nil {
  2150. if inbound.NodeID != nil {
  2151. return false, rterr
  2152. }
  2153. needRestart = true
  2154. break
  2155. }
  2156. cipher := ""
  2157. if string(inbound.Protocol) == "shadowsocks" {
  2158. var oldSettings map[string]any
  2159. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  2160. if err != nil {
  2161. return false, err
  2162. }
  2163. cipher = oldSettings["method"].(string)
  2164. }
  2165. err1 := rt.AddUser(context.Background(), inbound, map[string]any{
  2166. "email": client.Email,
  2167. "id": client.ID,
  2168. "auth": client.Auth,
  2169. "security": client.Security,
  2170. "flow": client.Flow,
  2171. "password": client.Password,
  2172. "cipher": cipher,
  2173. })
  2174. if err1 == nil {
  2175. logger.Debug("Client enabled on", rt.Name(), "due to reset traffic:", clientEmail)
  2176. } else {
  2177. logger.Debug("Error in enabling client on", rt.Name(), ":", err1)
  2178. needRestart = true
  2179. }
  2180. break
  2181. }
  2182. }
  2183. }
  2184. traffic.Up = 0
  2185. traffic.Down = 0
  2186. traffic.Enable = true
  2187. db := database.GetDB()
  2188. err = db.Save(traffic).Error
  2189. if err != nil {
  2190. return false, err
  2191. }
  2192. now := time.Now().UnixMilli()
  2193. _ = db.Model(model.Inbound{}).
  2194. Where("id = ?", id).
  2195. Update("last_traffic_reset_time", now).Error
  2196. inbound, err := s.GetInbound(id)
  2197. if err == nil && inbound != nil && inbound.NodeID != nil {
  2198. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  2199. if e := rt.ResetClientTraffic(context.Background(), inbound, clientEmail); e != nil {
  2200. logger.Warning("ResetClientTraffic: remote propagation to", rt.Name(), "failed:", e)
  2201. }
  2202. } else {
  2203. logger.Warning("ResetClientTraffic: runtime lookup failed:", rterr)
  2204. }
  2205. }
  2206. return needRestart, nil
  2207. }
  2208. func (s *InboundService) ResetAllTraffics() error {
  2209. return submitTrafficWrite(func() error {
  2210. return s.resetAllTrafficsLocked()
  2211. })
  2212. }
  2213. func (s *InboundService) resetAllTrafficsLocked() error {
  2214. db := database.GetDB()
  2215. now := time.Now().UnixMilli()
  2216. if err := db.Model(model.Inbound{}).
  2217. Where("user_id > ?", 0).
  2218. Updates(map[string]any{
  2219. "up": 0,
  2220. "down": 0,
  2221. "last_traffic_reset_time": now,
  2222. }).Error; err != nil {
  2223. return err
  2224. }
  2225. return nil
  2226. }
  2227. func (s *InboundService) ResetInboundTraffic(id int) error {
  2228. return submitTrafficWrite(func() error {
  2229. db := database.GetDB()
  2230. return db.Model(model.Inbound{}).
  2231. Where("id = ?", id).
  2232. Updates(map[string]any{"up": 0, "down": 0}).Error
  2233. })
  2234. }
  2235. // EmailsByInbound returns the list of client emails currently configured on
  2236. // an inbound's settings.clients[]. Used by the "delete all clients" flow on
  2237. // the inbounds page, which then feeds the list into ClientService.BulkDelete.
  2238. func (s *InboundService) EmailsByInbound(inboundId int) ([]string, error) {
  2239. inbound, err := s.GetInbound(inboundId)
  2240. if err != nil {
  2241. return nil, err
  2242. }
  2243. clients, err := s.GetClients(inbound)
  2244. if err != nil {
  2245. return nil, err
  2246. }
  2247. emails := make([]string, 0, len(clients))
  2248. for _, c := range clients {
  2249. if e := strings.TrimSpace(c.Email); e != "" {
  2250. emails = append(emails, e)
  2251. }
  2252. }
  2253. return emails, nil
  2254. }
  2255. func (s *InboundService) DelDepletedClients(id int) (err error) {
  2256. db := database.GetDB()
  2257. tx := db.Begin()
  2258. defer func() {
  2259. if err == nil {
  2260. tx.Commit()
  2261. } else {
  2262. tx.Rollback()
  2263. }
  2264. }()
  2265. // Collect depleted emails globally — a shared-email row owned by one
  2266. // inbound depletes every sibling that lists the email.
  2267. now := time.Now().Unix() * 1000
  2268. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  2269. var depletedRows []xray.ClientTraffic
  2270. err = db.Model(xray.ClientTraffic{}).
  2271. Where(depletedClause, now).
  2272. Find(&depletedRows).Error
  2273. if err != nil {
  2274. return err
  2275. }
  2276. if len(depletedRows) == 0 {
  2277. return nil
  2278. }
  2279. depletedEmails := make(map[string]struct{}, len(depletedRows))
  2280. for _, r := range depletedRows {
  2281. if r.Email == "" {
  2282. continue
  2283. }
  2284. depletedEmails[strings.ToLower(r.Email)] = struct{}{}
  2285. }
  2286. if len(depletedEmails) == 0 {
  2287. return nil
  2288. }
  2289. var inbounds []*model.Inbound
  2290. inboundQuery := db.Model(model.Inbound{})
  2291. if id >= 0 {
  2292. inboundQuery = inboundQuery.Where("id = ?", id)
  2293. }
  2294. if err = inboundQuery.Find(&inbounds).Error; err != nil {
  2295. return err
  2296. }
  2297. for _, inbound := range inbounds {
  2298. var settings map[string]any
  2299. if err = json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2300. return err
  2301. }
  2302. rawClients, ok := settings["clients"].([]any)
  2303. if !ok {
  2304. continue
  2305. }
  2306. newClients := make([]any, 0, len(rawClients))
  2307. removed := 0
  2308. for _, client := range rawClients {
  2309. c, ok := client.(map[string]any)
  2310. if !ok {
  2311. newClients = append(newClients, client)
  2312. continue
  2313. }
  2314. email, _ := c["email"].(string)
  2315. if _, isDepleted := depletedEmails[strings.ToLower(email)]; isDepleted {
  2316. removed++
  2317. continue
  2318. }
  2319. newClients = append(newClients, client)
  2320. }
  2321. if removed == 0 {
  2322. continue
  2323. }
  2324. if len(newClients) == 0 {
  2325. s.DelInbound(inbound.Id)
  2326. continue
  2327. }
  2328. settings["clients"] = newClients
  2329. ns, mErr := json.MarshalIndent(settings, "", " ")
  2330. if mErr != nil {
  2331. return mErr
  2332. }
  2333. inbound.Settings = string(ns)
  2334. if err = tx.Save(inbound).Error; err != nil {
  2335. return err
  2336. }
  2337. survivingClients, gcErr := s.GetClients(inbound)
  2338. if gcErr != nil {
  2339. err = gcErr
  2340. return err
  2341. }
  2342. if err = s.clientService.SyncInbound(tx, inbound.Id, survivingClients); err != nil {
  2343. return err
  2344. }
  2345. }
  2346. // Drop now-orphaned rows. With id >= 0, a row is safe to drop only when
  2347. // no out-of-scope inbound still references the email.
  2348. if id < 0 {
  2349. err = tx.Where(depletedClause, now).Delete(xray.ClientTraffic{}).Error
  2350. return err
  2351. }
  2352. emails := make([]string, 0, len(depletedEmails))
  2353. for e := range depletedEmails {
  2354. emails = append(emails, e)
  2355. }
  2356. var stillReferenced []string
  2357. emailExpr := database.JSONFieldText("client.value", "email")
  2358. stillQuery := fmt.Sprintf(
  2359. "SELECT DISTINCT LOWER(%s) %s WHERE LOWER(%s) IN ?",
  2360. emailExpr,
  2361. database.JSONClientsFromInbound(),
  2362. emailExpr,
  2363. )
  2364. if err = tx.Raw(stillQuery, emails).Scan(&stillReferenced).Error; err != nil {
  2365. return err
  2366. }
  2367. stillSet := make(map[string]struct{}, len(stillReferenced))
  2368. for _, e := range stillReferenced {
  2369. stillSet[e] = struct{}{}
  2370. }
  2371. toDelete := make([]string, 0, len(emails))
  2372. for _, e := range emails {
  2373. if _, kept := stillSet[e]; !kept {
  2374. toDelete = append(toDelete, e)
  2375. }
  2376. }
  2377. if len(toDelete) > 0 {
  2378. if err = tx.Where("LOWER(email) IN ?", toDelete).Delete(xray.ClientTraffic{}).Error; err != nil {
  2379. return err
  2380. }
  2381. }
  2382. return nil
  2383. }
  2384. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  2385. db := database.GetDB()
  2386. var inbounds []*model.Inbound
  2387. // Retrieve inbounds where settings contain the given tgId
  2388. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  2389. if err != nil && err != gorm.ErrRecordNotFound {
  2390. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  2391. return nil, err
  2392. }
  2393. var emails []string
  2394. for _, inbound := range inbounds {
  2395. clients, err := s.GetClients(inbound)
  2396. if err != nil {
  2397. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  2398. continue
  2399. }
  2400. for _, client := range clients {
  2401. if client.TgID == tgId {
  2402. emails = append(emails, client.Email)
  2403. }
  2404. }
  2405. }
  2406. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  2407. // account owns thousands of clients across inbounds.
  2408. uniqEmails := uniqueNonEmptyStrings(emails)
  2409. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  2410. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  2411. var page []*xray.ClientTraffic
  2412. if err = db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  2413. if err == gorm.ErrRecordNotFound {
  2414. continue
  2415. }
  2416. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  2417. return nil, err
  2418. }
  2419. traffics = append(traffics, page...)
  2420. }
  2421. if len(traffics) == 0 {
  2422. logger.Warning("No ClientTraffic records found for emails:", emails)
  2423. return nil, nil
  2424. }
  2425. // Populate UUID and other client data for each traffic record
  2426. for i := range traffics {
  2427. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  2428. traffics[i].Enable = client.Enable
  2429. traffics[i].UUID = client.ID
  2430. traffics[i].SubId = client.SubID
  2431. }
  2432. }
  2433. return traffics, nil
  2434. }
  2435. // sqliteMaxVars is a safe ceiling for the number of bind parameters in a
  2436. // single SQL statement. SQLite's SQLITE_MAX_VARIABLE_NUMBER is 999 on builds
  2437. // before 3.32 and 32766 after; staying under 999 keeps queries portable
  2438. // across forks/old binaries and also bounds per-query memory on truly large
  2439. // installs (>32k clients) where even modern SQLite would refuse a single IN.
  2440. const sqliteMaxVars = 900
  2441. // uniqueNonEmptyStrings returns a deduplicated copy of in with empty strings
  2442. // removed, preserving the order of first occurrence.
  2443. func uniqueNonEmptyStrings(in []string) []string {
  2444. if len(in) == 0 {
  2445. return nil
  2446. }
  2447. seen := make(map[string]struct{}, len(in))
  2448. out := make([]string, 0, len(in))
  2449. for _, v := range in {
  2450. if v == "" {
  2451. continue
  2452. }
  2453. if _, ok := seen[v]; ok {
  2454. continue
  2455. }
  2456. seen[v] = struct{}{}
  2457. out = append(out, v)
  2458. }
  2459. return out
  2460. }
  2461. // uniqueInts returns a deduplicated copy of in, preserving order of first occurrence.
  2462. func uniqueInts(in []int) []int {
  2463. if len(in) == 0 {
  2464. return nil
  2465. }
  2466. seen := make(map[int]struct{}, len(in))
  2467. out := make([]int, 0, len(in))
  2468. for _, v := range in {
  2469. if _, ok := seen[v]; ok {
  2470. continue
  2471. }
  2472. seen[v] = struct{}{}
  2473. out = append(out, v)
  2474. }
  2475. return out
  2476. }
  2477. // chunkStrings splits s into consecutive sub-slices of at most size elements.
  2478. // Returns nil for an empty input or non-positive size.
  2479. func chunkStrings(s []string, size int) [][]string {
  2480. if size <= 0 || len(s) == 0 {
  2481. return nil
  2482. }
  2483. out := make([][]string, 0, (len(s)+size-1)/size)
  2484. for i := 0; i < len(s); i += size {
  2485. end := min(i+size, len(s))
  2486. out = append(out, s[i:end])
  2487. }
  2488. return out
  2489. }
  2490. // chunkInts splits s into consecutive sub-slices of at most size elements.
  2491. // Returns nil for an empty input or non-positive size.
  2492. func chunkInts(s []int, size int) [][]int {
  2493. if size <= 0 || len(s) == 0 {
  2494. return nil
  2495. }
  2496. out := make([][]int, 0, (len(s)+size-1)/size)
  2497. for i := 0; i < len(s); i += size {
  2498. end := min(i+size, len(s))
  2499. out = append(out, s[i:end])
  2500. }
  2501. return out
  2502. }
  2503. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  2504. uniq := uniqueNonEmptyStrings(emails)
  2505. if len(uniq) == 0 {
  2506. return nil, nil
  2507. }
  2508. db := database.GetDB()
  2509. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  2510. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  2511. var page []*xray.ClientTraffic
  2512. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  2513. return nil, err
  2514. }
  2515. traffics = append(traffics, page...)
  2516. }
  2517. return traffics, nil
  2518. }
  2519. // GetAllClientTraffics returns the full set of client_traffics rows so the
  2520. // websocket broadcasters can ship a complete snapshot every cycle. The old
  2521. // delta-only path (GetActiveClientTraffics on activeEmails) silently dropped
  2522. // the per-client section whenever no client moved bytes in the cycle or a
  2523. // node sync failed, leaving client rows in the UI stuck at stale numbers.
  2524. func (s *InboundService) GetAllClientTraffics() ([]*xray.ClientTraffic, error) {
  2525. db := database.GetDB()
  2526. var traffics []*xray.ClientTraffic
  2527. if err := db.Model(xray.ClientTraffic{}).Find(&traffics).Error; err != nil {
  2528. return nil, err
  2529. }
  2530. return traffics, nil
  2531. }
  2532. type InboundTrafficSummary struct {
  2533. Id int `json:"id"`
  2534. Up int64 `json:"up"`
  2535. Down int64 `json:"down"`
  2536. Total int64 `json:"total"`
  2537. Enable bool `json:"enable"`
  2538. }
  2539. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  2540. db := database.GetDB()
  2541. var summaries []InboundTrafficSummary
  2542. if err := db.Model(&model.Inbound{}).
  2543. Select("id, up, down, total, enable").
  2544. Find(&summaries).Error; err != nil {
  2545. return nil, err
  2546. }
  2547. return summaries, nil
  2548. }
  2549. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  2550. // Prefer retrieving along with client to reflect actual enabled state from inbound settings
  2551. t, client, err := s.GetClientByEmail(email)
  2552. if err != nil {
  2553. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  2554. return nil, err
  2555. }
  2556. if t != nil && client != nil {
  2557. t.UUID = client.ID
  2558. t.SubId = client.SubID
  2559. return t, nil
  2560. }
  2561. return nil, nil
  2562. }
  2563. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  2564. return submitTrafficWrite(func() error {
  2565. db := database.GetDB()
  2566. err := db.Model(xray.ClientTraffic{}).
  2567. Where("email = ?", email).
  2568. Updates(map[string]any{
  2569. "up": upload,
  2570. "down": download,
  2571. }).Error
  2572. if err != nil {
  2573. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  2574. }
  2575. return err
  2576. })
  2577. }
  2578. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  2579. db := database.GetDB()
  2580. inbound := &model.Inbound{}
  2581. traffic = &xray.ClientTraffic{}
  2582. // Search for inbound settings that contain the query
  2583. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  2584. if err != nil {
  2585. if err == gorm.ErrRecordNotFound {
  2586. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  2587. return nil, err
  2588. }
  2589. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  2590. return nil, err
  2591. }
  2592. traffic.InboundId = inbound.Id
  2593. // Unmarshal settings to get clients
  2594. settings := map[string][]model.Client{}
  2595. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2596. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  2597. return nil, err
  2598. }
  2599. clients := settings["clients"]
  2600. for _, client := range clients {
  2601. if (client.ID == query || client.Password == query) && client.Email != "" {
  2602. traffic.Email = client.Email
  2603. break
  2604. }
  2605. }
  2606. if traffic.Email == "" {
  2607. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  2608. return nil, gorm.ErrRecordNotFound
  2609. }
  2610. // Retrieve ClientTraffic based on the found email
  2611. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  2612. if err != nil {
  2613. if err == gorm.ErrRecordNotFound {
  2614. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  2615. return nil, err
  2616. }
  2617. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  2618. return nil, err
  2619. }
  2620. return traffic, nil
  2621. }
  2622. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  2623. db := database.GetDB()
  2624. InboundClientIps := &model.InboundClientIps{}
  2625. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  2626. if err != nil {
  2627. return "", err
  2628. }
  2629. if InboundClientIps.Ips == "" {
  2630. return "", nil
  2631. }
  2632. // Try to parse as new format (with timestamps)
  2633. type IPWithTimestamp struct {
  2634. IP string `json:"ip"`
  2635. Timestamp int64 `json:"timestamp"`
  2636. }
  2637. var ipsWithTime []IPWithTimestamp
  2638. err = json.Unmarshal([]byte(InboundClientIps.Ips), &ipsWithTime)
  2639. // If successfully parsed as new format, return with timestamps
  2640. if err == nil && len(ipsWithTime) > 0 {
  2641. return InboundClientIps.Ips, nil
  2642. }
  2643. // Otherwise, assume it's old format (simple string array)
  2644. // Try to parse as simple array and convert to new format
  2645. var oldIps []string
  2646. err = json.Unmarshal([]byte(InboundClientIps.Ips), &oldIps)
  2647. if err == nil && len(oldIps) > 0 {
  2648. // Convert old format to new format with current timestamp
  2649. newIpsWithTime := make([]IPWithTimestamp, len(oldIps))
  2650. for i, ip := range oldIps {
  2651. newIpsWithTime[i] = IPWithTimestamp{
  2652. IP: ip,
  2653. Timestamp: time.Now().Unix(),
  2654. }
  2655. }
  2656. result, _ := json.Marshal(newIpsWithTime)
  2657. return string(result), nil
  2658. }
  2659. // Return as-is if parsing fails
  2660. return InboundClientIps.Ips, nil
  2661. }
  2662. func (s *InboundService) ClearClientIps(clientEmail string) error {
  2663. db := database.GetDB()
  2664. result := db.Model(model.InboundClientIps{}).
  2665. Where("client_email = ?", clientEmail).
  2666. Update("ips", "")
  2667. err := result.Error
  2668. if err != nil {
  2669. return err
  2670. }
  2671. return nil
  2672. }
  2673. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  2674. db := database.GetDB()
  2675. var inbounds []*model.Inbound
  2676. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  2677. if err != nil && err != gorm.ErrRecordNotFound {
  2678. return nil, err
  2679. }
  2680. return inbounds, nil
  2681. }
  2682. func (s *InboundService) MigrationRequirements() {
  2683. db := database.GetDB()
  2684. tx := db.Begin()
  2685. var err error
  2686. defer func() {
  2687. if err == nil {
  2688. tx.Commit()
  2689. if !database.IsPostgres() {
  2690. if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
  2691. logger.Warningf("VACUUM failed: %v", dbErr)
  2692. }
  2693. }
  2694. } else {
  2695. tx.Rollback()
  2696. }
  2697. }()
  2698. if tx.Migrator().HasColumn(&model.Inbound{}, "all_time") {
  2699. if err = tx.Migrator().DropColumn(&model.Inbound{}, "all_time"); err != nil {
  2700. return
  2701. }
  2702. }
  2703. if tx.Migrator().HasColumn(&xray.ClientTraffic{}, "all_time") {
  2704. if err = tx.Migrator().DropColumn(&xray.ClientTraffic{}, "all_time"); err != nil {
  2705. return
  2706. }
  2707. }
  2708. // Fix inbounds based problems
  2709. var inbounds []*model.Inbound
  2710. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan", "shadowsocks", "hysteria"}).Find(&inbounds).Error
  2711. if err != nil && err != gorm.ErrRecordNotFound {
  2712. return
  2713. }
  2714. for inbound_index := range inbounds {
  2715. settings := map[string]any{}
  2716. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  2717. if raw, exists := settings["clients"]; exists && raw == nil {
  2718. settings["clients"] = []any{}
  2719. }
  2720. clients, ok := settings["clients"].([]any)
  2721. if ok {
  2722. // Fix Client configuration problems
  2723. newClients := make([]any, 0, len(clients))
  2724. hasVisionFlow := false
  2725. for client_index := range clients {
  2726. c := clients[client_index].(map[string]any)
  2727. // Add email='' if it is not exists
  2728. if _, ok := c["email"]; !ok {
  2729. c["email"] = ""
  2730. }
  2731. // Convert string tgId to int64
  2732. if _, ok := c["tgId"]; ok {
  2733. var tgId any = c["tgId"]
  2734. if tgIdStr, ok2 := tgId.(string); ok2 {
  2735. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  2736. if err == nil {
  2737. c["tgId"] = tgIdInt64
  2738. }
  2739. }
  2740. }
  2741. // Remove "flow": "xtls-rprx-direct"
  2742. if _, ok := c["flow"]; ok {
  2743. if c["flow"] == "xtls-rprx-direct" {
  2744. c["flow"] = ""
  2745. }
  2746. }
  2747. if flow, _ := c["flow"].(string); flow == "xtls-rprx-vision" {
  2748. hasVisionFlow = true
  2749. }
  2750. // Backfill created_at and updated_at
  2751. if _, ok := c["created_at"]; !ok {
  2752. c["created_at"] = time.Now().Unix() * 1000
  2753. }
  2754. c["updated_at"] = time.Now().Unix() * 1000
  2755. newClients = append(newClients, any(c))
  2756. }
  2757. settings["clients"] = newClients
  2758. // Drop orphaned testseed: VLESS-only field, only meaningful when at least
  2759. // one client uses the exact xtls-rprx-vision flow. Older versions saved it
  2760. // for any non-empty flow (including the UDP variant) or kept it after the
  2761. // flow was cleared from the client modal — clean those up here.
  2762. if inbounds[inbound_index].Protocol == model.VLESS && !hasVisionFlow {
  2763. delete(settings, "testseed")
  2764. }
  2765. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2766. if err != nil {
  2767. return
  2768. }
  2769. inbounds[inbound_index].Settings = string(modifiedSettings)
  2770. }
  2771. // Add client traffic row for all clients which has email
  2772. modelClients, err := s.GetClients(inbounds[inbound_index])
  2773. if err != nil {
  2774. return
  2775. }
  2776. for _, modelClient := range modelClients {
  2777. if len(modelClient.Email) > 0 {
  2778. var count int64
  2779. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  2780. if count == 0 {
  2781. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  2782. }
  2783. }
  2784. }
  2785. // Heal clients table for installs where the one-shot seeder
  2786. // skipped clients due to a tgId-string unmarshal error.
  2787. if syncErr := s.clientService.SyncInbound(tx, inbounds[inbound_index].Id, modelClients); syncErr != nil {
  2788. logger.Warning("MigrationRequirements sync clients failed:", syncErr)
  2789. }
  2790. }
  2791. tx.Save(inbounds)
  2792. // Remove orphaned traffics
  2793. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  2794. // Migrate old MultiDomain to External Proxy
  2795. var externalProxy []struct {
  2796. Id int
  2797. Port int
  2798. StreamSettings []byte
  2799. }
  2800. err = tx.Raw(`select id, port, stream_settings
  2801. from inbounds
  2802. WHERE protocol in ('vmess','vless','trojan')
  2803. AND json_extract(stream_settings, '$.security') = 'tls'
  2804. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  2805. if err != nil || len(externalProxy) == 0 {
  2806. return
  2807. }
  2808. for _, ep := range externalProxy {
  2809. var reverses any
  2810. var stream map[string]any
  2811. json.Unmarshal(ep.StreamSettings, &stream)
  2812. if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
  2813. if settings, ok := tlsSettings["settings"].(map[string]any); ok {
  2814. if domains, ok := settings["domains"].([]any); ok {
  2815. for _, domain := range domains {
  2816. if domainMap, ok := domain.(map[string]any); ok {
  2817. domainMap["forceTls"] = "same"
  2818. domainMap["port"] = ep.Port
  2819. domainMap["dest"] = domainMap["domain"].(string)
  2820. delete(domainMap, "domain")
  2821. }
  2822. }
  2823. }
  2824. reverses = settings["domains"]
  2825. delete(settings, "domains")
  2826. }
  2827. }
  2828. stream["externalProxy"] = reverses
  2829. newStream, _ := json.MarshalIndent(stream, " ", " ")
  2830. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  2831. }
  2832. err = tx.Raw(`UPDATE inbounds
  2833. SET tag = REPLACE(tag, '0.0.0.0:', '')
  2834. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  2835. if err != nil {
  2836. return
  2837. }
  2838. }
  2839. func (s *InboundService) MigrateDB() {
  2840. s.MigrationRequirements()
  2841. s.MigrationRemoveOrphanedTraffics()
  2842. }
  2843. func (s *InboundService) GetOnlineClients() []string {
  2844. return p.GetOnlineClients()
  2845. }
  2846. func (s *InboundService) SetNodeOnlineClients(nodeID int, emails []string) {
  2847. if p != nil {
  2848. p.SetNodeOnlineClients(nodeID, emails)
  2849. }
  2850. }
  2851. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  2852. if p != nil {
  2853. p.ClearNodeOnlineClients(nodeID)
  2854. }
  2855. }
  2856. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  2857. db := database.GetDB()
  2858. var rows []xray.ClientTraffic
  2859. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  2860. if err != nil && err != gorm.ErrRecordNotFound {
  2861. return nil, err
  2862. }
  2863. result := make(map[string]int64, len(rows))
  2864. for _, r := range rows {
  2865. result[r.Email] = r.LastOnline
  2866. }
  2867. return result, nil
  2868. }
  2869. func (s *InboundService) RefreshOnlineClientsFromMap(lastOnlineMap map[string]int64) {
  2870. now := time.Now().UnixMilli()
  2871. newOnlineClients := make([]string, 0, len(lastOnlineMap))
  2872. for email, lastOnline := range lastOnlineMap {
  2873. if now-lastOnline < onlineGracePeriodMs {
  2874. newOnlineClients = append(newOnlineClients, email)
  2875. }
  2876. }
  2877. if p != nil {
  2878. p.SetOnlineClients(newOnlineClients)
  2879. }
  2880. }
  2881. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  2882. db := database.GetDB()
  2883. // Step 1: Get ClientTraffic records for emails in the input list.
  2884. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  2885. uniqEmails := uniqueNonEmptyStrings(emails)
  2886. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  2887. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  2888. var page []xray.ClientTraffic
  2889. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && err != gorm.ErrRecordNotFound {
  2890. return nil, nil, err
  2891. }
  2892. clients = append(clients, page...)
  2893. }
  2894. // Step 2: Sort clients by (Up + Down) descending
  2895. sort.Slice(clients, func(i, j int) bool {
  2896. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  2897. })
  2898. // Step 3: Extract sorted valid emails and track found ones
  2899. validEmails := make([]string, 0, len(clients))
  2900. found := make(map[string]bool)
  2901. for _, client := range clients {
  2902. validEmails = append(validEmails, client.Email)
  2903. found[client.Email] = true
  2904. }
  2905. // Step 4: Identify emails that were not found in the database
  2906. extraEmails := make([]string, 0)
  2907. for _, email := range emails {
  2908. if !found[email] {
  2909. extraEmails = append(extraEmails, email)
  2910. }
  2911. }
  2912. return validEmails, extraEmails, nil
  2913. }
  2914. type SubLinkProvider interface {
  2915. SubLinksForSubId(host, subId string) ([]string, error)
  2916. LinksForClient(host string, inbound *model.Inbound, email string) []string
  2917. }
  2918. var registeredSubLinkProvider SubLinkProvider
  2919. func RegisterSubLinkProvider(p SubLinkProvider) {
  2920. registeredSubLinkProvider = p
  2921. }
  2922. func (s *InboundService) GetSubLinks(host, subId string) ([]string, error) {
  2923. if registeredSubLinkProvider == nil {
  2924. return nil, common.NewError("sub link provider not registered")
  2925. }
  2926. return registeredSubLinkProvider.SubLinksForSubId(host, subId)
  2927. }
  2928. func (s *InboundService) GetAllClientLinks(host string, email string) ([]string, error) {
  2929. if email == "" {
  2930. return nil, common.NewError("client email is required")
  2931. }
  2932. if registeredSubLinkProvider == nil {
  2933. return nil, common.NewError("sub link provider not registered")
  2934. }
  2935. rec, err := s.clientService.GetRecordByEmail(nil, email)
  2936. if err != nil {
  2937. return nil, err
  2938. }
  2939. inboundIds, err := s.clientService.GetInboundIdsForRecord(rec.Id)
  2940. if err != nil {
  2941. return nil, err
  2942. }
  2943. var links []string
  2944. for _, ibId := range inboundIds {
  2945. inbound, getErr := s.GetInbound(ibId)
  2946. if getErr != nil {
  2947. return nil, getErr
  2948. }
  2949. links = append(links, registeredSubLinkProvider.LinksForClient(host, inbound, email)...)
  2950. }
  2951. return links, nil
  2952. }