修改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

@@ -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"
@@ -81,4 +81,9 @@ iptables_nat = true
#启用压缩
compression = false
#低于及等于多少字节不压缩
no_compress_limit = 256
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

@@ -30,7 +30,7 @@ type User struct {
Email string `json:"email" xorm:"varchar(255)"`
// Password string `json:"password"`
PinCode string `json:"pin_code" xorm:"varchar(32)"`
LimitTime *time.Time `json:"limittime,omitempty" xorm:"Datetime limittime"` //值为null时前端不显示
LimitTime *time.Time `json:"limittime,omitempty" xorm:"Datetime limittime"` // 值为null时前端不显示
OtpSecret string `json:"otp_secret" xorm:"varchar(255)"`
DisableOtp bool `json:"disable_otp" xorm:"Bool"` // 禁用otp
Groups []string `json:"groups" xorm:"Text"`
@@ -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

@@ -19,8 +19,8 @@ var profileHash = ""
func LinkAuth(w http.ResponseWriter, r *http.Request) {
// TODO 调试信息输出
//hd, _ := httputil.DumpRequest(r, true)
//base.Debug("DumpRequest: ", string(hd))
// hd, _ := httputil.DumpRequest(r, true)
// base.Debug("DumpRequest: ", string(hd))
// 判断anyconnect客户端
userAgent := strings.ToLower(r.UserAgent())
@@ -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
)
@@ -49,33 +51,69 @@ func initIpPool() {
IpPool.IpLongMax = utils.Ip2long(net.ParseIP(base.Cfg.Ipv4End))
// 获取IpLease数据
//go cronIpLease()
// 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
@@ -84,21 +122,23 @@ func AcquireIp(username, macAddr string, uniqueMac bool) net.IP {
defer ipPoolMux.Unlock()
var (
err error
tNow = time.Now()
leaseTime = time.Now().Add(-1 * time.Duration(base.Cfg.IpLease) * time.Second)
err error
tNow = time.Now()
)
// 唯一mac
if uniqueMac {
// 判断是否已经分配过
mi := &dbdata.IpMap{}
err = dbdata.One("mac_addr", macAddr, mi)
// 查询报错
if err != nil {
if !dbdata.CheckErrNotFound(err) {
base.Error(err)
return nil
// 没有查询到数据
if dbdata.CheckErrNotFound(err) {
return loopIp(username, macAddr, uniqueMac)
}
// 查询报错
base.Error(err)
return nil
}
// 存在ip记录
@@ -107,59 +147,73 @@ 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 {
ipMaps := []dbdata.IpMap{}
err = dbdata.FindWhere(&ipMaps, 50, 1, "username=? and unique_mac=?", username, false)
// 查询报错
if err != nil {
if !dbdata.CheckErrNotFound(err) {
base.Error(err)
return nil
}
// 没有获取到mac
ipMaps := []dbdata.IpMap{}
err = dbdata.FindWhere(&ipMaps, 50, 1, "username=? and unique_mac=?", username, false)
if err != nil {
// 没有查询到数据
if dbdata.CheckErrNotFound(err) {
return loopIp(username, macAddr, uniqueMac)
}
//遍历mac记录
for _, mi := range ipMaps {
ipStr := mi.IpAddr
ip := net.ParseIP(ipStr)
// 跳过活跃连接
if _, ok := ipActive[ipStr]; ok {
continue
}
//跳过保留ip
if mi.Keep {
continue
}
if IpPool.Ipv4IPNet.Contains(ip) &&
mi.LastLogin.Before(leaseTime) && // 说明已经超过租期,可以直接使用
utils.Ip2long(ip) >= IpPool.IpLongMin &&
utils.Ip2long(ip) <= IpPool.IpLongMax {
mi.LastLogin = tNow
mi.MacAddr = macAddr
mi.UniqueMac = uniqueMac
// 回写db数据
_ = dbdata.Set(mi)
ipActive[ipStr] = true
return ip
}
// 查询报错
base.Error(err)
return nil
}
// 遍历 用户的 mac记录
for _, im := range ipMaps {
mi := &im
ipStr := mi.IpAddr
ip := net.ParseIP(ipStr)
// 跳过活跃连接
if _, ok := ipActive[ipStr]; ok {
continue
}
// 跳过保留ip
if mi.Keep {
continue
}
// 没有租期限制
if utils.Ip2long(ip) >= IpPool.IpLongMin &&
utils.Ip2long(ip) <= IpPool.IpLongMax {
mi.LastLogin = tNow
mi.MacAddr = macAddr
mi.UniqueMac = uniqueMac
// 回写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,41 +223,37 @@ 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 {
continue
}
if mi.LastLogin.Before(leaseTime) {
// 存在记录,说明已经超过租期,可以直接使用
mi.LastLogin = tNow
mi.MacAddr = macAddr
mi.UniqueMac = uniqueMac
// 回写db数据
_ = dbdata.Set(mi)
ipActive[ipStr] = true
return ip
}
// 跳过保留ip
if _, ok := ipKeep[ipStr]; ok {
continue
}
if dbdata.CheckErrNotFound(err) {
// 该ip没有被使用
mi := &dbdata.IpMap{IpAddr: ipStr, MacAddr: macAddr, UniqueMac: uniqueMac, Username: username, LastLogin: tNow}
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 err != nil {
base.Error(err)
return nil
// 存在记录
if mi.LastLogin.Before(leaseTime) {
// 存在记录,说明已经超过租期,可以直接使用
mi.LastLogin = tNow
mi.MacAddr = macAddr
mi.UniqueMac = uniqueMac
// 回写db数据
_ = dbdata.Set(mi)
ipActive[ipStr] = true
ipAll[ipStr] = mi
return ip
}
}
// 最后从未超过租期的记录获取一个
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
}
}