修改ip pool策略

This commit is contained in:
bjdgyc 2023-04-19 18:12:50 +08:00
parent bc9248e16b
commit 638c601c02
15 changed files with 452 additions and 9919 deletions

View File

@ -60,7 +60,7 @@ AnyLink 服务端仅在 CentOS 7、CentOS 8、Ubuntu 18.04、Ubuntu 20.04 测试
### 自行编译安装
> 需要提前安装好 golang >= 1.19 和 nodejs >= 14.x 和 pnpm >= v7.x
> 需要提前安装好 golang >= 1.19 和 nodejs >= 14.x 和 yarn >= v1.22.x
```shell
git clone https://github.com/bjdgyc/anylink.git

View File

@ -19,11 +19,10 @@ cd $cpath/web
#npm install --registry=https://registry.npm.taobao.org
#npm install
#npm run build
#yarn install
#yarn run build
pnpm i --registry=https://registry.npmmirror.com
pnpm build
yarn install --registry=https://registry.npmmirror.com
yarn run build
RETVAL $?

View File

@ -7,6 +7,7 @@ import (
"strconv"
"github.com/bjdgyc/anylink/dbdata"
"github.com/bjdgyc/anylink/sessdata"
)
func UserIpMapList(w http.ResponseWriter, r *http.Request) {
@ -80,6 +81,8 @@ func UserIpMapSet(w http.ResponseWriter, r *http.Request) {
return
}
sessdata.IpAllSet(v)
RespSucess(w, nil)
}
@ -93,11 +96,20 @@ func UserIpMapDel(w http.ResponseWriter, r *http.Request) {
return
}
data := dbdata.IpMap{Id: id}
err := dbdata.Del(&data)
var data dbdata.IpMap
err := dbdata.One("Id", id, &data)
if err != nil {
RespError(w, RespInternalErr, err)
return
}
err = dbdata.Del(&data)
if err != nil {
RespError(w, RespInternalErr, err)
return
}
sessdata.IpAllDel(&data)
RespSucess(w, nil)
}

View File

@ -77,6 +77,8 @@ type ServerConfig struct {
IptablesNat bool `json:"iptables_nat"`
Compression bool `json:"compression"` // bool
NoCompressLimit int `json:"no_compress_limit"` // int
DisplayError bool `json:"display_error"`
}
func initServerCfg() {

View File

@ -48,7 +48,7 @@ var configs = []config{
{Typ: cfgStr, Name: "default_group", Usage: "默认用户组", ValStr: "one"},
{Typ: cfgStr, Name: "default_domain", Usage: "要发布的默认域", ValStr: ""},
{Typ: cfgInt, Name: "ip_lease", Usage: "IP租期(秒)", ValInt: 1209600},
{Typ: cfgInt, Name: "ip_lease", Usage: "IP租期(秒)", ValInt: 86400},
{Typ: cfgInt, Name: "max_client", Usage: "最大用户连接", ValInt: 200},
{Typ: cfgInt, Name: "max_user_client", Usage: "最大单用户连接", ValInt: 3},
{Typ: cfgInt, Name: "cstp_keepalive", Usage: "keepalive时间(秒)", ValInt: 4},
@ -56,7 +56,7 @@ var configs = []config{
{Typ: cfgInt, Name: "mobile_keepalive", Usage: "移动端keepalive接检测时间(秒)", ValInt: 7},
{Typ: cfgInt, Name: "mobile_dpd", Usage: "移动端死链接检测时间(秒)", ValInt: 15},
{Typ: cfgInt, Name: "mtu", Usage: "最大传输单元MTU", ValInt: 1460},
{Typ: cfgInt, Name: "session_timeout", Usage: "session过期时间(秒)", ValInt: 3600},
{Typ: cfgInt, Name: "session_timeout", Usage: "session过期时间(秒)-用于断线重连0永不过期", ValInt: 3600},
// {Typ: cfgInt, Name: "auth_timeout", Usage: "auth_timeout", ValInt: 0},
{Typ: cfgInt, Name: "audit_interval", Usage: "审计去重间隔(秒),-1关闭", ValInt: -1},
@ -64,6 +64,8 @@ var configs = []config{
{Typ: cfgBool, Name: "iptables_nat", Usage: "是否自动添加NAT", ValBool: true},
{Typ: cfgBool, Name: "compression", Usage: "启用压缩", ValBool: false},
{Typ: cfgInt, Name: "no_compress_limit", Usage: "低于及等于多少字节不压缩", ValInt: 256},
{Typ: cfgBool, Name: "display_error", Usage: "客户端显示详细错误信息(线上环境慎开启)", ValBool: false},
}
var envs = map[string]string{}

View File

@ -50,7 +50,7 @@ max_client = 100
#单个用户同时在线数量
max_user_client = 3
#IP租期(秒)
ip_lease = 1209600
ip_lease = 86400
#默认选择的组
default_group = "one"
@ -82,3 +82,8 @@ iptables_nat = true
compression = false
#低于及等于多少字节不压缩
no_compress_limit = 256
#客户端显示详细错误信息(线上环境慎开启)
display_error = false

View File

@ -35,3 +35,9 @@ ipv4_end = "192.168.90.200"
#是否自动添加nat
iptables_nat = true
#客户端显示详细错误信息(线上环境慎开启)
display_error = false

View File

@ -5,17 +5,18 @@ import (
"time"
)
// type IpMap struct {
// Id int `json:"id" xorm:"pk autoincr not null"`
// IpAddr string `json:"ip_addr" xorm:"not null unique"`
// MacAddr string `json:"mac_addr" xorm:"not null unique"`
// Username string `json:"username"`
// Keep bool `json:"keep"` // 保留 ip-mac 绑定
// KeepTime time.Time `json:"keep_time"`
// Note string `json:"note"` // 备注
// LastLogin time.Time `json:"last_login"`
// UpdatedAt time.Time `json:"updated_at"`
// }
type IpMap struct {
Id int `json:"id" xorm:"pk autoincr not null"`
IpAddr string `json:"ip_addr" xorm:"varchar(32) not null unique"`
MacAddr string `json:"mac_addr" xorm:"varchar(32) not null unique"`
UniqueMac bool `json:"unique_mac" xorm:"Bool index"`
Username string `json:"username" xorm:"varchar(60)"`
Keep bool `json:"keep" xorm:"Bool"` // 保留 ip-mac 绑定
KeepTime time.Time `json:"keep_time" xorm:"DateTime"`
Note string `json:"note" xorm:"varchar(255)"` // 备注
LastLogin time.Time `json:"last_login" xorm:"DateTime"`
UpdatedAt time.Time `json:"updated_at" xorm:"DateTime updated"`
}
func SetIpMap(v *IpMap) error {
var err error

View File

@ -56,19 +56,6 @@ type UserActLog struct {
CreatedAt time.Time `json:"created_at" xorm:"DateTime created"`
}
type IpMap struct {
Id int `json:"id" xorm:"pk autoincr not null"`
IpAddr string `json:"ip_addr" xorm:"varchar(32) not null unique"`
MacAddr string `json:"mac_addr" xorm:"varchar(32) not null unique"`
UniqueMac bool `json:"unique_mac" xorm:"Bool index"`
Username string `json:"username" xorm:"varchar(60)"`
Keep bool `json:"keep" xorm:"Bool"` // 保留 ip-mac 绑定
KeepTime time.Time `json:"keep_time" xorm:"DateTime"`
Note string `json:"note" xorm:"varchar(255)"` // 备注
LastLogin time.Time `json:"last_login" xorm:"DateTime"`
UpdatedAt time.Time `json:"updated_at" xorm:"DateTime updated"`
}
type Setting struct {
Id int `json:"id" xorm:"pk autoincr not null"`
Name string `json:"name" xorm:"varchar(60) not null unique"`

View File

@ -88,6 +88,9 @@ func LinkAuth(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
data := RequestData{Group: cr.GroupSelect, Groups: dbdata.GetGroupNamesNormal(), Error: "用户名或密码错误"}
if base.Cfg.DisplayError {
data.Error = err.Error()
}
tplRequest(tpl_request, w, data)
return
}

View File

@ -13,8 +13,10 @@ import (
var (
IpPool = &ipPoolConfig{}
ipActive = map[string]bool{}
ipAll = map[string]*dbdata.IpMap{}
ipKeep = map[string]bool{}
// ipKeep and ipLease ipAddr => type
ipLease = map[string]bool{}
// ipLease = map[string]bool{}
ipPoolMux sync.Mutex
)
@ -50,32 +52,68 @@ func initIpPool() {
// 获取IpLease数据
// go cronIpLease()
getIpMapAll()
}
func cronIpLease() {
getIpLease()
tick := time.NewTicker(time.Minute * 30)
for range tick.C {
getIpLease()
}
}
// func cronIpLease() {
// getIpLease()
// tick := time.NewTicker(time.Minute * 30)
// for range tick.C {
// getIpLease()
// }
// }
//
// func getIpLease() {
// xdb := dbdata.GetXdb()
// keepIpMaps := []dbdata.IpMap{}
// sNow := time.Now().Add(-1 * time.Duration(base.Cfg.IpLease) * time.Second)
// err := xdb.Cols("ip_addr").Where("keep=?", true).
// Or("unique_mac=? and last_login>?", true, sNow).Find(&keepIpMaps)
// if err != nil {
// base.Error(err)
// }
// // fmt.Println(keepIpMaps)
// ipPoolMux.Lock()
// ipLease = map[string]bool{}
// for _, v := range keepIpMaps {
// ipLease[v.IpAddr] = true
// }
// ipPoolMux.Unlock()
// }
func getIpLease() {
xdb := dbdata.GetXdb()
keepIpMaps := []dbdata.IpMap{}
sNow := time.Now().Add(-1 * time.Duration(base.Cfg.IpLease) * time.Second)
err := xdb.Cols("ip_addr").Where("keep=?", true).
Or("unique_mac=? and last_login>?", true, sNow).Find(&keepIpMaps)
if err != nil {
base.Error(err)
}
// fmt.Println(keepIpMaps)
func IpAllSet(v *dbdata.IpMap) {
ipPoolMux.Lock()
ipLease = map[string]bool{}
for _, v := range keepIpMaps {
ipLease[v.IpAddr] = true
defer ipPoolMux.Unlock()
ipAll[v.IpAddr] = v
if v.Keep {
ipKeep[v.IpAddr] = true
} else {
delete(ipKeep, v.IpAddr)
}
}
func IpAllDel(v *dbdata.IpMap) {
ipPoolMux.Lock()
defer ipPoolMux.Unlock()
delete(ipAll, v.IpAddr)
delete(ipKeep, v.IpAddr)
}
func getIpMapAll() {
xdb := dbdata.GetXdb()
ipMaps := []dbdata.IpMap{}
err := xdb.Find(&ipMaps)
if err != nil {
base.Fatal(err)
}
for _, v := range ipMaps {
ipAll[v.IpAddr] = &v
if v.Keep {
ipKeep[v.IpAddr] = true
}
}
ipPoolMux.Unlock()
}
// AcquireIp 获取动态ip
@ -86,20 +124,22 @@ func AcquireIp(username, macAddr string, uniqueMac bool) net.IP {
var (
err error
tNow = time.Now()
leaseTime = time.Now().Add(-1 * time.Duration(base.Cfg.IpLease) * time.Second)
)
// 唯一mac
if uniqueMac {
// 判断是否已经分配过
mi := &dbdata.IpMap{}
err = dbdata.One("mac_addr", macAddr, mi)
// 查询报错
if err != nil {
if !dbdata.CheckErrNotFound(err) {
// 没有查询到数据
if dbdata.CheckErrNotFound(err) {
return loopIp(username, macAddr, uniqueMac)
}
// 查询报错
base.Error(err)
return nil
}
}
// 存在ip记录
ipStr := mi.IpAddr
@ -107,35 +147,41 @@ func AcquireIp(username, macAddr string, uniqueMac bool) net.IP {
// 跳过活跃连接
_, ok := ipActive[ipStr]
// 检测原有ip是否在新的ip池内
if IpPool.Ipv4IPNet.Contains(ip) && !ok &&
utils.Ip2long(ip) >= IpPool.IpLongMin &&
utils.Ip2long(ip) <= IpPool.IpLongMax {
// IpPool.Ipv4IPNet.Contains(ip) &&
if utils.Ip2long(ip) >= IpPool.IpLongMin &&
utils.Ip2long(ip) <= IpPool.IpLongMax && !ok {
mi.Username = username
mi.LastLogin = tNow
mi.UniqueMac = uniqueMac
// 回写db数据
_ = dbdata.Set(mi)
ipActive[ipStr] = true
ipAll[ipStr] = mi
return ip
}
// 原有ip不符合
_ = dbdata.Del(mi)
delete(ipAll, ipStr)
return loopIp(username, macAddr, uniqueMac)
}
} else {
// 没有获取到mac
ipMaps := []dbdata.IpMap{}
err = dbdata.FindWhere(&ipMaps, 50, 1, "username=? and unique_mac=?", username, false)
// 查询报错
if err != nil {
if !dbdata.CheckErrNotFound(err) {
// 没有查询到数据
if dbdata.CheckErrNotFound(err) {
return loopIp(username, macAddr, uniqueMac)
}
// 查询报错
base.Error(err)
return nil
}
}
//遍历mac记录
for _, mi := range ipMaps {
// 遍历 用户的 mac记录
for _, im := range ipMaps {
mi := &im
ipStr := mi.IpAddr
ip := net.ParseIP(ipStr)
// 跳过活跃连接
if _, ok := ipActive[ipStr]; ok {
continue
@ -144,10 +190,8 @@ func AcquireIp(username, macAddr string, uniqueMac bool) net.IP {
if mi.Keep {
continue
}
if IpPool.Ipv4IPNet.Contains(ip) &&
mi.LastLogin.Before(leaseTime) && // 说明已经超过租期,可以直接使用
utils.Ip2long(ip) >= IpPool.IpLongMin &&
// 没有租期限制
if utils.Ip2long(ip) >= IpPool.IpLongMin &&
utils.Ip2long(ip) <= IpPool.IpLongMax {
mi.LastLogin = tNow
mi.MacAddr = macAddr
@ -155,11 +199,21 @@ func AcquireIp(username, macAddr string, uniqueMac bool) net.IP {
// 回写db数据
_ = dbdata.Set(mi)
ipActive[ipStr] = true
ipAll[ipStr] = mi
return ip
}
}
return loopIp(username, macAddr, uniqueMac)
}
// 遍历ip
func loopIp(username, macAddr string, uniqueMac bool) net.IP {
var (
tNow = time.Now()
leaseTime = time.Now().Add(-1 * time.Duration(base.Cfg.IpLease) * time.Second)
)
// 全局遍历超过租期和未保留的ip
for i := IpPool.IpLongMin; i <= IpPool.IpLongMax; i++ {
ip := utils.Long2ip(i)
@ -169,14 +223,22 @@ func AcquireIp(username, macAddr string, uniqueMac bool) net.IP {
if _, ok := ipActive[ipStr]; ok {
continue
}
mi := &dbdata.IpMap{}
err = dbdata.One("ip_addr", ipStr, mi)
if err == nil {
// 跳过保留ip
if mi.Keep {
if _, ok := ipKeep[ipStr]; ok {
continue
}
mi, ok := ipAll[ipStr]
if !ok {
// 该ip没有被使用 直接返回
mi = &dbdata.IpMap{IpAddr: ipStr, MacAddr: macAddr, UniqueMac: uniqueMac, Username: username, LastLogin: tNow}
_ = dbdata.Add(mi)
ipActive[ipStr] = true
ipAll[ipStr] = mi
return ip
}
// 存在记录
if mi.LastLogin.Before(leaseTime) {
// 存在记录,说明已经超过租期,可以直接使用
mi.LastLogin = tNow
@ -185,24 +247,12 @@ func AcquireIp(username, macAddr string, uniqueMac bool) net.IP {
// 回写db数据
_ = dbdata.Set(mi)
ipActive[ipStr] = true
ipAll[ipStr] = mi
return ip
}
}
if dbdata.CheckErrNotFound(err) {
// 该ip没有被使用
mi := &dbdata.IpMap{IpAddr: ipStr, MacAddr: macAddr, UniqueMac: uniqueMac, Username: username, LastLogin: tNow}
_ = dbdata.Add(mi)
ipActive[ipStr] = true
return ip
}
// 查询报错
if err != nil {
base.Error(err)
return nil
}
}
// 最后从未超过租期的记录获取一个
base.Warn("no ip available, please see ip_map table row")
return nil
@ -220,5 +270,6 @@ func ReleaseIp(ip net.IP, macAddr string) {
if err == nil {
mi.LastLogin = time.Now()
_ = dbdata.Set(mi)
ipAll[mi.IpAddr] = mi
}
}

File diff suppressed because it is too large Load Diff

View File

@ -194,8 +194,7 @@
<el-form-item label="排除本地网络" prop="allow_lan">
<el-switch
v-model="ruleForm.allow_lan"
active-text="开启后 用户本地所在网段将不通过anylink加密传输"
inactive-text="开启后 用户本地所在网段将不通过anylink加密传输">
active-text="开启后 用户本地所在网段将不通过anylink加密传输">
</el-switch>
</el-form-item>

View File

@ -11,6 +11,12 @@
@click="handleEdit('')">添加
</el-button>
</el-form-item>
<el-form-item>
<el-alert
title="直接操作数据库增删改数据后请重启anylink服务"
type="warning">
</el-alert>
</el-form-item>
</el-form>
<el-table

View File

@ -6759,6 +6759,13 @@ qs@6.9.7:
resolved "https://registry.yarnpkg.com/qs/-/qs-6.9.7.tgz#4610846871485e1e048f44ae3b94033f0e675afe"
integrity sha512-IhMFgUmuNpyRfxA90umL7ByLlgRXu6tIfKPpF5TmcfRLlLCckfP/g3IQmju6jjpu+Hh8rA+2p6A27ZSPOOHdKw==
qs@^6.11.1:
version "6.11.1"
resolved "https://registry.npmmirror.com/qs/-/qs-6.11.1.tgz#6c29dff97f0c0060765911ba65cbc9764186109f"
integrity sha512-0wsrzgTz/kAVIeuxSjnpGC56rzYtr6JT/2BwEvMaPhFIoYa1aGO8LbzuU1R0uUYQkLpWBTOj0l/CLAJB64J6nQ==
dependencies:
side-channel "^1.0.4"
qs@~6.5.2:
version "6.5.3"
resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.3.tgz#3aeeffc91967ef6e35c0e488ef46fb296ab76aad"