Merge pull request #50 from bjdgyc/dev

更换为sql数据库
This commit is contained in:
bjdgyc 2021-08-02 11:42:49 +08:00 committed by GitHub
commit 6daf4e1b03
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 14236 additions and 179 deletions

View File

@ -18,7 +18,7 @@ COPY --from=builder_node /web/ui /anylink/server/ui
#TODO 本地打包时使用镜像
#RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories
RUN apk add --no-cache git
RUN apk add --no-cache git gcc
RUN cd /anylink/server;go build -o anylink -ldflags "-X main.CommitId=$(git rev-parse HEAD)" \
&& /anylink/server/anylink tool -v

View File

@ -77,7 +77,7 @@ sudo ./anylink
## Config
> 默认配置文件内有详细的注释,根据注释填写配置即可。
> 示例配置文件内有详细的注释,根据注释填写配置即可。
```shell
# 生成后台密码
@ -179,25 +179,29 @@ systemd 脚本放入:
```bash
docker pull bjdgyc/anylink:latest
# 查看帮助命令信息
```
2. 查看命令信息
```bash
docker run -it --rm bjdgyc/anylink -h
```
2. 生成密码
3. 生成密码
```bash
docker run -it --rm bjdgyc/anylink tool -p 123456
#Passwd:$2a$10$lCWTCcGmQdE/4Kb1wabbLelu4vY/cUwBwN64xIzvXcihFgRzUvH2a
```
3. 生成jwt secret
4. 生成jwt secret
```bash
docker run -it --rm bjdgyc/anylink tool -s
#Secret:9qXoIhY01jqhWIeIluGliOS4O_rhcXGGGu422uRZ1JjZxIZmh17WwzW36woEbA
```
4. 启动容器
5. 启动容器
```bash
docker run -itd --name anylink --privileged \
@ -206,19 +210,19 @@ systemd 脚本放入:
bjdgyc/anylink
```
5. 使用自定义参数启动容器
6. 使用自定义参数启动容器
```bash
# 参数可以参考 -h 命令
docker run -itd --name anylink --privileged \
-e IPV4_CIDR=192.168.10.0/24 \
-p 443:443 -p 8800:8800 \
--restart=always \
bjdgyc/anylink \
# "-c=/etc/server.toml" 参数可以参考 -h 命令
-c=/etc/server.toml --ip_lease = 1209600 \ # IP地址租约时长
```
6. 构建镜像
7. 构建镜像
```bash
#获取仓库源码

View File

@ -25,6 +25,8 @@ echo "编译二进制文件"
cd $cpath/server
rm -rf ui
cp -rf $cpath/web/ui .
#国内可替换源加快速度
export GOPROXY=https://goproxy.io
go build -v -o anylink -ldflags "-X main.CommitId=$(git rev-parse HEAD)"
RETVAL $?

View File

@ -58,7 +58,7 @@ func StartAdmin() {
r.HandleFunc("/debug/pprof/profile", pprof.Profile).Name("debug")
r.HandleFunc("/debug/pprof/symbol", pprof.Symbol).Name("debug")
r.HandleFunc("/debug/pprof/trace", pprof.Trace).Name("debug")
r.HandleFunc("/debug/pprof", location("/debug/pprof/"))
r.HandleFunc("/debug/pprof", location("/debug/pprof/")).Name("debug")
r.PathPrefix("/debug/pprof/").HandlerFunc(pprof.Index).Name("debug")
}

View File

