ldap_sync_job.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. clientsToEnable := map[string][]string{} // tag -> []email
  116. clientsToDisable := map[string][]string{} // tag -> []email
  117. for email, allowed := range flags {
  118. existing := allClients[email]
  119. if existing == nil {
  120. if allowed && autoCreate {
  121. clientsToCreate = append(clientsToCreate, j.buildClient(email, defGB, defExpiryDays, defLimitIP))
  122. }
  123. continue
  124. }
  125. for _, tag := range resolvedTags {
  126. if allowed && !existing.Enable {
  127. clientsToEnable[tag] = append(clientsToEnable[tag], email)
  128. } else if !allowed && existing.Enable {
  129. clientsToDisable[tag] = append(clientsToDisable[tag], email)
  130. }
  131. }
  132. }
  133. j.createClients(clientsToCreate, resolvedInboundIds, resolvedTags)
  134. // --- Execute enable/disable batch ---
  135. for tag, emails := range clientsToEnable {
  136. j.batchSetEnable(inboundMap[tag], emails, true)
  137. }
  138. for tag, emails := range clientsToDisable {
  139. j.batchSetEnable(inboundMap[tag], emails, false)
  140. }
  141. // --- Auto delete clients not in LDAP ---
  142. autoDelete := mustGetBool(j.settingService.GetLdapAutoDelete)
  143. if autoDelete && j.autoDeleteSafeForFetch(len(flags)) {
  144. ldapEmailSet := map[string]struct{}{}
  145. for e := range flags {
  146. ldapEmailSet[e] = struct{}{}
  147. }
  148. for _, tag := range inboundTags {
  149. j.deleteClientsNotInLDAP(tag, ldapEmailSet)
  150. }
  151. }
  152. j.lastFlagCount.Store(int64(len(flags)))
  153. }
  154. // FetchVlessFlags returns (empty, nil) when the bind succeeds but the search
  155. // yields nothing — a renamed OU, a lost read grant — which is not "all gone".
  156. func (j *LdapSyncJob) autoDeleteSafeForFetch(fetched int) bool {
  157. if fetched == 0 {
  158. logger.Warning("LDAP auto-delete skipped: directory returned no usable users")
  159. return false
  160. }
  161. previous := j.lastFlagCount.Load()
  162. if previous > 0 && int64(fetched)*100 < previous*ldapAutoDeleteMinRetainPercent {
  163. logger.Warningf("LDAP auto-delete skipped: fetched %d users, previous successful sync saw %d (below %d%% retention)",
  164. fetched, previous, ldapAutoDeleteMinRetainPercent)
  165. return false
  166. }
  167. return true
  168. }
  169. func truthyValuesOrDefault(s string) []string {
  170. if vals := splitCsv(s); len(vals) > 0 {
  171. return vals
  172. }
  173. return DefaultTruthyValues
  174. }
  175. func splitCsv(s string) []string {
  176. if s == "" {
  177. return nil
  178. }
  179. parts := strings.Split(s, ",")
  180. out := make([]string, 0, len(parts))
  181. for _, p := range parts {
  182. v := strings.TrimSpace(p)
  183. if v != "" {
  184. out = append(out, v)
  185. }
  186. }
  187. return out
  188. }
  189. // buildClient creates a new client for auto-create; ClientService.Create fills per-protocol credentials
  190. func (j *LdapSyncJob) buildClient(email string, defGB, defExpiryDays, defLimitIP int) model.Client {
  191. c := model.Client{
  192. Email: email,
  193. Enable: true,
  194. LimitIP: defLimitIP,
  195. TotalGB: int64(defGB) * 1024 * 1024 * 1024,
  196. }
  197. if defExpiryDays > 0 {
  198. c.ExpiryTime = time.Now().Add(time.Duration(defExpiryDays) * 24 * time.Hour).UnixMilli()
  199. }
  200. return c
  201. }
  202. // createClients adds each new LDAP client once, attached to every configured inbound
  203. func (j *LdapSyncJob) createClients(newClients []model.Client, inboundIds []int, tags []string) {
  204. if len(newClients) == 0 || len(inboundIds) == 0 {
  205. return
  206. }
  207. tagList := strings.Join(tags, ",")
  208. created := 0
  209. restartNeeded := false
  210. for _, c := range newClients {
  211. nr, err := j.clientService.Create(&j.inboundService, &service.ClientCreatePayload{Client: c, InboundIds: inboundIds})
  212. if err != nil {
  213. logger.Warningf("Failed to add client %s for tags %s: %v", c.Email, tagList, err)
  214. continue
  215. }
  216. created++
  217. if nr {
  218. restartNeeded = true
  219. }
  220. }
  221. if created == 0 {
  222. return
  223. }
  224. logger.Infof("LDAP auto-create: %d clients for %s", created, tagList)
  225. if restartNeeded {
  226. j.xrayService.SetToNeedRestart()
  227. }
  228. }
  229. func (j *LdapSyncJob) batchSetEnable(ib *model.Inbound, emails []string, enable bool) {
  230. if len(emails) == 0 {
  231. return
  232. }
  233. restartNeeded := false
  234. changed := 0
  235. for _, email := range emails {
  236. ok, needRestart, err := j.clientService.SetClientEnableByEmail(&j.inboundService, email, enable)
  237. if err != nil {
  238. logger.Warningf("Batch set enable failed for %s in inbound %s: %v", email, ib.Tag, err)
  239. continue
  240. }
  241. if ok {
  242. changed++
  243. }
  244. if needRestart {
  245. restartNeeded = true
  246. }
  247. }
  248. if changed > 0 {
  249. logger.Infof("Batch set enable=%v for %d clients in inbound %s", enable, changed, ib.Tag)
  250. }
  251. if restartNeeded {
  252. j.xrayService.SetToNeedRestart()
  253. }
  254. }
  255. // deleteClientsNotInLDAP deletes clients not in LDAP using batches and a single restart
  256. func (j *LdapSyncJob) deleteClientsNotInLDAP(inboundTag string, ldapEmails map[string]struct{}) {
  257. inbounds, err := j.inboundService.GetAllInbounds()
  258. if err != nil {
  259. logger.Warning("Failed to get inbounds for deletion:", err)
  260. return
  261. }
  262. batchSize := 50 // clients in 1 batch
  263. restartNeeded := false
  264. for _, ib := range inbounds {
  265. if ib.Tag != inboundTag {
  266. continue
  267. }
  268. clients, err := j.inboundService.GetClients(ib)
  269. if err != nil {
  270. logger.Warningf("Failed to get clients for inbound %s: %v", ib.Tag, err)
  271. continue
  272. }
  273. // Collect clients for deletion
  274. toDelete := []model.Client{}
  275. for _, c := range clients {
  276. if _, ok := ldapEmails[c.Email]; !ok {
  277. toDelete = append(toDelete, c)
  278. }
  279. }
  280. if len(toDelete) == 0 {
  281. continue
  282. }
  283. for i := 0; i < len(toDelete); i += batchSize {
  284. end := min(i+batchSize, len(toDelete))
  285. batch := toDelete[i:end]
  286. for _, c := range batch {
  287. nr, err := j.clientService.DetachByEmail(&j.inboundService, ib.Id, c.Email)
  288. if err != nil {
  289. logger.Warningf("Failed to delete client %s from inbound id=%d(tag=%s): %v",
  290. c.Email, ib.Id, ib.Tag, err)
  291. continue
  292. }
  293. logger.Infof("Deleted client %s from inbound id=%d(tag=%s)",
  294. c.Email, ib.Id, ib.Tag)
  295. if nr {
  296. restartNeeded = true
  297. }
  298. }
  299. }
  300. }
  301. if restartNeeded {
  302. j.xrayService.SetToNeedRestart()
  303. logger.Info("Xray restart scheduled after batch deletion")
  304. }
  305. }