inbound.go 86 KB

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