Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ldap_sync_job.go « job « web - github.com/MHSanaei/3x-ui.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 7edb81786c35d8febb756f5cccdc1f276bdbcc6b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package job

import (
	"time"

	"strings"

	"github.com/mhsanaei/3x-ui/v2/database/model"
	"github.com/mhsanaei/3x-ui/v2/logger"
	ldaputil "github.com/mhsanaei/3x-ui/v2/util/ldap"
	"github.com/mhsanaei/3x-ui/v2/web/service"

	"strconv"

	"github.com/google/uuid"
)

var DefaultTruthyValues = []string{"true", "1", "yes", "on"}

type LdapSyncJob struct {
	settingService service.SettingService
	inboundService service.InboundService
	xrayService    service.XrayService
}

// --- Helper functions for mustGet ---
func mustGetString(fn func() (string, error)) string {
	v, err := fn()
	if err != nil {
		panic(err)
	}
	return v
}

func mustGetInt(fn func() (int, error)) int {
	v, err := fn()
	if err != nil {
		panic(err)
	}
	return v
}

func mustGetBool(fn func() (bool, error)) bool {
	v, err := fn()
	if err != nil {
		panic(err)
	}
	return v
}

func mustGetStringOr(fn func() (string, error), fallback string) string {
	v, err := fn()
	if err != nil || v == "" {
		return fallback
	}
	return v
}

func NewLdapSyncJob() *LdapSyncJob {
	return new(LdapSyncJob)
}

func (j *LdapSyncJob) Run() {
	logger.Info("LDAP sync job started")

	enabled, err := j.settingService.GetLdapEnable()
	if err != nil || !enabled {
		logger.Warning("LDAP disabled or failed to fetch flag")
		return
	}

	// --- LDAP fetch ---
	cfg := ldaputil.Config{
		Host:       mustGetString(j.settingService.GetLdapHost),
		Port:       mustGetInt(j.settingService.GetLdapPort),
		UseTLS:     mustGetBool(j.settingService.GetLdapUseTLS),
		BindDN:     mustGetString(j.settingService.GetLdapBindDN),
		Password:   mustGetString(j.settingService.GetLdapPassword),
		BaseDN:     mustGetString(j.settingService.GetLdapBaseDN),
		UserFilter: mustGetString(j.settingService.GetLdapUserFilter),
		UserAttr:   mustGetString(j.settingService.GetLdapUserAttr),
		FlagField:  mustGetStringOr(j.settingService.GetLdapFlagField, mustGetString(j.settingService.GetLdapVlessField)),
		TruthyVals: splitCsv(mustGetString(j.settingService.GetLdapTruthyValues)),
		Invert:     mustGetBool(j.settingService.GetLdapInvertFlag),
	}

	flags, err := ldaputil.FetchVlessFlags(cfg)
	if err != nil {
		logger.Warning("LDAP fetch failed:", err)
		return
	}
	logger.Infof("Fetched %d LDAP flags", len(flags))

	// --- Load all inbounds and all clients once ---
	inboundTags := splitCsv(mustGetString(j.settingService.GetLdapInboundTags))
	inbounds, err := j.inboundService.GetAllInbounds()
	if err != nil {
		logger.Warning("Failed to get inbounds:", err)
		return
	}

	allClients := map[string]*model.Client{}  // email -> client
	inboundMap := map[string]*model.Inbound{} // tag -> inbound
	for _, ib := range inbounds {
		inboundMap[ib.Tag] = ib
		clients, _ := j.inboundService.GetClients(ib)
		for i := range clients {
			allClients[clients[i].Email] = &clients[i]
		}
	}

	// --- Prepare batch operations ---
	autoCreate := mustGetBool(j.settingService.GetLdapAutoCreate)
	defGB := mustGetInt(j.settingService.GetLdapDefaultTotalGB)
	defExpiryDays := mustGetInt(j.settingService.GetLdapDefaultExpiryDays)
	defLimitIP := mustGetInt(j.settingService.GetLdapDefaultLimitIP)

	clientsToCreate := map[string][]model.Client{} // tag -> []new clients
	clientsToEnable := map[string][]string{}       // tag -> []email
	clientsToDisable := map[string][]string{}      // tag -> []email

	for email, allowed := range flags {
		exists := allClients[email] != nil
		for _, tag := range inboundTags {
			if !exists && allowed && autoCreate {
				newClient := j.buildClient(inboundMap[tag], email, defGB, defExpiryDays, defLimitIP)
				clientsToCreate[tag] = append(clientsToCreate[tag], newClient)
			} else if exists {
				if allowed && !allClients[email].Enable {
					clientsToEnable[tag] = append(clientsToEnable[tag], email)
				} else if !allowed && allClients[email].Enable {
					clientsToDisable[tag] = append(clientsToDisable[tag], email)
				}
			}
		}
	}

	// --- Execute batch create ---
	for tag, newClients := range clientsToCreate {
		if len(newClients) == 0 {
			continue
		}
		payload := &model.Inbound{Id: inboundMap[tag].Id}
		payload.Settings = j.clientsToJSON(newClients)
		if _, err := j.inboundService.AddInboundClient(payload); err != nil {
			logger.Warningf("Failed to add clients for tag %s: %v", tag, err)
		} else {
			logger.Infof("LDAP auto-create: %d clients for %s", len(newClients), tag)
			j.xrayService.SetToNeedRestart()
		}
	}

	// --- Execute enable/disable batch ---
	for tag, emails := range clientsToEnable {
		j.batchSetEnable(inboundMap[tag], emails, true)
	}
	for tag, emails := range clientsToDisable {
		j.batchSetEnable(inboundMap[tag], emails, false)
	}

	// --- Auto delete clients not in LDAP ---
	autoDelete := mustGetBool(j.settingService.GetLdapAutoDelete)
	if autoDelete {
		ldapEmailSet := map[string]struct{}{}
		for e := range flags {
			ldapEmailSet[e] = struct{}{}
		}
		for _, tag := range inboundTags {
			j.deleteClientsNotInLDAP(tag, ldapEmailSet)
		}
	}
}

