ldap_sync_job.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. package job
  2. import (
  3. "strings"
  4. "sync/atomic"
  5. "time"
  6. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  7. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  8. ldaputil "github.com/mhsanaei/3x-ui/v3/internal/util/ldap"
  9. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  10. )
  11. var DefaultTruthyValues = []string{"true", "1", "yes", "on"}
  12. // Share of the previous successful fetch a new one must still return to be
  13. // trusted: a sudden collapse means a broken directory far more often than churn.
  14. const ldapAutoDeleteMinRetainPercent = 50
  15. type LdapSyncJob struct {
  16. settingService service.SettingService
  17. inboundService service.InboundService
  18. clientService service.ClientService
  19. xrayService service.XrayService
  20. lastFlagCount atomic.Int64
  21. }
  22. // --- Helper functions for mustGet ---
  23. func mustGetString(fn func() (string, error)) string {
  24. v, err := fn()
  25. if err != nil {
  26. panic(err)
  27. }
  28. return v
  29. }
  30. func mustGetInt(fn func() (int, error)) int {
  31. v, err := fn()
  32. if err != nil {
  33. panic(err)
  34. }
  35. return v
  36. }
  37. func mustGetBool(fn func() (bool, error)) bool {
  38. v, err := fn()
  39. if err != nil {
  40. panic(err)
  41. }
  42. return v
  43. }
  44. func mustGetStringOr(fn func() (string, error), fallback string) string {
  45. v, err := fn()
  46. if err != nil || v == "" {
  47. return fallback
  48. }
  49. return v
  50. }
  51. func NewLdapSyncJob() *LdapSyncJob {
  52. return new(LdapSyncJob)
  53. }
  54. func (j *LdapSyncJob) Run() {
  55. logger.Info("LDAP sync job started")
  56. enabled, err := j.settingService.GetLdapEnable()
  57. if err != nil || !enabled {
  58. logger.Warning("LDAP disabled or failed to fetch flag")
  59. return
  60. }
  61. // --- LDAP fetch ---
  62. cfg := ldaputil.Config{
  63. Host: mustGetString(j.settingService.GetLdapHost),
  64. Port: mustGetInt(j.settingService.GetLdapPort),
  65. UseTLS: mustGetBool(j.settingService.GetLdapUseTLS),
  66. InsecureSkipVerify: mustGetBool(j.settingService.GetLdapInsecureSkipVerify),
  67. BindDN: mustGetString(j.settingService.GetLdapBindDN),
  68. Password: mustGetString(j.settingService.GetLdapPassword),
  69. BaseDN: mustGetString(j.settingService.GetLdapBaseDN),
  70. UserFilter: mustGetString(j.settingService.GetLdapUserFilter),
  71. UserAttr: mustGetString(j.settingService.GetLdapUserAttr),
  72. FlagField: mustGetStringOr(j.settingService.GetLdapFlagField, mustGetString(j.settingService.GetLdapVlessField)),
  73. TruthyVals: truthyValuesOrDefault(mustGetString(j.settingService.GetLdapTruthyValues)),
  74. Invert: mustGetBool(j.settingService.GetLdapInvertFlag),
  75. }
  76. flags, err := ldaputil.FetchVlessFlags(cfg)
  77. if err != nil {
  78. logger.Warning("LDAP fetch failed:", err)
  79. return
  80. }
  81. logger.Infof("Fetched %d LDAP flags", len(flags))
  82. // --- Load all inbounds and all clients once ---
  83. inboundTags := splitCsv(mustGetString(j.settingService.GetLdapInboundTags))
  84. inbounds, err := j.inboundService.GetAllInbounds()
  85. if err != nil {
  86. logger.Warning("Failed to get inbounds:", err)
  87. return
  88. }
  89. allClients := map[string]*model.Client{} // email -> client
  90. inboundMap := map[string]*model.Inbound{} // tag -> inbound
  91. for _, ib := range inbounds {
  92. inboundMap[ib.Tag] = ib
  93. clients, _ := j.inboundService.GetClients(ib)
  94. for i := range clients {
  95. allClients[clients[i].Email] = &clients[i]
  96. }
  97. }
  98. // --- Prepare batch operations ---
  99. autoCreate := mustGetBool(j.settingService.GetLdapAutoCreate)
  100. defGB := mustGetInt(j.settingService.GetLdapDefaultTotalGB)
  101. defExpiryDays := mustGetInt(j.settingService.GetLdapDefaultExpiryDays)
  102. defLimitIP := mustGetInt(j.settingService.GetLdapDefaultLimitIP)
  103. resolvedInboundIds := make([]int, 0, len(inboundTags))
  104. resolvedTags := make([]string, 0, len(inboundTags))
  105. for _, tag := range inboundTags {
  106. ib := inboundMap[tag]
  107. if ib == nil {
  108. logger.Warningf("LDAP inbound tag %s does not match any inbound", tag)
  109. continue
  110. }
  111. resolvedInboundIds = append(resolvedInboundIds, ib.Id)
  112. resolvedTags = append(resolvedTags, tag)
  113. }
  114. clientsToCreate := []model.Client{}
  115. var clientsToEnable, clientsToDisable []string
  116. for email, allowed := range flags {
  117. existing := allClients[email]
  118. if existing == nil {
  119. if allowed && autoCreate {
  120. clientsToCreate = append(clientsToCreate, j.buildClient(email, defGB, defExpiryDays, defLimitIP))
  121. }
  122. continue
  123. }
  124. if len(resolvedTags) == 0 {
  125. continue
  126. }
  127. if allowed && !existing.Enable {
  128. clientsToEnable = append(clientsToEnable, email)
  129. } else if !allowed && existing.Enable {
  130. clientsToDisable = append(clientsToDisable, email)
  131. }
  132. }
  133. j.createClients(clientsToCreate, resolvedInboundIds, resolvedTags)
  134. // --- Execute enable/disable batch ---
  135. j.batchSetEnable(clientsToEnable, true)
  136. j.batchSetEnable(clientsToDisable, false)
  137. // --- Auto delete clients not in LDAP ---
  138. autoDelete := mustGetBool(j.settingService.GetLdapAutoDelete)
  139. if autoDelete && j.autoDeleteSafeForFetch(len(flags)) {
  140. ldapEmailSet := map[string]struct{}{}
  141. for e := range flags {
  142. ldapEmailSet[e] = struct{}{}
  143. }
  144. for _, tag := range inboundTags {
  145. j.deleteClientsNotInLDAP(tag, ldapEmailSet)
  146. }
  147. }
  148. j.lastFlagCount.Store(int64(len(flags)))
  149. }
  150. // FetchVlessFlags returns (empty, nil) when the bind succeeds but the search
  151. // yields nothing — a renamed OU, a lost read grant — which is not "all gone".
  152. func (j *LdapSyncJob) autoDeleteSafeForFetch(fetched int) bool {
  153. if fetched == 0 {
  154. logger.Warning("LDAP auto-delete skipped: directory returned no usable users")
  155. return false
  156. }
  157. previous := j.lastFlagCount.Load()
  158. if previous > 0 && int64(fetched)*100 < previous*ldapAutoDeleteMinRetainPercent {
  159. logger.Warningf("LDAP auto-delete skipped: fetched %d users, previous successful sync saw %d (below %d%% retention)",
  160. fetched, previous, ldapAutoDeleteMinRetainPercent)
  161. return false
  162. }
  163. return true
  164. }
  165. func truthyValuesOrDefault(s string) []string {
  166. if vals := splitCsv(s); len(vals) > 0 {
  167. return vals
  168. }
  169. return DefaultTruthyValues
  170. }
  171. func splitCsv(s string) []string {
  172. if s == "" {
  173. return nil
  174. }
  175. parts := strings.Split(s, ",")
  176. out := make([]string, 0, len(parts))
  177. for _, p := range parts {
  178. v := strings.TrimSpace(p)
  179. if v != "" {
  180. out = append(out, v)
  181. }
  182. }
  183. return out
  184. }
  185. // buildClient creates a new client for auto-create; ClientService.Create fills per-protocol credentials
  186. func (j *LdapSyncJob) buildClient(email string, defGB, defExpiryDays, defLimitIP int) model.Client {
  187. c := model.Client{
  188. Email: email,
  189. Enable: true,
  190. LimitIP: defLimitIP,
  191. TotalGB: int64(defGB) * 1024 * 1024 * 1024,
  192. }
  193. if defExpiryDays > 0 {
  194. c.ExpiryTime = time.Now().Add(time.Duration(defExpiryDays) * 24 * time.Hour).UnixMilli()
  195. }
  196. return c
  197. }
  198. // createClients adds each new LDAP client once, attached to every configured inbound
  199. func (j *LdapSyncJob) createClients(newClients []model.Client, inboundIds []int, tags []string) {
  200. if len(newClients) == 0 || len(inboundIds) == 0 {
  201. return
  202. }
  203. tagList := strings.Join(tags, ",")
  204. created := 0
  205. restartNeeded := false
  206. for _, c := range newClients {
  207. nr, err := j.clientService.Create(&j.inboundService, &service.ClientCreatePayload{Client: c, InboundIds: inboundIds})
  208. // Read before the error check: a partly-applied create still committed
  209. // clients on the inbounds that succeeded, and those need the restart.
  210. if nr {
  211. restartNeeded = true
  212. }
  213. if err != nil {
  214. logger.Warningf("Failed to add client %s for tags %s: %v", c.Email, tagList, err)
  215. continue
  216. }
  217. created++
  218. }
  219. if restartNeeded {
  220. j.xrayService.SetToNeedRestart()
  221. }
  222. if created == 0 {
  223. return
  224. }
  225. logger.Infof("LDAP auto-create: %d clients for %s", created, tagList)
  226. }
  227. // batchSetEnable takes the bulk path: per-user calls held each inbound's lock through
  228. // its node push, so users sharing a hung node inbound queued one push timeout apiece.
  229. func (j *LdapSyncJob) batchSetEnable(emails []string, enable bool) {
  230. if len(emails) == 0 {
  231. return
  232. }
  233. result, needRestart, err := j.clientService.BulkSetEnable(&j.inboundService, emails, enable)
  234. if err != nil {
  235. logger.Warningf("Batch set enable=%v failed: %v", enable, err)
  236. }
  237. for _, skipped := range result.Skipped {
  238. logger.Warningf("Batch set enable failed for %s: %s", skipped.Email, skipped.Reason)
  239. }
  240. if result.Changed > 0 {
  241. logger.Infof("Batch set enable=%v for %d clients", enable, result.Changed)
  242. }
  243. if needRestart {
  244. j.xrayService.SetToNeedRestart()
  245. }
  246. }
  247. // deleteClientsNotInLDAP detaches clients not in LDAP, one bulk detach per inbound
  248. func (j *LdapSyncJob) deleteClientsNotInLDAP(inboundTag string, ldapEmails map[string]struct{}) {
  249. inbounds, err := j.inboundService.GetAllInbounds()
  250. if err != nil {
  251. logger.Warning("Failed to get inbounds for deletion:", err)
  252. return
  253. }
  254. restartNeeded := false
  255. for _, ib := range inbounds {
  256. if ib.Tag != inboundTag {
  257. continue
  258. }
  259. clients, err := j.inboundService.GetClients(ib)
  260. if err != nil {
  261. logger.Warningf("Failed to get clients for inbound %s: %v", ib.Tag, err)
  262. continue
  263. }
  264. // Collect clients for deletion
  265. toDelete := []model.Client{}
  266. for _, c := range clients {
  267. if _, ok := ldapEmails[c.Email]; !ok {
  268. toDelete = append(toDelete, c)
  269. }
  270. }
  271. if len(toDelete) == 0 {
  272. continue
  273. }
  274. emails := make([]string, len(toDelete))
  275. for i, c := range toDelete {
  276. emails[i] = c.Email
  277. }
  278. result, nr, err := j.clientService.BulkDetach(&j.inboundService, emails, []int{ib.Id})
  279. if err != nil {
  280. logger.Warningf("Failed to delete clients from inbound id=%d(tag=%s): %v", ib.Id, ib.Tag, err)
  281. continue
  282. }
  283. for _, msg := range result.Errors {
  284. logger.Warningf("Failed to delete client from inbound id=%d(tag=%s): %s", ib.Id, ib.Tag, msg)
  285. }
  286. for _, email := range result.Detached {
  287. logger.Infof("Deleted client %s from inbound id=%d(tag=%s)", email, ib.Id, ib.Tag)
  288. }
  289. if nr {
  290. restartNeeded = true
  291. }
  292. }
  293. if restartNeeded {
  294. j.xrayService.SetToNeedRestart()
  295. logger.Info("Xray restart scheduled after batch deletion")
  296. }
  297. }