inbound.go 91 KB

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