some changes

ip limit method back to v1.6.0 method
remove event on getDBClientIps
better show ip on log (",\n")
This commit is contained in:
MHSanaei 2023-06-03 18:59:32 +03:30
parent 33a598366b
commit fdc1124ea4
6 changed files with 86 additions and 102 deletions

View file

@ -57,6 +57,7 @@
</span> </span>
<a-input v-model.trim="clientsBulkModal.tgId"></a-input> <a-input v-model.trim="clientsBulkModal.tgId"></a-input>
</a-form-item> </a-form-item>
<br>
<a-form-item> <a-form-item>
<span slot="label"> <span slot="label">
<span>{{ i18n "pages.inbounds.IPLimit" }}</span> <span>{{ i18n "pages.inbounds.IPLimit" }}</span>

View file

@ -120,26 +120,27 @@
}, },
}, },
methods: { methods: {
async getDBClientIps(email, event) { async getDBClientIps(email) {
const msg = await HttpUtil.post('/panel/inbound/clientIps/' + email);
if (!msg.success) {
return;
}
try { try {
ips = JSON.parse(msg.obj) const msg = await HttpUtil.post(`/panel/inbound/clientIps/${email}`);
ips = ips.join(",") if (!msg.success) {
event.target.value = ips return;
}
const ips = JSON.parse(msg.obj).join(",\n");
document.getElementById("clientIPs").value = ips;
} catch (error) { } catch (error) {
// text document.getElementById("clientIPs").value = msg.obj;
event.target.value = msg.obj
} }
}, },
async clearDBClientIps(email) { async clearDBClientIps(email) {
const msg = await HttpUtil.post('/panel/inbound/clearClientIps/' + email); try {
if (!msg.success) { const msg = await HttpUtil.post(`/panel/inbound/clearClientIps/${email}`);
return; if (!msg.success) {
return;
}
document.getElementById("clientIPs").value = "";
} catch (error) {
} }
document.getElementById("clientIPs").value = ""
}, },
resetClientTraffic(email, dbInboundId, iconElement) { resetClientTraffic(email, dbInboundId, iconElement) {
this.$confirm({ this.$confirm({

View file

@ -72,31 +72,32 @@
<a-input-number v-model="client.limitIp" min="0"></a-input-number> <a-input-number v-model="client.limitIp" min="0"></a-input-number>
</a-form-item> </a-form-item>
<a-form-item v-if="client.email && client.limitIp > 0 && isEdit"> <a-form-item v-if="client.email && client.limitIp > 0 && isEdit">
<span slot="label"> <span slot="label">
<span>{{ i18n "pages.inbounds.IPLimitlog" }}</span> <span>{{ i18n "pages.inbounds.IPLimitlog" }}</span>
<a-tooltip> <a-tooltip>
<template slot="title"> <template slot="title">
<span>{{ i18n "pages.inbounds.IPLimitlogDesc" }}</span> <span>{{ i18n "pages.inbounds.IPLimitlogDesc" }}</span>
</template> </template>
<a-icon type="question-circle" theme="filled"></a-icon> <a-icon type="question-circle" theme="filled"></a-icon>
</a-tooltip> </a-tooltip>
<a-tooltip> <a-tooltip>
<template slot="title"> <template slot="title">
<span>{{ i18n "pages.inbounds.IPLimitlogclear" }}</span> <span>{{ i18n "pages.inbounds.IPLimitlogclear" }}</span>
</template> </template>
<span style="color: #FF4D4F"> <span style="color: #FF4D4F">
<a-icon type="delete" @click="clearDBClientIps(client.email)"></a-icon> <a-icon type="delete" @click="clearDBClientIps(client.email)"></a-icon>
</span> </span>
</a-tooltip> </a-tooltip>
</span> </span>
<a-form layout="block"> <a-form layout="block">
<a-textarea id="clientIPs" readonly <a-textarea id="clientIPs" readonly
@click="getDBClientIps(client.email,$event)" @click="getDBClientIps(client.email)"
placeholder="Click To Get IPs" placeholder="Click To Get IPs"
:auto-size="{ minRows: 2, maxRows: 10 }"> :auto-size="{ minRows: 5, maxRows: 10 }"
</a-textarea> >
</a-form> </a-textarea>
</a-form-item> </a-form>
</a-form-item>
<br> <br>
<a-form-item v-if="inbound.xtls" label="Flow"> <a-form-item v-if="inbound.xtls" label="Flow">
<a-select v-model="client.flow" style="width: 200px" :dropdown-class-name="themeSwitcher.darkCardClass"> <a-select v-model="client.flow" style="width: 200px" :dropdown-class-name="themeSwitcher.darkCardClass">

View file

@ -1,12 +1,13 @@
{{define "form/inbound"}} {{define "form/inbound"}}
<!-- base --> <!-- base -->
<a-form layout="inline"> <a-form layout="inline">
<a-form-item label='{{ i18n "remark" }}'>
<a-input v-model.trim="dbInbound.remark"></a-input>
</a-form-item>
<a-form-item label='{{ i18n "enable" }}'> <a-form-item label='{{ i18n "enable" }}'>
<a-switch v-model="dbInbound.enable"></a-switch> <a-switch v-model="dbInbound.enable"></a-switch>
</a-form-item> </a-form-item>
<br>
<a-form-item label='{{ i18n "remark" }}'>
<a-input v-model.trim="dbInbound.remark"></a-input>
</a-form-item>
<a-form-item label='{{ i18n "protocol" }}'> <a-form-item label='{{ i18n "protocol" }}'>
<a-select v-model="inbound.protocol" style="width: 160px;" :disabled="isEdit" :dropdown-class-name="themeSwitcher.darkCardClass"> <a-select v-model="inbound.protocol" style="width: 160px;" :disabled="isEdit" :dropdown-class-name="themeSwitcher.darkCardClass">
<a-select-option v-for="p in Protocols" :key="p" :value="p">[[ p ]]</a-select-option> <a-select-option v-for="p in Protocols" :key="p" :value="p">[[ p ]]</a-select-option>

View file

@ -4,7 +4,6 @@ import (
"encoding/json" "encoding/json"
"os" "os"
"regexp" "regexp"
"sync"
"x-ui/database" "x-ui/database"
"x-ui/database/model" "x-ui/database/model"
"x-ui/logger" "x-ui/logger"
@ -21,38 +20,33 @@ import (
type CheckClientIpJob struct { type CheckClientIpJob struct {
xrayService service.XrayService xrayService service.XrayService
AllowedIps []string
mutex sync.Mutex
} }
var job *CheckClientIpJob var job *CheckClientIpJob
var AllowedIps []string var disAllowedIps []string
var ipRegx *regexp.Regexp = regexp.MustCompile(`[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+`)
var emailRegx *regexp.Regexp = regexp.MustCompile(`email:.+`)
func NewCheckClientIpJob() *CheckClientIpJob { func NewCheckClientIpJob() *CheckClientIpJob {
job := &CheckClientIpJob{} job = new(CheckClientIpJob)
return job return job
} }
func (j *CheckClientIpJob) Run() { func (j *CheckClientIpJob) Run() {
logger.Debug("Check Client IP Job...") logger.Debug("Check Client IP Job...")
j.processLogFile() processLogFile()
// AllowedIps = []string{"192.168.1.183","192.168.1.197"} blockedIps := []byte(strings.Join(disAllowedIps, ","))
allowedIps := []byte(strings.Join(j.getAllowedIps(), ","))
// check if file exists, if not create one // check if file exists, if not create one
_, err := os.Stat(xray.GetAllowedIPsPath()) _, err := os.Stat(xray.GetBlockedIPsPath())
if os.IsNotExist(err) { if os.IsNotExist(err) {
_, err = os.OpenFile(xray.GetAllowedIPsPath(), os.O_RDWR|os.O_CREATE, 0755) _, err = os.OpenFile(xray.GetBlockedIPsPath(), os.O_RDWR|os.O_CREATE, 0755)
checkError(err) checkError(err)
} }
err = os.WriteFile(xray.GetAllowedIPsPath(), allowedIps, 0755) err = os.WriteFile(xray.GetBlockedIPsPath(), blockedIps, 0755)
checkError(err) checkError(err)
} }
func (j *CheckClientIpJob) processLogFile() { func processLogFile() {
accessLogPath := GetAccessLogPath() accessLogPath := GetAccessLogPath()
if accessLogPath == "" { if accessLogPath == "" {
logger.Warning("access.log doesn't exist in your config.json") logger.Warning("access.log doesn't exist in your config.json")
@ -70,6 +64,8 @@ func (j *CheckClientIpJob) processLogFile() {
lines := strings.Split(string(data), "\n") lines := strings.Split(string(data), "\n")
for _, line := range lines { for _, line := range lines {
ipRegx, _ := regexp.Compile(`[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+`)
emailRegx, _ := regexp.Compile(`email:.+`)
matchesIp := ipRegx.FindString(line) matchesIp := ipRegx.FindString(line)
if len(matchesIp) > 0 { if len(matchesIp) > 0 {
@ -84,13 +80,19 @@ func (j *CheckClientIpJob) processLogFile() {
} }
matchesEmail = strings.TrimSpace(strings.Split(matchesEmail, "email: ")[1]) matchesEmail = strings.TrimSpace(strings.Split(matchesEmail, "email: ")[1])
if !contains(InboundClientIps[matchesEmail], ip) { if InboundClientIps[matchesEmail] != nil {
if contains(InboundClientIps[matchesEmail], ip) {
continue
}
InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
} else {
InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip) InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
} }
} }
} }
j.setAllowedIps([]string{}) disAllowedIps = []string{}
for clientEmail, ips := range InboundClientIps { for clientEmail, ips := range InboundClientIps {
inboundClientIps, err := GetInboundClientIps(clientEmail) inboundClientIps, err := GetInboundClientIps(clientEmail)
@ -99,7 +101,7 @@ func (j *CheckClientIpJob) processLogFile() {
addInboundClientIps(clientEmail, ips) addInboundClientIps(clientEmail, ips)
} else { } else {
j.updateInboundClientIps(inboundClientIps, clientEmail, ips) updateInboundClientIps(inboundClientIps, clientEmail, ips)
} }
} }
@ -112,7 +114,6 @@ func (j *CheckClientIpJob) processLogFile() {
stop <- true stop <- true
} }
func GetAccessLogPath() string { func GetAccessLogPath() string {
config, err := os.ReadFile(xray.GetConfigPath()) config, err := os.ReadFile(xray.GetConfigPath())
@ -133,22 +134,20 @@ func GetAccessLogPath() string {
return "" return ""
} }
func checkError(e error) { func checkError(e error) {
if e != nil { if e != nil {
logger.Warning("client ip job err:", e) logger.Warning("client ip job err:", e)
} }
} }
func contains(s []string, str string) bool { func contains(s []string, str string) bool {
for _, v := range s { for _, v := range s {
if v == str { if v == str {
return true return true
} }
} }
return false return false
} }
func GetInboundClientIps(clientEmail string) (*model.InboundClientIps, error) { func GetInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
db := database.GetDB() db := database.GetDB()
InboundClientIps := &model.InboundClientIps{} InboundClientIps := &model.InboundClientIps{}
@ -158,7 +157,6 @@ func GetInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
} }
return InboundClientIps, nil return InboundClientIps, nil
} }
func addInboundClientIps(clientEmail string, ips []string) error { func addInboundClientIps(clientEmail string, ips []string) error {
inboundClientIps := &model.InboundClientIps{} inboundClientIps := &model.InboundClientIps{}
jsonIps, err := json.Marshal(ips) jsonIps, err := json.Marshal(ips)
@ -171,10 +169,10 @@ func addInboundClientIps(clientEmail string, ips []string) error {
tx := db.Begin() tx := db.Begin()
defer func() { defer func() {
if r := recover(); r != nil { if err == nil {
tx.Rollback()
} else {
tx.Commit() tx.Commit()
} else {
tx.Rollback()
} }
}() }()
@ -184,7 +182,13 @@ func addInboundClientIps(clientEmail string, ips []string) error {
} }
return nil return nil
} }
func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, ips []string) error { func updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, ips []string) error {
jsonIps, err := json.Marshal(ips)
checkError(err)
inboundClientIps.ClientEmail = clientEmail
inboundClientIps.Ips = string(jsonIps)
// check inbound limitation // check inbound limitation
inbound, err := GetInboundByEmail(clientEmail) inbound, err := GetInboundByEmail(clientEmail)
@ -201,22 +205,17 @@ func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.Inboun
for _, client := range clients { for _, client := range clients {
if client.Email == clientEmail { if client.Email == clientEmail {
limitIp := client.LimitIP limitIp := client.LimitIP
if limitIp < len(ips) && limitIp != 0 && inbound.Enable { if limitIp < len(ips) && limitIp != 0 && inbound.Enable {
for _, ip := range ips[:limitIp] {
j.addAllowedIp(ip) disAllowedIps = append(disAllowedIps, ips[limitIp:]...)
}
} }
} }
} }
logger.Debug("disAllowedIps ", disAllowedIps)
jsonIps, err := json.Marshal(ips) // marshal the possibly truncated list of IPs sort.Strings(disAllowedIps)
checkError(err)
inboundClientIps.ClientEmail = clientEmail
inboundClientIps.Ips = string(jsonIps)
logger.Debug("Allowed IPs: ", ips)
db := database.GetDB() db := database.GetDB()
err = db.Save(inboundClientIps).Error err = db.Save(inboundClientIps).Error
@ -225,25 +224,6 @@ func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.Inboun
} }
return nil return nil
} }
func (j *CheckClientIpJob) setAllowedIps(ips []string) {
j.mutex.Lock()
defer j.mutex.Unlock()
j.AllowedIps = ips
}
func (j *CheckClientIpJob) addAllowedIp(ip string) {
j.mutex.Lock()
defer j.mutex.Unlock()
j.AllowedIps = append(j.AllowedIps, ip)
}
func (j *CheckClientIpJob) getAllowedIps() []string {
j.mutex.Lock()
defer j.mutex.Unlock()
return j.AllowedIps
}
func DisableInbound(id int) error { func DisableInbound(id int) error {
db := database.GetDB() db := database.GetDB()
result := db.Model(model.Inbound{}). result := db.Model(model.Inbound{}).
@ -297,7 +277,7 @@ func LimitDevice() {
srcPort = portRegx.FindString(data[1]) srcPort = portRegx.FindString(data[1])
srcPort = strings.Replace(srcPort, ":", "", -1) srcPort = strings.Replace(srcPort, ":", "", -1)
if contains(AllowedIps, srcIp) { if contains(disAllowedIps, srcIp) {
dropCmd := cmd.NewCmd("bash", "-c", "ss -K dport = "+srcPort) dropCmd := cmd.NewCmd("bash", "-c", "ss -K dport = "+srcPort)
dropCmd.Start() dropCmd.Start()

View file

@ -51,8 +51,8 @@ func GetIranPath() string {
return config.GetBinFolderPath() + "/iran.dat" return config.GetBinFolderPath() + "/iran.dat"
} }
func GetAllowedIPsPath() string { func GetBlockedIPsPath() string {
return config.GetBinFolderPath() + "/AllowedIPs" return config.GetBinFolderPath() + "/BlockedIps"
} }
func stopProcess(p *Process) { func stopProcess(p *Process) {
@ -173,7 +173,7 @@ func (p *process) Start() (err error) {
return common.NewErrorf("Failed to write configuration file: %v", err) return common.NewErrorf("Failed to write configuration file: %v", err)
} }
cmd := exec.Command(GetBinaryPath(), "-c", configPath, "-restrictedIPsPath", GetAllowedIPsPath()) cmd := exec.Command(GetBinaryPath(), "-c", configPath, "-restrictedIPsPath", GetBlockedIPsPath())
p.cmd = cmd p.cmd = cmd
stdReader, err := cmd.StdoutPipe() stdReader, err := cmd.StdoutPipe()