func splitCsv(s string) []string {
	if s == "" {
		return DefaultTruthyValues
	}
	parts := strings.Split(s, ",")
	out := make([]string, 0, len(parts))
	for _, p := range parts {
		v := strings.TrimSpace(p)
		if v != "" {
			out = append(out, v)
		}
	}
	return out
}

// buildClient creates a new client for auto-create
func (j *LdapSyncJob) buildClient(ib *model.Inbound, email string, defGB, defExpiryDays, defLimitIP int) model.Client {
	c := model.Client{
		Email:   email,
		Enable:  true,
		LimitIP: defLimitIP,
		TotalGB: int64(defGB),
	}
	if defExpiryDays > 0 {
		c.ExpiryTime = time.Now().Add(time.Duration(defExpiryDays) * 24 * time.Hour).UnixMilli()
	}
	switch ib.Protocol {
	case model.Trojan, model.Shadowsocks:
		c.Password = uuid.NewString()
	default:
		c.ID = uuid.NewString()
	}
	return c
}

// batchSetEnable enables/disables clients in batch through a single call
func (j *LdapSyncJob) batchSetEnable(ib *model.Inbound, emails []string, enable bool) {
	if len(emails) == 0 {
		return
	}

	// Prepare JSON for mass update
	clients := make([]model.Client, 0, len(emails))
	for _, email := range emails {
		clients = append(clients, model.Client{
			Email:  email,
			Enable: enable,
		})
	}

	payload := &model.Inbound{
		Id:       ib.Id,
		Settings: j.clientsToJSON(clients),
	}

	// Use a single AddInboundClient call to update enable
	if _, err := j.inboundService.AddInboundClient(payload); err != nil {
		logger.Warningf("Batch set enable failed for inbound %s: %v", ib.Tag, err)
		return
	}

	logger.Infof("Batch set enable=%v for %d clients in inbound %s", enable, len(emails), ib.Tag)
	j.xrayService.SetToNeedRestart()
}