@ -5,8 +5,6 @@ import (
"os"
"path/filepath"
"reflect"
"github.com/spf13/viper"
)
const (
@ -31,7 +29,7 @@ var (
type ServerConfig struct {
// LinkAddr string `json:"link_addr"`
ConfFile string `json:"conf_file"`
Conf string `json:"conf"`
ServerAddr string `json:"server_addr"`
ServerDTLSAddr string `json:"server_dtls_addr"`
ServerDTLS bool `json:"server_dtls"`
@ -83,6 +81,10 @@ func initServerCfg() {
// Cfg.FilesPath = getAbsPath(base, Cfg.FilesPath)
// Cfg.LogPath = getAbsPath(base, Cfg.LogPath)
if Cfg.AdminPass == defaultPwd {
fmt.Fprintln(os.Stderr, "=== 使用默认的admin_pass有安全风险请设置新的admin_pass ===")
}
if Cfg.JwtSecret == defaultJwt {
fmt.Fprintln(os.Stderr, "=== 使用默认的jwt_secret有安全风险请设置新的jwt_secret ===")
}
@ -116,19 +118,18 @@ func initCfg() {
for _, v := range configs {
if v.Name == tag {
if v.Typ == cfgStr {
value.SetString(viper.GetString(v.Name))
value.SetString(linkViper.GetString(v.Name))
}
if v.Typ == cfgInt {
value.SetInt(int64(viper.GetInt(v.Name)))
value.SetInt(int64(linkViper.GetInt(v.Name)))
}
if v.Typ == cfgBool {
value.SetBool(viper.GetBool(v.Name))
value.SetBool(linkViper.GetBool(v.Name))
}
}
}
}
Cfg.ConfFile = cfgFile
initServerCfg()
}
@ -152,9 +153,6 @@ func ServerCfg2Slice() []SCfg {
value := s.Field(i)
tag := field.Tag.Get("json")
usage, env := getUsageEnv(tag)
// if usage == "" {
// continue
// }
datas = append(datas, SCfg{Name: tag, Env: env, Info: usage, Data: value.Interface()})
}

View File

@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"os"
"reflect"
"runtime"
"strings"
@ -15,8 +16,6 @@ import (
var (
// 提交id
CommitId string
// 配置文件
cfgFile string
// pass明文
passwd string
// 生成密钥
@ -29,11 +28,14 @@ var (
// Used for flags.
runSrv bool
rootCmd *cobra.Command
linkViper *viper.Viper
rootCmd *cobra.Command
)
// Execute executes the root command.
func execute() {
initCmd()
err := rootCmd.Execute()
if err != nil {
fmt.Println(err)
@ -41,13 +43,25 @@ func execute() {
}
// viper.Debug()
ref := reflect.ValueOf(linkViper)
s := ref.Elem()
ee := s.FieldByName("env")
if ee.Kind() != reflect.Map {
panic("Viper env is err")
}
rr := ee.MapRange()
for rr.Next() {
// fmt.Println(rr.Key(), rr.Value())
envs[rr.Key().String()] = rr.Value().String()
}
if !runSrv {
os.Exit(0)
}
}
func init() {
func initCmd() {
linkViper = viper.New()
rootCmd = &cobra.Command{
Use: "anylink",
Short: "AnyLink VPN Server",
@ -58,11 +72,9 @@ func init() {
},
}
viper.SetEnvPrefix("link")
linkViper.SetEnvPrefix("link")
// 基础配置
rootCmd.Flags().StringVarP(&cfgFile, "conf", "c", "./conf/server.toml", "config file")
_ = viper.BindEnv("conf")
for _, v := range configs {
if v.Typ == cfgStr {
@ -75,24 +87,25 @@ func init() {
rootCmd.Flags().BoolP(v.Name, v.Short, v.ValBool, v.Usage)
}
_ = viper.BindPFlag(v.Name, rootCmd.Flags().Lookup(v.Name))
_ = viper.BindEnv(v.Name)
_ = linkViper.BindPFlag(v.Name, rootCmd.Flags().Lookup(v.Name))
_ = linkViper.BindEnv(v.Name)
// viper.SetDefault(v.Name, v.Value)
}
rootCmd.AddCommand(initToolCmd())
cobra.OnInitialize(func() {
viper.SetConfigFile(cfgFile)
viper.AutomaticEnv()
linkViper.AutomaticEnv()
conf := linkViper.GetString("conf")
_, err := os.Stat(cfgFile)
_, err := os.Stat(conf)
if errors.Is(err, os.ErrNotExist) {
// 没有配置文件,不做处理
return
}
err = viper.ReadInConfig()
linkViper.SetConfigFile(conf)
err = linkViper.ReadInConfig()
if err != nil {
fmt.Println("Using config file:", err)
}
@ -124,7 +137,7 @@ func initToolCmd() *cobra.Command {
pass, _ := utils.PasswordHash(passwd)
fmt.Printf("Passwd:%s\n", pass)
case debug:
viper.Debug()
linkViper.Debug()
default:
fmt.Println("Using [anylink tool -h] for help")
}

View File

@ -6,6 +6,7 @@ const (
cfgBool
defaultJwt = "abcdef.0123456789.abcdef"
defaultPwd = "$2a$10$UQ7C.EoPifDeJh6d8.31TeSPQU7hM/NOM2nixmBucJpAuXDQNqNke"
)
type config struct {
@ -19,6 +20,7 @@ type config struct {
}
var configs = []config{
{Typ: cfgStr, Name: "conf", Usage: "config file", ValStr: "./conf/server.toml", Short: "c"},
{Typ: cfgStr, Name: "server_addr", Usage: "服务监听地址", ValStr: ":443"},
{Typ: cfgBool, Name: "server_dtls", Usage: "开启DTLS", ValBool: false},
{Typ: cfgStr, Name: "server_dtls_addr", Usage: "DTLS监听地址", ValStr: ":4433"},
@ -34,7 +36,7 @@ var configs = []config{
{Typ: cfgBool, Name: "pprof", Usage: "开启pprof", ValBool: false},
{Typ: cfgStr, Name: "issuer", Usage: "系统名称", ValStr: "XX公司VPN"},
{Typ: cfgStr, Name: "admin_user", Usage: "管理用户名", ValStr: "admin"},
{Typ: cfgStr, Name: "admin_pass", Usage: "管理用户密码", ValStr: "$2a$10$UQ7C.EoPifDeJh6d8.31TeSPQU7hM/NOM2nixmBucJpAuXDQNqNke"},
{Typ: cfgStr, Name: "admin_pass", Usage: "管理用户密码", ValStr: defaultPwd},
{Typ: cfgStr, Name: "jwt_secret", Usage: "JWT密钥", ValStr: defaultJwt},
{Typ: cfgStr, Name: "link_mode", Usage: "虚拟网络类型", ValStr: "tun"},
{Typ: cfgStr, Name: "ipv4_cidr", Usage: "ip地址网段", ValStr: "192.168.10.0/24"},

View File

@ -1,4 +1,4 @@
#服务配置信息
#示例配置信息
#其他配置文件,可以使用绝对路径
#或者相对于 anylink 二进制文件的路径

View File

@ -34,9 +34,8 @@ func LinkCstp(conn net.Conn, cSess *sessdata.ConnSession) {
return
}
// hdata := make([]byte, BufferSize)
hb := getByteFull()
hdata := *hb
n, err = conn.Read(hdata)
pl := getPayload()
n, err = conn.Read(pl.Data)
if err != nil {
base.Error("read hdata: ", err)
return
@ -48,7 +47,7 @@ func LinkCstp(conn net.Conn, cSess *sessdata.ConnSession) {
base.Error(err)
}
switch hdata[6] {
switch pl.Data[6] {
case 0x07: // KEEPALIVE
// do nothing
// base.Debug("recv keepalive", cSess.IpAddr)
@ -57,19 +56,24 @@ func LinkCstp(conn net.Conn, cSess *sessdata.ConnSession) {
return
case 0x03: // DPD-REQ
// base.Debug("recv DPD-REQ", cSess.IpAddr)
if payloadOutCstp(cSess, sessdata.LTypeIPData, 0x04, nil) {
pl.PType = 0x04
if payloadOutCstp(cSess, pl) {
return
}
case 0x04:
// log.Println("recv DPD-RESP")
case 0x00: // DATA
dataLen = binary.BigEndian.Uint16(hdata[4:6]) // 4,5
if payloadIn(cSess, sessdata.LTypeIPData, 0x00, hdata[8:8+dataLen]) {
// 获取数据长度
dataLen = binary.BigEndian.Uint16(pl.Data[4:6]) // 4,5
// 去除数据头
copy(pl.Data, pl.Data[8:8+dataLen])
// 更新切片长度
pl.Data = pl.Data[:dataLen]
// pl.Data = append(pl.Data[:0], pl.Data[8:8+dataLen]...)
if payloadIn(cSess, pl) {
return
}
}
putByte(hb)
}
}
@ -83,38 +87,44 @@ func cstpWrite(conn net.Conn, cSess *sessdata.ConnSession) {
var (
err error
n int
// header []byte
payload *sessdata.Payload
pl *sessdata.Payload
)
for {
select {
case payload = <-cSess.PayloadOutCstp:
case pl = <-cSess.PayloadOutCstp:
case <-cSess.CloseChan:
return
}
if payload.LType != sessdata.LTypeIPData {
if pl.LType != sessdata.LTypeIPData {
continue
}
h := []byte{'S', 'T', 'F', 0x01, 0x00, 0x00, payload.PType, 0x00}
hb := getByteZero()
header := *hb
header = append(header, h...)
if payload.PType == 0x00 {
data := *payload.Data
binary.BigEndian.PutUint16(header[4:6], uint16(len(data)))
header = append(header, data...)
if pl.PType == 0x00 {
// 获取数据长度
l := len(pl.Data)
// 先扩容 +8
pl.Data = pl.Data[:l+8]
// 数据后移
copy(pl.Data[8:], pl.Data)
// 添加头信息
copy(pl.Data[:8], plHeader)
// 更新头长度
binary.BigEndian.PutUint16(pl.Data[4:6], uint16(l))
} else {
pl.Data = append(pl.Data[:0], plHeader...)
// 设置头类型
pl.Data[6] = pl.PType
}
n, err = conn.Write(header)
n, err = conn.Write(pl.Data)
if err != nil {
base.Error("write err", err)
return
}
putByte(hb)
putPayload(payload)
putPayload(pl)
// 限流设置
err = cSess.RateLimit(n, false)

View File

@ -24,21 +24,22 @@ func LinkDtls(conn net.Conn, cSess *sessdata.ConnSession) {
}()
var (
err error
n int
dead = time.Duration(cSess.CstpDpd+5) * time.Second
)
go dtlsWrite(conn, dSess, cSess)
for {
err := conn.SetReadDeadline(time.Now().Add(dead))
err = conn.SetReadDeadline(time.Now().Add(dead))
if err != nil {
base.Error("SetDeadline: ", err)
return
}
hb := getByteFull()
hdata := *hb
n, err := conn.Read(hdata)
pl := getPayload()
n, err = conn.Read(pl.Data)
if err != nil {
base.Error("read hdata: ", err)
return
@ -50,7 +51,7 @@ func LinkDtls(conn net.Conn, cSess *sessdata.ConnSession) {
base.Error(err)
}
switch hdata[0] {
switch pl.Data[0] {
case 0x07: // KEEPALIVE
// do nothing
// base.Debug("recv keepalive", cSess.IpAddr)
@ -59,18 +60,23 @@ func LinkDtls(conn net.Conn, cSess *sessdata.ConnSession) {
return
case 0x03: // DPD-REQ
// base.Debug("recv DPD-REQ", cSess.IpAddr)
if payloadOutDtls(cSess, dSess, sessdata.LTypeIPData, 0x04, nil) {
pl.PType = 0x04
if payloadOutDtls(cSess, dSess, pl) {
return
}
case 0x04:
// base.Debug("recv DPD-RESP", cSess.IpAddr)
case 0x00: // DATA
if payloadIn(cSess, sessdata.LTypeIPData, 0x00, hdata[1:n]) {
// 去除数据头
// copy(pl.Data, pl.Data[1:n])
// 更新切片长度
// pl.Data = pl.Data[:n-1]
pl.Data = append(pl.Data[:0], pl.Data[1:n]...)
if payloadIn(cSess, pl) {
return
}
}
putByte(hb)
}
}
@ -82,37 +88,42 @@ func dtlsWrite(conn net.Conn, dSess *sessdata.DtlsSession, cSess *sessdata.ConnS
}()
var (
// header []byte
payload *sessdata.Payload
pl *sessdata.Payload
)
for {
// dtls优先推送数据
select {
case payload = <-cSess.PayloadOutDtls:
case pl = <-cSess.PayloadOutDtls:
case <-dSess.CloseChan:
return
}
if payload.LType != sessdata.LTypeIPData {
if pl.LType != sessdata.LTypeIPData {
continue
}
// header = []byte{payload.PType}
hb := getByteZero()
header := *hb
header = append(header, payload.PType)
if payload.PType == 0x00 { // data
header = append(header, *payload.Data...)
if pl.PType == 0x00 { // data
// 获取数据长度
l := len(pl.Data)
// 先扩容 +1
pl.Data = pl.Data[:l+1]
// 数据后移
copy(pl.Data[1:], pl.Data)
// 添加头信息
pl.Data[0] = pl.PType
} else {
// 设置头类型
pl.Data = append(pl.Data[:0], pl.PType)
}
n, err := conn.Write(header)
n, err := conn.Write(pl.Data)
if err != nil {
base.Error("write err", err)
return
}
putByte(hb)
putPayload(payload)
putPayload(pl)
// 限流设置
err = cSess.RateLimit(n, false)

View File

@ -88,14 +88,14 @@ func tapWrite(ifce *water.Interface, cSess *sessdata.ConnSession) {
}()
var (
err error
payload *sessdata.Payload
frame ethernet.Frame
err error
pl *sessdata.Payload
frame ethernet.Frame
)
for {
select {
case payload = <-cSess.PayloadIn:
case pl = <-cSess.PayloadIn:
case <-cSess.CloseChan:
return
}
@ -103,16 +103,15 @@ func tapWrite(ifce *water.Interface, cSess *sessdata.ConnSession) {
// var frame ethernet.Frame
fb := getByteFull()
frame = *fb
pData := *payload.Data
switch payload.LType {
switch pl.LType {
default:
// log.Println(payload)
case sessdata.LTypeEthernet:
copy(frame, pData)
frame = frame[:len(pData)]
copy(frame, pl.Data)
frame = frame[:len(pl.Data)]
case sessdata.LTypeIPData: // 需要转换成 Ethernet 数据
ip_src := waterutil.IPv4Source(pData)
if waterutil.IsIPv6(pData) || !ip_src.Equal(cSess.IpAddr) {
ip_src := waterutil.IPv4Source(pl.Data)
if waterutil.IsIPv6(pl.Data) || !ip_src.Equal(cSess.IpAddr) {
// 过滤掉IPv6的数据
// 非分配给客户端ip直接丢弃
continue
@ -121,7 +120,7 @@ func tapWrite(ifce *water.Interface, cSess *sessdata.ConnSession) {
// packet := gopacket.NewPacket(data, layers.LayerTypeIPv4, gopacket.Default)
// fmt.Println("get:", packet)
ip_dst := waterutil.IPv4Destination(pData)
ip_dst := waterutil.IPv4Destination(pl.Data)
// fmt.Println("get:", ip_src, ip_dst)
var dstHw net.HardwareAddr
@ -141,8 +140,8 @@ func tapWrite(ifce *water.Interface, cSess *sessdata.ConnSession) {
}
// fmt.Println("Gateway", ip_dst, dstAddr.HardwareAddr)
frame.Prepare(dstHw, cSess.MacHw, ethernet.NotTagged, ethernet.IPv4, len(pData))
copy(frame[12+2:], pData)
frame.Prepare(dstHw, cSess.MacHw, ethernet.NotTagged, ethernet.IPv4, len(pl.Data))
copy(frame[12+2:], pl.Data)
}
// packet := gopacket.NewPacket(frame, layers.LayerTypeEthernet, gopacket.Default)
@ -154,7 +153,7 @@ func tapWrite(ifce *water.Interface, cSess *sessdata.ConnSession) {
}
putByte(fb)
putPayload(payload)
putPayload(pl)
}
}
@ -167,7 +166,7 @@ func tapRead(ifce *water.Interface, cSess *sessdata.ConnSession) {
var (
err error
n int
buf []byte
data []byte
frame ethernet.Frame
)
@ -192,7 +191,7 @@ func tapRead(ifce *water.Interface, cSess *sessdata.ConnSession) {
continue
case ethernet.IPv4:
// 发送IP数据
data := frame.Payload()
data = frame.Payload()
ip_dst := waterutil.IPv4Destination(data)
if !ip_dst.Equal(cSess.IpAddr) {
@ -204,7 +203,12 @@ func tapRead(ifce *water.Interface, cSess *sessdata.ConnSession) {
// packet := gopacket.NewPacket(data, layers.LayerTypeIPv4, gopacket.Default)
// fmt.Println("put:", packet)
if payloadOut(cSess, sessdata.LTypeIPData, 0x00, data) {
pl := getPayload()
// 拷贝数据到pl
copy(pl.Data, data)
// 更新切片长度
pl.Data = pl.Data[:len(data)]
if payloadOut(cSess, pl) {
return
}
@ -225,7 +229,7 @@ func tapRead(ifce *water.Interface, cSess *sessdata.ConnSession) {
// 返回ARP数据
src := &arpdis.Addr{IP: cSess.IpAddr, HardwareAddr: cSess.MacHw}
dst := &arpdis.Addr{IP: arpReq.SourceProtAddress, HardwareAddr: frame.Source()}
buf, err = arpdis.NewARPReply(src, dst)
data, err = arpdis.NewARPReply(src, dst)
if err != nil {
base.Error(err)
return
@ -242,7 +246,15 @@ func tapRead(ifce *water.Interface, cSess *sessdata.ConnSession) {
copy(addr.HardwareAddr, frame.Source())
arpdis.Add(addr)
if payloadIn(cSess, sessdata.LTypeEthernet, 0x00, buf) {
pl := getPayload()
// 设置为二层数据类型
pl.LType = sessdata.LTypeEthernet
// 拷贝数据到pl
copy(pl.Data, data)
// 更新切片长度
pl.Data = pl.Data[:len(data)]
if payloadIn(cSess, pl) {
return
}

View File

@ -69,24 +69,24 @@ func tunWrite(ifce *water.Interface, cSess *sessdata.ConnSession) {
}()
var (
err error
payload *sessdata.Payload
err error
pl *sessdata.Payload
)
for {
select {
case payload = <-cSess.PayloadIn:
case pl = <-cSess.PayloadIn:
case <-cSess.CloseChan:
return
}
_, err = ifce.Write(*payload.Data)
_, err = ifce.Write(pl.Data)
if err != nil {
base.Error("tun Write err", err)
return
}
putPayload(payload)
putPayload(pl)
}
}
@ -102,14 +102,16 @@ func tunRead(ifce *water.Interface, cSess *sessdata.ConnSession) {
for {
// data := make([]byte, BufferSize)
hb := getByteFull()
data := *hb
n, err = ifce.Read(data)
pl := getPayload()
n, err = ifce.Read(pl.Data)
if err != nil {
base.Error("tun Read err", n, err)
return
}
// 更新数据长度
pl.Data = (pl.Data)[:n]
// data = data[:n]
// ip_src := waterutil.IPv4Source(data)
// ip_dst := waterutil.IPv4Destination(data)
@ -118,10 +120,8 @@ func tunRead(ifce *water.Interface, cSess *sessdata.ConnSession) {
// packet := gopacket.NewPacket(data, layers.LayerTypeIPv4, gopacket.Default)
// fmt.Println("read:", packet)
if payloadOut(cSess, sessdata.LTypeIPData, 0x00, data[:n]) {
if payloadOut(cSess, pl) {
return
}
putByte(hb)
}
}

View File

@ -6,18 +6,9 @@ import (
"github.com/songgao/water/waterutil"
)
func payloadIn(cSess *sessdata.ConnSession, lType sessdata.LType, pType byte, data []byte) bool {
pl := getPayload()
pl.LType = lType
pl.PType = pType
*pl.Data = append(*pl.Data, data...)
return payloadInData(cSess, pl)
}
func payloadInData(cSess *sessdata.ConnSession, payload *sessdata.Payload) bool {
func payloadIn(cSess *sessdata.ConnSession, pl *sessdata.Payload) bool {
// 进行Acl规则判断
check := checkLinkAcl(cSess.Group, payload)
check := checkLinkAcl(cSess.Group, pl)
if !check {
// 校验不通过直接丢弃
return false
@ -25,7 +16,7 @@ func payloadInData(cSess *sessdata.ConnSession, payload *sessdata.Payload) bool
closed := false
select {
case cSess.PayloadIn <- payload:
case cSess.PayloadIn <- pl:
case <-cSess.CloseChan:
closed = true
}
@ -33,21 +24,16 @@ func payloadInData(cSess *sessdata.ConnSession, payload *sessdata.Payload) bool
return closed
}
func payloadOut(cSess *sessdata.ConnSession, lType sessdata.LType, pType byte, data []byte) bool {
func payloadOut(cSess *sessdata.ConnSession, pl *sessdata.Payload) bool {
dSess := cSess.GetDtlsSession()
if dSess == nil {
return payloadOutCstp(cSess, lType, pType, data)
return payloadOutCstp(cSess, pl)
} else {
return payloadOutDtls(cSess, dSess, lType, pType, data)
return payloadOutDtls(cSess, dSess, pl)
}
}
func payloadOutCstp(cSess *sessdata.ConnSession, lType sessdata.LType, pType byte, data []byte) bool {
pl := getPayload()
pl.LType = lType
pl.PType = pType
*pl.Data = append(*pl.Data, data...)
func payloadOutCstp(cSess *sessdata.ConnSession, pl *sessdata.Payload) bool {
closed := false
select {
@ -59,12 +45,7 @@ func payloadOutCstp(cSess *sessdata.ConnSession, lType sessdata.LType, pType byt
return closed
}
func payloadOutDtls(cSess *sessdata.ConnSession, dSess *sessdata.DtlsSession, lType sessdata.LType, pType byte, data []byte) bool {
pl := getPayload()
pl.LType = lType
pl.PType = pType
*pl.Data = append(*pl.Data, data...)
func payloadOutDtls(cSess *sessdata.ConnSession, dSess *sessdata.DtlsSession, pl *sessdata.Payload) bool {
select {
case cSess.PayloadOutDtls <- pl:
case <-dSess.CloseChan:
@ -74,13 +55,13 @@ func payloadOutDtls(cSess *sessdata.ConnSession, dSess *sessdata.DtlsSession, lT
}
// Acl规则校验
func checkLinkAcl(group *dbdata.Group, payload *sessdata.Payload) bool {
if payload.LType == sessdata.LTypeIPData && payload.PType == 0x00 && len(group.LinkAcl) > 0 {
func checkLinkAcl(group *dbdata.Group, pl *sessdata.Payload) bool {
if pl.LType == sessdata.LTypeIPData && pl.PType == 0x00 && len(group.LinkAcl) > 0 {
} else {
return true
}
data := *payload.Data
data := pl.Data
ip_dst := waterutil.IPv4Destination(data)
ip_port := waterutil.IPv4DestinationPort(data)
ip_proto := waterutil.IPv4Protocol(data)

View File

@ -3,14 +3,21 @@ package handler
import (
"sync"
"github.com/bjdgyc/anylink/base"
"github.com/bjdgyc/anylink/sessdata"
)
// 不允许直接修改
// [6] => PType
var plHeader = []byte{'S', 'T', 'F', 0x01, 0x00, 0x00, 0x00, 0x00}
var plPool = sync.Pool{
New: func() interface{} {
b := make([]byte, 0, BufferSize)
b := make([]byte, BufferSize)
pl := sessdata.Payload{
Data: &b,
LType: sessdata.LTypeIPData,
PType: 0x00,
Data: b,
}
// fmt.Println("plPool-init", len(pl.Data), cap(pl.Data))
return &pl
@ -23,15 +30,21 @@ func getPayload() *sessdata.Payload {
}
func putPayload(pl *sessdata.Payload) {
pl.LType = 0
pl.PType = 0
*pl.Data = (*pl.Data)[:0]
// 错误数据丢弃
if cap(pl.Data) != BufferSize {
base.Warn("payload cap is err", cap(pl.Data))
return
}
pl.LType = sessdata.LTypeIPData
pl.PType = 0x00
pl.Data = pl.Data[:BufferSize]
plPool.Put(pl)
}
var bytePool = sync.Pool{
New: func() interface{} {
b := make([]byte, 0, BufferSize)
b := make([]byte, BufferSize)
// fmt.Println("bytePool-init")
return &b
},
@ -39,15 +52,15 @@ var bytePool = sync.Pool{
func getByteZero() *[]byte {
b := bytePool.Get().(*[]byte)
*b = (*b)[:0]
return b
}
func getByteFull() *[]byte {
b := bytePool.Get().(*[]byte)
*b = (*b)[:BufferSize]
return b
}
func putByte(b *[]byte) {
*b = (*b)[:0]
*b = (*b)[:BufferSize]
bytePool.Put(b)
}

View File

@ -0,0 +1,44 @@
package handler
import (
"testing"
)
// go test -bench=. -benchmem
// 去除数据头
func BenchmarkHeaderCopy(b *testing.B) {
l := 1500
for i := 0; i < b.N; i++ {
b.StopTimer()
pl := getPayload()
// 初始化数据
pl.Data = pl.Data[:l]
b.StartTimer()
dataLen := l - 8
copy(pl.Data, pl.Data[8:8+dataLen])
// 更新切片长度
pl.Data = pl.Data[:dataLen]
b.StopTimer()
putPayload(pl)
}
}
func BenchmarkHeaderAppend(b *testing.B) {
l := 1500
for i := 0; i < b.N; i++ {
b.StopTimer()
pl := getPayload()
// 初始化数据
pl.Data = pl.Data[:l]
b.StartTimer()
dataLen := l - 8
pl.Data = append(pl.Data[:0], pl.Data[:8+dataLen]...)
b.StopTimer()
putPayload(pl)
}
}

View File

@ -8,9 +8,9 @@ const (
)
type Payload struct {
PType byte // payload types
LType LType // LinkType
Data *[]byte
PType byte // payload types
Data []byte
}
/*

13976
web/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -181,18 +181,20 @@
<el-col :span="4">
<el-button size="mini" type="success" icon="el-icon-plus" circle
@click.prevent="addDomain(ruleForm.client_dns)"></el-button>
<el-button size="mini" type="danger" icon="el-icon-minus" circle
@click.prevent="removeDomain(ruleForm.client_dns)"></el-button>
</el-col>
</el-row>
<el-row v-for="(item,index) in ruleForm.client_dns"
:key="index" style="margin-bottom: 5px" gutter="10">
:key="index" style="margin-bottom: 5px" :gutter="10">
<el-col :span="10">
<el-input v-model="item.val"></el-input>
</el-col>
<el-col :span="14">
<el-col :span="12">
<el-input v-model="item.note" placeholder="备注"></el-input>
</el-col>
<el-col :span="2">
<el-button size="mini" type="danger" icon="el-icon-minus" circle
@click.prevent="removeDomain(ruleForm.client_dns,index)"></el-button>
</el-col>
</el-row>
</el-form-item>
@ -202,18 +204,20 @@
<el-col :span="4">
<el-button size="mini" type="success" icon="el-icon-plus" circle
@click.prevent="addDomain(ruleForm.route_include)"></el-button>
<el-button size="mini" type="danger" icon="el-icon-minus" circle
@click.prevent="removeDomain(ruleForm.route_include)"></el-button>
</el-col>
</el-row>
<el-row v-for="(item,index) in ruleForm.route_include"
:key="index" style="margin-bottom: 5px" gutter="10">
:key="index" style="margin-bottom: 5px" :gutter="10">
<el-col :span="10">
<el-input v-model="item.val"></el-input>
</el-col>
<el-col :span="14">
<el-col :span="12">
<el-input v-model="item.note" placeholder="备注"></el-input>
</el-col>
<el-col :span="2">
<el-button size="mini" type="danger" icon="el-icon-minus" circle
@click.prevent="removeDomain(ruleForm.route_include,index)"></el-button>
</el-col>
</el-row>
</el-form-item>
@ -223,18 +227,20 @@
<el-col :span="4">
<el-button size="mini" type="success" icon="el-icon-plus" circle
@click.prevent="addDomain(ruleForm.route_exclude)"></el-button>
<el-button size="mini" type="danger" icon="el-icon-minus" circle
@click.prevent="removeDomain(ruleForm.route_exclude)"></el-button>
</el-col>
</el-row>
<el-row v-for="(item,index) in ruleForm.route_exclude"
:key="index" style="margin-bottom: 5px" gutter="10">
:key="index" style="margin-bottom: 5px" :gutter="10">
<el-col :span="10">
<el-input v-model="item.val"></el-input>
</el-col>
<el-col :span="14">
<el-col :span="12">
<el-input v-model="item.note" placeholder="备注"></el-input>
</el-col>
<el-col :span="2">
<el-button size="mini" type="danger" icon="el-icon-minus" circle
@click.prevent="removeDomain(ruleForm.route_exclude,index)"></el-button>
</el-col>
</el-row>
</el-form-item>
@ -244,13 +250,11 @@
<el-col :span="4">
<el-button size="mini" type="success" icon="el-icon-plus" circle
@click.prevent="addDomain(ruleForm.link_acl)"></el-button>
<el-button size="mini" type="danger" icon="el-icon-minus" circle
@click.prevent="removeDomain(ruleForm.link_acl)"></el-button>
</el-col>
</el-row>
<el-row v-for="(item,index) in ruleForm.link_acl"
:key="index" style="margin-bottom: 5px" gutter="5">
:key="index" style="margin-bottom: 5px" :gutter="5">
<el-col :span="11">
<el-input placeholder="请输入CIDR地址" v-model="item.val">
<el-select v-model="item.action" slot="prepend">
@ -262,9 +266,13 @@
<el-col :span="3">
<el-input v-model.number="item.port" placeholder="端口"></el-input>
</el-col>
<el-col :span="10">
<el-col :span="8">
<el-input v-model="item.note" placeholder="备注"></el-input>
</el-col>
<el-col :span="2">
<el-button size="mini" type="danger" icon="el-icon-minus" circle
@click.prevent="removeDomain(ruleForm.link_acl,index)"></el-button>
</el-col>
</el-row>
</el-form-item>
@ -389,13 +397,16 @@ export default {
console.log(error);
});
},
removeDomain(arr, item) {
console.log(item)
removeDomain(arr, index) {
console.log(index)
if (index >= 0 && index < arr.length) {
arr.splice(index, 1)
}
// let index = arr.indexOf(item);
// if (index !== -1 && arr.length > 1) {
// arr.splice(index, 1)
// }
arr.pop()
// arr.pop()
},
addDomain(arr) {
arr.push({val: "", action: "allow", port: 0});