inbound.go 94 KB

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