// deleteClientsNotInLDAP deletes clients not in LDAP using batches and a single restart
func (j *LdapSyncJob) deleteClientsNotInLDAP(inboundTag string, ldapEmails map[string]struct{}) {
	inbounds, err := j.inboundService.GetAllInbounds()
	if err != nil {
		logger.Warning("Failed to get inbounds for deletion:", err)
		return
	}

	batchSize := 50 //  clients in 1 batch
	restartNeeded := false

	for _, ib := range inbounds {
		if ib.Tag != inboundTag {
			continue
		}
		clients, err := j.inboundService.GetClients(ib)
		if err != nil {
			logger.Warningf("Failed to get clients for inbound %s: %v", ib.Tag, err)
			continue
		}

		// Collect clients for deletion
		toDelete := []model.Client{}
		for _, c := range clients {
			if _, ok := ldapEmails[c.Email]; !ok {
				toDelete = append(toDelete, c)
			}
		}

		if len(toDelete) == 0 {
			continue
		}

		// Delete in batches
		for i := 0; i < len(toDelete); i += batchSize {
			end := min(i+batchSize, len(toDelete))
			batch := toDelete[i:end]

			for _, c := range batch {
				var clientKey string
				switch ib.Protocol {
				case model.Trojan:
					clientKey = c.Password
				case model.Shadowsocks:
					clientKey = c.Email
				default: // vless/vmess
					clientKey = c.ID
				}

				if _, err := j.inboundService.DelInboundClient(ib.Id, clientKey); err != nil {
					logger.Warningf("Failed to delete client %s from inbound id=%d(tag=%s): %v",
						c.Email, ib.Id, ib.Tag, err)
				} else {
					logger.Infof("Deleted client %s from inbound id=%d(tag=%s)",
						c.Email, ib.Id, ib.Tag)
					// do not restart here
					restartNeeded = true
				}
			}
		}
	}

	// One time after all batches
	if restartNeeded {
		j.xrayService.SetToNeedRestart()
		logger.Info("Xray restart scheduled after batch deletion")
	}
}

// clientsToJSON serializes an array of clients to JSON
func (j *LdapSyncJob) clientsToJSON(clients []model.Client) string {
	b := strings.Builder{}
	b.WriteString("{\"clients\":[")
	for i, c := range clients {
		if i > 0 {
			b.WriteString(",")
		}
		b.WriteString(j.clientToJSON(c))
	}
	b.WriteString("]}")
	return b.String()
}

// clientToJSON serializes minimal client fields to JSON object string without extra deps
func (j *LdapSyncJob) clientToJSON(c model.Client) string {
	// construct minimal JSON manually to avoid importing json for simple case
	b := strings.Builder{}
	b.WriteString("{")
	if c.ID != "" {
		b.WriteString("\"id\":\"")
		b.WriteString(c.ID)
		b.WriteString("\",")
	}
	if c.Password != "" {
		b.WriteString("\"password\":\"")
		b.WriteString(c.Password)
		b.WriteString("\",")
	}
	b.WriteString("\"email\":\"")
	b.WriteString(c.Email)
	b.WriteString("\",")
	b.WriteString("\"enable\":")
	if c.Enable {
		b.WriteString("true")
	} else {
		b.WriteString("false")
	}
	b.WriteString(",")
	b.WriteString("\"limitIp\":")
	b.WriteString(strconv.Itoa(c.LimitIP))
	b.WriteString(",")
	b.WriteString("\"totalGB\":")
	b.WriteString(strconv.FormatInt(c.TotalGB, 10))
	if c.ExpiryTime > 0 {
		b.WriteString(",\"expiryTime\":")
		b.WriteString(strconv.FormatInt(c.ExpiryTime, 10))
	}
	b.WriteString("}")
	return b.String()
}