Compare commits
112 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
df31921954 | ||
|
|
299abb7b04 | ||
|
|
85ce63b4d3 | ||
|
|
9d9ae288bd | ||
|
|
c0a35eb5e7 | ||
|
|
d1d0ff062b | ||
|
|
396e8a22c4 | ||
|
|
4f040db1ef | ||
|
|
e3cf111344 | ||
|
|
28cb3c383d | ||
|
|
10665c0f37 | ||
|
|
4096f11909 | ||
|
|
5df209b6d5 | ||
|
|
db353fe025 | ||
|
|
30c3e143b8 | ||
|
|
15fe7b33a4 | ||
|
|
17e0666ba4 | ||
|
|
3f24bfaaf5 | ||
|
|
ceadcfece9 | ||
|
|
bc706237ef | ||
|
|
b8c5a78f2e | ||
|
|
9ad1c3a3c8 | ||
|
|
8cfde43f5d | ||
|
|
6f843b071a | ||
|
|
a72b025900 | ||
|
|
dfb66775d7 | ||
|
|
c4dca2df30 | ||
|
|
a3525bdaa4 | ||
|
|
09390bbb97 | ||
|
|
70ae4391d7 | ||
|
|
85931f55e1 | ||
|
|
0f5f03c9ed | ||
|
|
1181a0585b | ||
|
|
fd6fa929de | ||
|
|
73888c98a8 | ||
|
|
04ebfbea8a | ||
|
|
2b650fd285 | ||
|
|
515a590681 | ||
|
|
62f9d1f09a | ||
|
|
25c11f3d69 | ||
|
|
fde18c3b82 | ||
|
|
23a4b64e6d | ||
|
|
46a82f5988 | ||
|
|
1f37816a3a | ||
|
|
2301e74b1c | ||
|
|
a47d7d275c | ||
|
|
706519ac2e | ||
|
|
b8e193bc60 | ||
|
|
e44f9cc2fb | ||
|
|
c6823ae3a8 | ||
|
|
a18ebc0060 | ||
|
|
7cf41ace47 | ||
|
|
987350f0b4 | ||
|
|
ce7dda8cf5 | ||
|
|
af87cc9f16 | ||
|
|
d5f6acf690 | ||
|
|
92f541b0aa | ||
|
|
fb6fee8c60 | ||
|
|
75fe0bd8c6 | ||
|
|
8f1f5f5bb4 | ||
|
|
9fe6bc2dcc | ||
|
|
b254cfc1a7 | ||
|
|
f8e155887f | ||
|
|
c5a635d796 | ||
|
|
607fa58ece | ||
|
|
0d5540295f | ||
|
|
9ce516caeb | ||
|
|
77bb1cf14e | ||
|
|
274284dbe1 | ||
|
|
cd6d7221e8 | ||
|
|
b1d0c8852e | ||
|
|
4c4033bb56 | ||
|
|
6d642b75f6 | ||
|
|
eb47e3a08c | ||
|
|
d82d16e28d | ||
|
|
b2fc785543 | ||
|
|
189e3342ce | ||
|
|
885defbf31 | ||
|
|
74f1bf330d | ||
|
|
ad843d9d10 | ||
|
|
13e718742d | ||
|
|
771eff8fb1 | ||
|
|
20d7e0b1bf | ||
|
|
e6c7bbec06 | ||
|
|
be61ef89fe | ||
|
|
3d7d8f1e63 | ||
|
|
a4fb465a19 | ||
|
|
96c725c13d | ||
|
|
7635def2fa | ||
|
|
b704a73338 | ||
|
|
123b5f5969 | ||
|
|
eea2037444 | ||
|
|
4e6d2fa5ea | ||
|
|
14bb131e8d | ||
|
|
31814bb54c | ||
|
|
49b8fd6e97 | ||
|
|
a9d31a2e35 | ||
|
|
298cef7f05 | ||
|
|
9bdd9a433c | ||
|
|
45620dcdb7 | ||
|
|
84a5d38b0b | ||
|
|
e812b3fcf6 | ||
|
|
1bd16fa1d3 | ||
|
|
f3ea4957be | ||
|
|
04da107c94 | ||
|
|
e77de69a15 | ||
|
|
e88eda56f5 | ||
|
|
d6ceccc52e | ||
|
|
cd948ac68c | ||
|
|
9eac8afa3d | ||
|
|
fb3610966a | ||
|
|
a6673449db |
29
LICENSE
Normal file
29
LICENSE
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
BSD 3-Clause License
|
||||||
|
|
||||||
|
Copyright (c) 2020, LiuXiangChao
|
||||||
|
All rights reserved.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without
|
||||||
|
modification, are permitted provided that the following conditions are met:
|
||||||
|
|
||||||
|
1. Redistributions of source code must retain the above copyright notice, this
|
||||||
|
list of conditions and the following disclaimer.
|
||||||
|
|
||||||
|
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||||
|
this list of conditions and the following disclaimer in the documentation
|
||||||
|
and/or other materials provided with the distribution.
|
||||||
|
|
||||||
|
3. Neither the name of the copyright holder nor the names of its
|
||||||
|
contributors may be used to endorse or promote products derived from
|
||||||
|
this software without specific prior written permission.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||||
|
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||||
|
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||||
|
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||||
|
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||||
|
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||||
|
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||||
|
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||||
|
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
function build() {
|
function build() {
|
||||||
ROOT=$(dirname $0)
|
ROOT=$(dirname $0)
|
||||||
NAME="edge-node"
|
NAME="edge-node"
|
||||||
VERSION=$(lookup-version $ROOT/../internal/const/const.go)
|
VERSION=$(lookup-version "$ROOT"/../internal/const/const.go)
|
||||||
DIST=$ROOT/"../dist/${NAME}"
|
DIST=$ROOT/"../dist/${NAME}"
|
||||||
MUSL_DIR="/usr/local/opt/musl-cross/bin"
|
MUSL_DIR="/usr/local/opt/musl-cross/bin"
|
||||||
GCC_X86_64_DIR="/usr/local/Cellar/x86_64-unknown-linux-gnu/10.3.0/bin"
|
GCC_X86_64_DIR="/usr/local/Cellar/x86_64-unknown-linux-gnu/10.3.0/bin"
|
||||||
@@ -13,21 +13,21 @@ function build() {
|
|||||||
ARCH=${2}
|
ARCH=${2}
|
||||||
TAG=${3}
|
TAG=${3}
|
||||||
|
|
||||||
if [ -z $OS ]; then
|
if [ -z "$OS" ]; then
|
||||||
echo "usage: build.sh OS ARCH"
|
echo "usage: build.sh OS ARCH"
|
||||||
exit
|
exit
|
||||||
fi
|
fi
|
||||||
if [ -z $ARCH ]; then
|
if [ -z "$ARCH" ]; then
|
||||||
echo "usage: build.sh OS ARCH"
|
echo "usage: build.sh OS ARCH"
|
||||||
exit
|
exit
|
||||||
fi
|
fi
|
||||||
if [ -z $TAG ]; then
|
if [ -z "$TAG" ]; then
|
||||||
TAG="community"
|
TAG="community"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "checking ..."
|
echo "checking ..."
|
||||||
ZIP_PATH=$(which zip)
|
ZIP_PATH=$(which zip)
|
||||||
if [ -z $ZIP_PATH ]; then
|
if [ -z "$ZIP_PATH" ]; then
|
||||||
echo "we need 'zip' command to compress files"
|
echo "we need 'zip' command to compress files"
|
||||||
exit
|
exit
|
||||||
fi
|
fi
|
||||||
@@ -36,28 +36,28 @@ function build() {
|
|||||||
ZIP="${NAME}-${OS}-${ARCH}-${TAG}-v${VERSION}.zip"
|
ZIP="${NAME}-${OS}-${ARCH}-${TAG}-v${VERSION}.zip"
|
||||||
|
|
||||||
echo "copying ..."
|
echo "copying ..."
|
||||||
if [ ! -d $DIST ]; then
|
if [ ! -d "$DIST" ]; then
|
||||||
mkdir $DIST
|
mkdir "$DIST"
|
||||||
mkdir $DIST/bin
|
mkdir "$DIST"/bin
|
||||||
mkdir $DIST/configs
|
mkdir "$DIST"/configs
|
||||||
mkdir $DIST/logs
|
mkdir "$DIST"/logs
|
||||||
mkdir $DIST/data
|
mkdir "$DIST"/data
|
||||||
|
|
||||||
if [ "$TAG" = "plus" ]; then
|
if [ "$TAG" = "plus" ]; then
|
||||||
mkdir $DIST/scripts
|
mkdir "$DIST"/scripts
|
||||||
mkdir $DIST/scripts/js
|
mkdir "$DIST"/scripts/js
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
cp $ROOT/configs/api.template.yaml $DIST/configs
|
cp "$ROOT"/configs/api.template.yaml "$DIST"/configs
|
||||||
cp -R $ROOT/www $DIST/
|
cp -R "$ROOT"/www "$DIST"/
|
||||||
cp -R $ROOT/pages $DIST/
|
cp -R "$ROOT"/pages "$DIST"/
|
||||||
cp -R $ROOT/resources $DIST/
|
cp -R "$ROOT"/resources "$DIST"/
|
||||||
|
|
||||||
# we support TOA on linux/amd64 only
|
# we support TOA on linux/amd64 only
|
||||||
if [ $OS == "linux" -a $ARCH == "amd64" ]
|
if [ "$OS" == "linux" -a "$ARCH" == "amd64" ]
|
||||||
then
|
then
|
||||||
cp -R $ROOT/edge-toa $DIST
|
cp -R "$ROOT"/edge-toa "$DIST"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "building ..."
|
echo "building ..."
|
||||||
@@ -112,14 +112,14 @@ function build() {
|
|||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
if [ ! -z $CC_PATH ]; then
|
if [ ! -z $CC_PATH ]; then
|
||||||
env CC=$MUSL_DIR/$CC_PATH CXX=$MUSL_DIR/$CXX_PATH GOOS=${OS} GOARCH=${ARCH} CGO_ENABLED=1 go build -tags $BUILD_TAG -o $DIST/bin/${NAME} -ldflags "-linkmode external -extldflags -static -s -w" $ROOT/../cmd/edge-node/main.go
|
env CC=$MUSL_DIR/$CC_PATH CXX=$MUSL_DIR/$CXX_PATH GOOS="${OS}" GOARCH="${ARCH}" CGO_ENABLED=1 go build -trimpath -tags $BUILD_TAG -o "$DIST"/bin/${NAME} -ldflags "-linkmode external -extldflags -static -s -w" "$ROOT"/../cmd/edge-node/main.go
|
||||||
else
|
else
|
||||||
env GOOS=${OS} GOARCH=${ARCH} CGO_ENABLED=1 go build -tags $TAG -o $DIST/bin/${NAME} -ldflags="-s -w" $ROOT/../cmd/edge-node/main.go
|
env GOOS="${OS}" GOARCH="${ARCH}" CGO_ENABLED=1 go build -trimpath -tags $TAG -o "$DIST"/bin/${NAME} -ldflags="-s -w" "$ROOT"/../cmd/edge-node/main.go
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# delete hidden files
|
# delete hidden files
|
||||||
find $DIST -name ".DS_Store" -delete
|
find "$DIST" -name ".DS_Store" -delete
|
||||||
find $DIST -name ".gitignore" -delete
|
find "$DIST" -name ".gitignore" -delete
|
||||||
|
|
||||||
echo "zip files"
|
echo "zip files"
|
||||||
cd "${DIST}/../" || exit
|
cd "${DIST}/../" || exit
|
||||||
@@ -135,15 +135,15 @@ function build() {
|
|||||||
|
|
||||||
function lookup-version() {
|
function lookup-version() {
|
||||||
FILE=$1
|
FILE=$1
|
||||||
VERSION_DATA=$(cat $FILE)
|
VERSION_DATA=$(cat "$FILE")
|
||||||
re="Version[ ]+=[ ]+\"([0-9.]+)\""
|
re="Version[ ]+=[ ]+\"([0-9.]+)\""
|
||||||
if [[ $VERSION_DATA =~ $re ]]; then
|
if [[ $VERSION_DATA =~ $re ]]; then
|
||||||
VERSION=${BASH_REMATCH[1]}
|
VERSION=${BASH_REMATCH[1]}
|
||||||
echo $VERSION
|
echo "$VERSION"
|
||||||
else
|
else
|
||||||
echo "could not match version"
|
echo "could not match version"
|
||||||
exit
|
exit
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
build $1 $2 $3
|
build "$1" "$2" "$3"
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/apps"
|
"github.com/TeaOSLab/EdgeNode/internal/apps"
|
||||||
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
||||||
@@ -19,10 +20,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
app := apps.NewAppCmd().
|
var app = apps.NewAppCmd().
|
||||||
Version(teaconst.Version).
|
Version(teaconst.Version).
|
||||||
Product(teaconst.ProductName).
|
Product(teaconst.ProductName).
|
||||||
Usage(teaconst.ProcessName + " [-v|start|stop|restart|status|quit|test|reload|service|daemon|pprof]").
|
Usage(teaconst.ProcessName + " [-v|start|stop|restart|status|quit|test|reload|service|daemon|pprof|accesslog]").
|
||||||
Usage(teaconst.ProcessName + " [trackers|goman|conns|gc]").
|
Usage(teaconst.ProcessName + " [trackers|goman|conns|gc]").
|
||||||
Usage(teaconst.ProcessName + " [ip.drop|ip.reject|ip.remove] IP")
|
Usage(teaconst.ProcessName + " [ip.drop|ip.reject|ip.remove] IP")
|
||||||
|
|
||||||
@@ -67,24 +68,30 @@ func main() {
|
|||||||
fmt.Println("done")
|
fmt.Println("done")
|
||||||
})
|
})
|
||||||
app.On("pprof", func() {
|
app.On("pprof", func() {
|
||||||
// TODO 自己指定端口
|
var flagSet = flag.NewFlagSet("pprof", flag.ExitOnError)
|
||||||
addr := "127.0.0.1:6060"
|
var addr string
|
||||||
|
flagSet.StringVar(&addr, "addr", "", "")
|
||||||
|
_ = flagSet.Parse(os.Args[2:])
|
||||||
|
|
||||||
|
if len(addr) == 0 {
|
||||||
|
addr = "127.0.0.1:6060"
|
||||||
|
}
|
||||||
logs.Println("starting with pprof '" + addr + "'...")
|
logs.Println("starting with pprof '" + addr + "'...")
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
err := http.ListenAndServe(addr, nil)
|
err := http.ListenAndServe(addr, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logs.Println("[error]" + err.Error())
|
logs.Println("[ERROR]" + err.Error())
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
node := nodes.NewNode()
|
var node = nodes.NewNode()
|
||||||
node.Start()
|
node.Start()
|
||||||
})
|
})
|
||||||
app.On("dbstat", func() {
|
app.On("dbstat", func() {
|
||||||
teaconst.EnableDBStat = true
|
teaconst.EnableDBStat = true
|
||||||
|
|
||||||
node := nodes.NewNode()
|
var node = nodes.NewNode()
|
||||||
node.Start()
|
node.Start()
|
||||||
})
|
})
|
||||||
app.On("trackers", func() {
|
app.On("trackers", func() {
|
||||||
@@ -154,7 +161,7 @@ func main() {
|
|||||||
app.On("ip.drop", func() {
|
app.On("ip.drop", func() {
|
||||||
var args = os.Args[2:]
|
var args = os.Args[2:]
|
||||||
if len(args) == 0 {
|
if len(args) == 0 {
|
||||||
fmt.Println("Usage: edge-node ip.drop IP [--timeout=SECONDS]")
|
fmt.Println("Usage: edge-node ip.drop IP [--timeout=SECONDS] [--async]")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var ip = args[0]
|
var ip = args[0]
|
||||||
@@ -168,6 +175,11 @@ func main() {
|
|||||||
if ok {
|
if ok {
|
||||||
timeoutSeconds = types.Int(timeout[0])
|
timeoutSeconds = types.Int(timeout[0])
|
||||||
}
|
}
|
||||||
|
var async = false
|
||||||
|
_, ok = options["async"]
|
||||||
|
if ok {
|
||||||
|
async = true
|
||||||
|
}
|
||||||
|
|
||||||
fmt.Println("drop ip '" + ip + "' for '" + types.String(timeoutSeconds) + "' seconds")
|
fmt.Println("drop ip '" + ip + "' for '" + types.String(timeoutSeconds) + "' seconds")
|
||||||
var sock = gosock.NewTmpSock(teaconst.ProcessName)
|
var sock = gosock.NewTmpSock(teaconst.ProcessName)
|
||||||
@@ -176,6 +188,7 @@ func main() {
|
|||||||
Params: map[string]interface{}{
|
Params: map[string]interface{}{
|
||||||
"ip": ip,
|
"ip": ip,
|
||||||
"timeoutSeconds": timeoutSeconds,
|
"timeoutSeconds": timeoutSeconds,
|
||||||
|
"async": async,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -258,8 +271,55 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
app.On("accesslog", func() {
|
||||||
|
// local sock
|
||||||
|
var tmpDir = os.TempDir()
|
||||||
|
var sockFile = tmpDir + "/" + teaconst.AccessLogSockName
|
||||||
|
_, err := os.Stat(sockFile)
|
||||||
|
if err != nil {
|
||||||
|
if !os.IsNotExist(err) {
|
||||||
|
fmt.Println("[ERROR]" + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var processSock = gosock.NewTmpSock(teaconst.ProcessName)
|
||||||
|
reply, err := processSock.Send(&gosock.Command{
|
||||||
|
Code: "accesslog",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("[ERROR]" + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if reply.Code == "error" {
|
||||||
|
var errString = maps.NewMap(reply.Params).GetString("error")
|
||||||
|
if len(errString) > 0 {
|
||||||
|
fmt.Println("[ERROR]" + errString)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
conn, err := net.Dial("unix", sockFile)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("[ERROR]start reading access log failed: " + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
_ = conn.Close()
|
||||||
|
}()
|
||||||
|
var buf = make([]byte, 1024)
|
||||||
|
for {
|
||||||
|
n, err := conn.Read(buf)
|
||||||
|
if n > 0 {
|
||||||
|
fmt.Print(string(buf[:n]))
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
app.Run(func() {
|
app.Run(func() {
|
||||||
node := nodes.NewNode()
|
var node = nodes.NewNode()
|
||||||
node.Start()
|
node.Start()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
1
dist/.gitignore
vendored
1
dist/.gitignore
vendored
@@ -1 +1,2 @@
|
|||||||
*.zip
|
*.zip
|
||||||
|
edge-node
|
||||||
45
go.mod
45
go.mod
@@ -1,27 +1,30 @@
|
|||||||
module github.com/TeaOSLab/EdgeNode
|
module github.com/TeaOSLab/EdgeNode
|
||||||
|
|
||||||
go 1.15
|
go 1.18
|
||||||
|
|
||||||
replace github.com/TeaOSLab/EdgeCommon => ../EdgeCommon
|
replace (
|
||||||
|
github.com/TeaOSLab/EdgeCommon => ../EdgeCommon
|
||||||
|
github.com/fsnotify/fsnotify => /Users/WorkSpace/Projects/fsnotify
|
||||||
|
rogchap.com/v8go => /Users/Workspace/Projects/v8go
|
||||||
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/TeaOSLab/EdgeCommon v0.0.0-00010101000000-000000000000
|
github.com/TeaOSLab/EdgeCommon v0.0.0-00010101000000-000000000000
|
||||||
github.com/andybalholm/brotli v1.0.4
|
github.com/andybalholm/brotli v1.0.4
|
||||||
github.com/biessek/golang-ico v0.0.0-20180326222316-d348d9ea4670
|
github.com/biessek/golang-ico v0.0.0-20180326222316-d348d9ea4670
|
||||||
github.com/cespare/xxhash v1.1.0
|
github.com/cespare/xxhash v1.1.0
|
||||||
github.com/chai2010/webp v1.1.0 // indirect
|
|
||||||
github.com/dchest/captcha v0.0.0-20200903113550-03f5f0333e1f
|
github.com/dchest/captcha v0.0.0-20200903113550-03f5f0333e1f
|
||||||
github.com/fsnotify/fsnotify v1.5.1
|
github.com/fsnotify/fsnotify v1.5.1
|
||||||
github.com/go-redis/redis/v8 v8.11.5
|
github.com/go-redis/redis/v8 v8.11.5
|
||||||
github.com/golang/protobuf v1.5.2
|
github.com/golang/protobuf v1.5.2
|
||||||
github.com/google/nftables v0.0.0-20220407195405-950e408d48c6
|
github.com/google/nftables v0.0.0-20220407195405-950e408d48c6
|
||||||
github.com/iwind/TeaGo v0.0.0-20220304043459-0dd944a5b475
|
github.com/iwind/TeaGo v0.0.0-20220807030847-31de8e1cbe55
|
||||||
github.com/iwind/gofcgi v0.0.0-20210528023741-a92711d45f11
|
github.com/iwind/gofcgi v0.0.0-20210528023741-a92711d45f11
|
||||||
github.com/iwind/gosock v0.0.0-20211103081026-ee4652210ca4
|
github.com/iwind/gosock v0.0.0-20211103081026-ee4652210ca4
|
||||||
github.com/iwind/gowebp v0.0.0-20211029040624-7331ecc78ed8
|
github.com/iwind/gowebp v0.0.0-20211029040624-7331ecc78ed8
|
||||||
github.com/jsummers/gobmp v0.0.0-20151104160322-e2ba15ffa76e // indirect
|
github.com/klauspost/compress v1.15.8
|
||||||
github.com/kr/text v0.2.0 // indirect
|
|
||||||
github.com/mattn/go-sqlite3 v1.14.9
|
github.com/mattn/go-sqlite3 v1.14.9
|
||||||
|
github.com/mdlayher/netlink v1.4.2
|
||||||
github.com/miekg/dns v1.1.43
|
github.com/miekg/dns v1.1.43
|
||||||
github.com/mssola/user_agent v0.5.3
|
github.com/mssola/user_agent v0.5.3
|
||||||
github.com/pires/go-proxyproto v0.6.1
|
github.com/pires/go-proxyproto v0.6.1
|
||||||
@@ -31,6 +34,32 @@ require (
|
|||||||
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad
|
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad
|
||||||
golang.org/x/text v0.3.7
|
golang.org/x/text v0.3.7
|
||||||
google.golang.org/grpc v1.45.0
|
google.golang.org/grpc v1.45.0
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
|
rogchap.com/v8go v0.7.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/BurntSushi/toml v0.4.1 // indirect
|
||||||
|
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
||||||
|
github.com/chai2010/webp v1.1.0 // indirect
|
||||||
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||||
|
github.com/go-ole/go-ole v1.2.6 // indirect
|
||||||
|
github.com/go-sql-driver/mysql v1.5.0 // indirect
|
||||||
|
github.com/google/go-cmp v0.5.7 // indirect
|
||||||
|
github.com/josharian/native v0.0.0-20200817173448-b6b71def0850 // indirect
|
||||||
|
github.com/jsummers/gobmp v0.0.0-20151104160322-e2ba15ffa76e // indirect
|
||||||
|
github.com/kr/text v0.2.0 // indirect
|
||||||
|
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
|
||||||
|
github.com/mdlayher/socket v0.0.0-20211102153432-57e3fa563ecb // indirect
|
||||||
|
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
|
||||||
|
github.com/tklauser/go-sysconf v0.3.9 // indirect
|
||||||
|
github.com/tklauser/numcpus v0.3.0 // indirect
|
||||||
|
github.com/yusufpapurcu/wmi v1.2.2 // indirect
|
||||||
|
golang.org/x/mod v0.5.1 // indirect
|
||||||
|
golang.org/x/tools v0.1.8 // indirect
|
||||||
|
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
||||||
|
google.golang.org/genproto v0.0.0-20220317150908-0efb43f6373e // indirect
|
||||||
|
google.golang.org/protobuf v1.27.1 // indirect
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
|
||||||
|
honnef.co/go/tools v0.2.2 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
43
go.sum
43
go.sum
@@ -22,11 +22,7 @@ github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cb
|
|||||||
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
github.com/chai2010/webp v1.1.0 h1:4Ei0/BRroMF9FaXDG2e4OxwFcuW2vcXd+A6tyqTJUQQ=
|
github.com/chai2010/webp v1.1.0 h1:4Ei0/BRroMF9FaXDG2e4OxwFcuW2vcXd+A6tyqTJUQQ=
|
||||||
github.com/chai2010/webp v1.1.0/go.mod h1:LP12PG5IFmLGHUU26tBiCBKnghxx3toZFwDjOYvd3Ow=
|
github.com/chai2010/webp v1.1.0/go.mod h1:LP12PG5IFmLGHUU26tBiCBKnghxx3toZFwDjOYvd3Ow=
|
||||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
|
||||||
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
|
|
||||||
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
|
|
||||||
github.com/cilium/ebpf v0.5.0/go.mod h1:4tRaxcgiL706VnOzHOdBlY8IEAIdxINsQBcU4xJJXRs=
|
github.com/cilium/ebpf v0.5.0/go.mod h1:4tRaxcgiL706VnOzHOdBlY8IEAIdxINsQBcU4xJJXRs=
|
||||||
github.com/cilium/ebpf v0.7.0 h1:1k/q3ATgxSXRdrmPfH8d7YK0GfqVsEKZAX9dQZvs56k=
|
|
||||||
github.com/cilium/ebpf v0.7.0/go.mod h1:/oI2+1shJiTGAMgl6/RgJr36Eo1jzrRcAWbcXO2usCA=
|
github.com/cilium/ebpf v0.7.0/go.mod h1:/oI2+1shJiTGAMgl6/RgJr36Eo1jzrRcAWbcXO2usCA=
|
||||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||||
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
|
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
|
||||||
@@ -50,7 +46,6 @@ github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1m
|
|||||||
github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
|
github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
|
||||||
github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0=
|
github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0=
|
||||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||||
github.com/frankban/quicktest v1.11.3 h1:8sXhOn0uLys67V8EsXLc6eszDs8VXWxL3iRvebPhedY=
|
|
||||||
github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM0I9ntUbOk+k=
|
github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM0I9ntUbOk+k=
|
||||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||||
@@ -65,7 +60,6 @@ github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC
|
|||||||
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
|
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
|
||||||
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
|
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
|
||||||
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
|
||||||
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
|
|
||||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||||
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||||
@@ -96,17 +90,15 @@ github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8
|
|||||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
github.com/google/nftables v0.0.0-20220407195405-950e408d48c6 h1:btadZscaRmsi/+fOhkyUguRpSnrf6dykNEWxDeUCj9I=
|
github.com/google/nftables v0.0.0-20220407195405-950e408d48c6 h1:btadZscaRmsi/+fOhkyUguRpSnrf6dykNEWxDeUCj9I=
|
||||||
github.com/google/nftables v0.0.0-20220407195405-950e408d48c6/go.mod h1:0F8on3JWMkm+xahTHItkiu/E1SPqMd0TOxNweQv8ptE=
|
github.com/google/nftables v0.0.0-20220407195405-950e408d48c6/go.mod h1:0F8on3JWMkm+xahTHItkiu/E1SPqMd0TOxNweQv8ptE=
|
||||||
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
|
|
||||||
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
|
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
|
||||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||||
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
github.com/iwind/TeaGo v0.0.0-20220807023459-448081424640 h1:nBVQzDI4mrQS+Egg+Li6BGiTToBsv+XTck+BItgI52k=
|
||||||
github.com/iwind/TeaGo v0.0.0-20220304043459-0dd944a5b475 h1:EseyfFaQOjWanGiby9KMw7PjDBMg/95tLDgIw/ns0Cw=
|
github.com/iwind/TeaGo v0.0.0-20220807023459-448081424640/go.mod h1:+K2l6Num4Evl0jH7TYlZJ1oFJX8sA8YUC31Pb+I1mJk=
|
||||||
github.com/iwind/TeaGo v0.0.0-20220304043459-0dd944a5b475/go.mod h1:HRHK0zoC/og3c9/hKosD9yYVMTnnzm3PgXUdhRYHaLc=
|
github.com/iwind/TeaGo v0.0.0-20220807030847-31de8e1cbe55 h1:shQNx0flJFBwKsGE7Hs3bI2bDz+YF0zl/4qE8B2KRiY=
|
||||||
|
github.com/iwind/TeaGo v0.0.0-20220807030847-31de8e1cbe55/go.mod h1:fi/Pq+/5m2HZoseM+39dMF57ANXRt6w4PkGu3NXPc5s=
|
||||||
github.com/iwind/gofcgi v0.0.0-20210528023741-a92711d45f11 h1:DaQjoWZhLNxjhIXedVg4/vFEtHkZhK4IjIwsWdyzBLg=
|
github.com/iwind/gofcgi v0.0.0-20210528023741-a92711d45f11 h1:DaQjoWZhLNxjhIXedVg4/vFEtHkZhK4IjIwsWdyzBLg=
|
||||||
github.com/iwind/gofcgi v0.0.0-20210528023741-a92711d45f11/go.mod h1:JtbX20untAjUVjZs1ZBtq80f5rJWvwtQNRL6EnuYRnY=
|
github.com/iwind/gofcgi v0.0.0-20210528023741-a92711d45f11/go.mod h1:JtbX20untAjUVjZs1ZBtq80f5rJWvwtQNRL6EnuYRnY=
|
||||||
github.com/iwind/gosock v0.0.0-20210722083328-12b2d66abec3 h1:aBSonas7vFcgTj9u96/bWGILGv1ZbUSTLiOzcI1ZT6c=
|
|
||||||
github.com/iwind/gosock v0.0.0-20210722083328-12b2d66abec3/go.mod h1:H5Q7SXwbx3a97ecJkaS2sD77gspzE7HFUafBO0peEyA=
|
|
||||||
github.com/iwind/gosock v0.0.0-20211103081026-ee4652210ca4 h1:VWGsCqTzObdlbf7UUE3oceIpcEKi4C/YBUszQXk118A=
|
github.com/iwind/gosock v0.0.0-20211103081026-ee4652210ca4 h1:VWGsCqTzObdlbf7UUE3oceIpcEKi4C/YBUszQXk118A=
|
||||||
github.com/iwind/gosock v0.0.0-20211103081026-ee4652210ca4/go.mod h1:H5Q7SXwbx3a97ecJkaS2sD77gspzE7HFUafBO0peEyA=
|
github.com/iwind/gosock v0.0.0-20211103081026-ee4652210ca4/go.mod h1:H5Q7SXwbx3a97ecJkaS2sD77gspzE7HFUafBO0peEyA=
|
||||||
github.com/iwind/gowebp v0.0.0-20211029040624-7331ecc78ed8 h1:AojsHz9Es9B3He2MQQxeRq3TyD//o9huxUo7r1wh44g=
|
github.com/iwind/gowebp v0.0.0-20211029040624-7331ecc78ed8 h1:AojsHz9Es9B3He2MQQxeRq3TyD//o9huxUo7r1wh44g=
|
||||||
@@ -123,9 +115,10 @@ github.com/jsimonetti/rtnetlink v0.0.0-20210212075122-66c871082f2b/go.mod h1:8w9
|
|||||||
github.com/jsimonetti/rtnetlink v0.0.0-20210525051524-4cc836578190/go.mod h1:NmKSdU4VGSiv1bMsdqNALI4RSvvjtz65tTMCnD05qLo=
|
github.com/jsimonetti/rtnetlink v0.0.0-20210525051524-4cc836578190/go.mod h1:NmKSdU4VGSiv1bMsdqNALI4RSvvjtz65tTMCnD05qLo=
|
||||||
github.com/jsimonetti/rtnetlink v0.0.0-20211022192332-93da33804786 h1:N527AHMa793TP5z5GNAn/VLPzlc0ewzWdeP/25gDfgQ=
|
github.com/jsimonetti/rtnetlink v0.0.0-20211022192332-93da33804786 h1:N527AHMa793TP5z5GNAn/VLPzlc0ewzWdeP/25gDfgQ=
|
||||||
github.com/jsimonetti/rtnetlink v0.0.0-20211022192332-93da33804786/go.mod h1:v4hqbTdfQngbVSZJVWUhGE/lbTFf9jb+ygmNUDQMuOs=
|
github.com/jsimonetti/rtnetlink v0.0.0-20211022192332-93da33804786/go.mod h1:v4hqbTdfQngbVSZJVWUhGE/lbTFf9jb+ygmNUDQMuOs=
|
||||||
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
|
||||||
github.com/jsummers/gobmp v0.0.0-20151104160322-e2ba15ffa76e h1:LvL4XsI70QxOGHed6yhQtAU34Kx3Qq2wwBzGFKY8zKk=
|
github.com/jsummers/gobmp v0.0.0-20151104160322-e2ba15ffa76e h1:LvL4XsI70QxOGHed6yhQtAU34Kx3Qq2wwBzGFKY8zKk=
|
||||||
github.com/jsummers/gobmp v0.0.0-20151104160322-e2ba15ffa76e/go.mod h1:kLgvv7o6UM+0QSf0QjAse3wReFDsb9qbZJdfexWlrQw=
|
github.com/jsummers/gobmp v0.0.0-20151104160322-e2ba15ffa76e/go.mod h1:kLgvv7o6UM+0QSf0QjAse3wReFDsb9qbZJdfexWlrQw=
|
||||||
|
github.com/klauspost/compress v1.15.8 h1:JahtItbkWjf2jzm/T+qgMxkP9EMHsqEUA6vCMGmXvhA=
|
||||||
|
github.com/klauspost/compress v1.15.8/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
|
||||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||||
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
|
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
|
||||||
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||||
@@ -160,29 +153,20 @@ github.com/mdlayher/socket v0.0.0-20211102153432-57e3fa563ecb h1:2dC7L10LmTqlyMV
|
|||||||
github.com/mdlayher/socket v0.0.0-20211102153432-57e3fa563ecb/go.mod h1:nFZ1EtZYK8Gi/k6QNu7z7CgO20i/4ExeQswwWuPmG/g=
|
github.com/mdlayher/socket v0.0.0-20211102153432-57e3fa563ecb/go.mod h1:nFZ1EtZYK8Gi/k6QNu7z7CgO20i/4ExeQswwWuPmG/g=
|
||||||
github.com/miekg/dns v1.1.43 h1:JKfpVSCB84vrAmHzyrsxB5NAr5kLoMXZArPSw7Qlgyg=
|
github.com/miekg/dns v1.1.43 h1:JKfpVSCB84vrAmHzyrsxB5NAr5kLoMXZArPSw7Qlgyg=
|
||||||
github.com/miekg/dns v1.1.43/go.mod h1:+evo5L0630/F6ca/Z9+GAqzhjGyn8/c+TBaOyfEl0V4=
|
github.com/miekg/dns v1.1.43/go.mod h1:+evo5L0630/F6ca/Z9+GAqzhjGyn8/c+TBaOyfEl0V4=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
|
||||||
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
|
|
||||||
github.com/mssola/user_agent v0.5.3 h1:lBRPML9mdFuIZgI2cmlQ+atbpJdLdeVl2IDodjBR578=
|
github.com/mssola/user_agent v0.5.3 h1:lBRPML9mdFuIZgI2cmlQ+atbpJdLdeVl2IDodjBR578=
|
||||||
github.com/mssola/user_agent v0.5.3/go.mod h1:TTPno8LPY3wAIEKRpAtkdMT0f8SE24pLRGPahjCH4uw=
|
github.com/mssola/user_agent v0.5.3/go.mod h1:TTPno8LPY3wAIEKRpAtkdMT0f8SE24pLRGPahjCH4uw=
|
||||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||||
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
|
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
|
||||||
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
|
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
|
||||||
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
|
|
||||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||||
github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||||
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
|
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
|
||||||
github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY=
|
github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY=
|
||||||
github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=
|
|
||||||
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
|
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
|
||||||
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
|
|
||||||
github.com/onsi/ginkgo/v2 v2.0.0 h1:CcuG/HvWNkkaqCUpJifQY8z7qEMBJya6aLPx6ftGyjQ=
|
|
||||||
github.com/onsi/ginkgo/v2 v2.0.0/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c=
|
|
||||||
github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
||||||
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
|
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
|
||||||
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
|
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
|
||||||
github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=
|
|
||||||
github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE=
|
github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE=
|
||||||
github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs=
|
|
||||||
github.com/opentracing/opentracing-go v1.1.1-0.20190913142402-a7454ce5950e/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
|
github.com/opentracing/opentracing-go v1.1.1-0.20190913142402-a7454ce5950e/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o=
|
||||||
github.com/pires/go-proxyproto v0.6.1 h1:EBupykFmo22SDjv4fQVQd2J9NOoLPmyZA/15ldOGkPw=
|
github.com/pires/go-proxyproto v0.6.1 h1:EBupykFmo22SDjv4fQVQd2J9NOoLPmyZA/15ldOGkPw=
|
||||||
github.com/pires/go-proxyproto v0.6.1/go.mod h1:Odh9VFOZJCf9G8cLW5o435Xf1J95Jw9Gw5rnCjcwzAY=
|
github.com/pires/go-proxyproto v0.6.1/go.mod h1:Odh9VFOZJCf9G8cLW5o435Xf1J95Jw9Gw5rnCjcwzAY=
|
||||||
@@ -197,7 +181,6 @@ github.com/shirou/gopsutil/v3 v3.22.2/go.mod h1:WapW1AOOPlHyXr+yOyw3uYx36enocrtS
|
|||||||
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72 h1:qLC7fQah7D6K1B0ujays3HV9gkFtllcxhzImRR7ArPQ=
|
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72 h1:qLC7fQah7D6K1B0ujays3HV9gkFtllcxhzImRR7ArPQ=
|
||||||
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
|
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
|
||||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||||
@@ -257,7 +240,6 @@ golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v
|
|||||||
golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
||||||
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
|
|
||||||
golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
@@ -290,7 +272,6 @@ golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7w
|
|||||||
golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
||||||
golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
@@ -301,7 +282,6 @@ golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7w
|
|||||||
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20201218084310-7d0127a74742/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20201218084310-7d0127a74742/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210110051926-789bb1bd4061/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210110051926-789bb1bd4061/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
||||||
golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210123111255-9b0068b26619/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210123111255-9b0068b26619/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
@@ -312,7 +292,6 @@ golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7w
|
|||||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20210525143221-35b2ab0089ea/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20210525143221-35b2ab0089ea/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20210816074244-15123e1e1f71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20210816074244-15123e1e1f71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
@@ -322,14 +301,10 @@ golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBc
|
|||||||
golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20211205182925-97ca703d548d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20211205182925-97ca703d548d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.0.0-20220111092808-5a964db01320/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220111092808-5a964db01320/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8 h1:OH54vjqzRWmbJ62fjuhxy7AxFFgoHN0/DPc/UrL8cAs=
|
|
||||||
golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad h1:ntjMns5wyP/fN65tdBD4g8J5w8n015+iIIs9rtjXkY0=
|
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad h1:ntjMns5wyP/fN65tdBD4g8J5w8n015+iIIs9rtjXkY0=
|
||||||
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
@@ -344,7 +319,6 @@ golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3
|
|||||||
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
|
||||||
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
|
||||||
golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=
|
golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=
|
||||||
golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
|
golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
|
||||||
golang.org/x/tools v0.1.8 h1:P1HhGGuLW4aAclzjtmJdf0mJOjVUZUzOTqkAkWL+l6w=
|
golang.org/x/tools v0.1.8 h1:P1HhGGuLW4aAclzjtmJdf0mJOjVUZUzOTqkAkWL+l6w=
|
||||||
@@ -400,13 +374,14 @@ gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
|||||||
gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
|
|
||||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
honnef.co/go/tools v0.2.1/go.mod h1:lPVVZ2BS5TfnjLyizF7o7hv7j9/L+8cZY2hLyjP9cGY=
|
honnef.co/go/tools v0.2.1/go.mod h1:lPVVZ2BS5TfnjLyizF7o7hv7j9/L+8cZY2hLyjP9cGY=
|
||||||
honnef.co/go/tools v0.2.2 h1:MNh1AVMyVX23VUHE2O27jm6lNj3vjO5DexS4A1xvnzk=
|
honnef.co/go/tools v0.2.2 h1:MNh1AVMyVX23VUHE2O27jm6lNj3vjO5DexS4A1xvnzk=
|
||||||
honnef.co/go/tools v0.2.2/go.mod h1:lPVVZ2BS5TfnjLyizF7o7hv7j9/L+8cZY2hLyjP9cGY=
|
honnef.co/go/tools v0.2.2/go.mod h1:lPVVZ2BS5TfnjLyizF7o7hv7j9/L+8cZY2hLyjP9cGY=
|
||||||
|
rogchap.com/v8go v0.7.0 h1:kgjbiO4zE5itA962ze6Hqmbs4HgZbGzmueCXsZtremg=
|
||||||
rogchap.com/v8go v0.7.0/go.mod h1:MxgP3pL2MW4dpme/72QRs8sgNMmM0pRc8DPhcuLWPAs=
|
rogchap.com/v8go v0.7.0/go.mod h1:MxgP3pL2MW4dpme/72QRs8sgNMmM0pRc8DPhcuLWPAs=
|
||||||
|
|||||||
@@ -217,7 +217,10 @@ func (this *AppCmd) runStop() {
|
|||||||
if runtime.GOOS == "linux" {
|
if runtime.GOOS == "linux" {
|
||||||
systemctl, _ := exec.LookPath("systemctl")
|
systemctl, _ := exec.LookPath("systemctl")
|
||||||
if len(systemctl) > 0 {
|
if len(systemctl) > 0 {
|
||||||
_ = exec.Command(systemctl, "stop", teaconst.SystemdServiceName).Run()
|
go func() {
|
||||||
|
// 有可能会长时间执行,这里不阻塞进程
|
||||||
|
_ = exec.Command(systemctl, "stop", teaconst.SystemdServiceName).Run()
|
||||||
|
}()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -89,7 +89,10 @@ func (this *LogWriter) Write(message string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this.c <- message
|
select {
|
||||||
|
case this.c <- message:
|
||||||
|
default:
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (this *LogWriter) Close() {
|
func (this *LogWriter) Close() {
|
||||||
|
|||||||
@@ -227,7 +227,7 @@ func (this *FileList) PurgeLFU(count int, callback func(hash string) error) erro
|
|||||||
if notFound {
|
if notFound {
|
||||||
_, err = db.deleteHitByHashStmt.Exec(hash)
|
_, err = db.deleteHitByHashStmt.Exec(hash)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return db.WrapError(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -359,14 +359,14 @@ func (this *FileList) remove(hash string) (notFound bool, err error) {
|
|||||||
|
|
||||||
_, err = db.deleteByHashStmt.Exec(hash)
|
_, err = db.deleteByHashStmt.Exec(hash)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, db.WrapError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
atomic.AddInt64(&this.total, -1)
|
atomic.AddInt64(&this.total, -1)
|
||||||
|
|
||||||
_, err = db.deleteHitByHashStmt.Exec(hash)
|
_, err = db.deleteHitByHashStmt.Exec(hash)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, db.WrapError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if this.onRemove != nil {
|
if this.onRemove != nil {
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type FileListDB struct {
|
type FileListDB struct {
|
||||||
|
dbPath string
|
||||||
|
|
||||||
readDB *dbs.DB
|
readDB *dbs.DB
|
||||||
writeDB *dbs.DB
|
writeDB *dbs.DB
|
||||||
|
|
||||||
@@ -49,6 +51,8 @@ func NewFileListDB() *FileListDB {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (this *FileListDB) Open(dbPath string) error {
|
func (this *FileListDB) Open(dbPath string) error {
|
||||||
|
this.dbPath = dbPath
|
||||||
|
|
||||||
// write db
|
// write db
|
||||||
writeDB, err := sql.Open("sqlite3", "file:"+dbPath+"?cache=private&mode=rwc&_journal_mode=WAL&_sync=OFF&_cache_size=32000&_secure_delete=FAST")
|
writeDB, err := sql.Open("sqlite3", "file:"+dbPath+"?cache=private&mode=rwc&_journal_mode=WAL&_sync=OFF&_cache_size=32000&_secure_delete=FAST")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -185,7 +189,7 @@ func (this *FileListDB) Add(hash string, item *Item) error {
|
|||||||
// 放入队列
|
// 放入队列
|
||||||
_, err := this.insertStmt.Exec(hash, item.Key, item.HeaderSize, item.BodySize, item.MetaSize, item.ExpiredAt, item.StaleAt, item.Host, item.ServerId, utils.UnixTime())
|
_, err := this.insertStmt.Exec(hash, item.Key, item.HeaderSize, item.BodySize, item.MetaSize, item.ExpiredAt, item.StaleAt, item.Host, item.ServerId, utils.UnixTime())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return this.WrapError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -249,7 +253,7 @@ func (this *FileListDB) ListLFUItems(count int) (hashList []string, err error) {
|
|||||||
func (this *FileListDB) IncreaseHit(hash string) error {
|
func (this *FileListDB) IncreaseHit(hash string) error {
|
||||||
var week = timeutil.Format("YW")
|
var week = timeutil.Format("YW")
|
||||||
_, err := this.increaseHitStmt.Exec(hash, week, week, week, week)
|
_, err := this.increaseHitStmt.Exec(hash, week, week, week, week)
|
||||||
return err
|
return this.WrapError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (this *FileListDB) CleanPrefix(prefix string) error {
|
func (this *FileListDB) CleanPrefix(prefix string) error {
|
||||||
@@ -262,7 +266,7 @@ func (this *FileListDB) CleanPrefix(prefix string) error {
|
|||||||
for {
|
for {
|
||||||
result, err := this.writeDB.Exec(`UPDATE "`+this.itemsTableName+`" SET expiredAt=0,staleAt=? WHERE id IN (SELECT id FROM "`+this.itemsTableName+`" WHERE expiredAt>0 AND createdAt<=? AND INSTR("key", ?)=1 LIMIT `+types.String(count)+`)`, unixTime+int64(staleLife), unixTime, prefix)
|
result, err := this.writeDB.Exec(`UPDATE "`+this.itemsTableName+`" SET expiredAt=0,staleAt=? WHERE id IN (SELECT id FROM "`+this.itemsTableName+`" WHERE expiredAt>0 AND createdAt<=? AND INSTR("key", ?)=1 LIMIT `+types.String(count)+`)`, unixTime+int64(staleLife), unixTime, prefix)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return this.WrapError(err)
|
||||||
}
|
}
|
||||||
affectedRows, err := result.RowsAffected()
|
affectedRows, err := result.RowsAffected()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -281,7 +285,7 @@ func (this *FileListDB) CleanAll() error {
|
|||||||
|
|
||||||
_, err := this.deleteAllStmt.Exec()
|
_, err := this.deleteAllStmt.Exec()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return this.WrapError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -351,6 +355,13 @@ func (this *FileListDB) Close() error {
|
|||||||
return errors.New("close database failed: " + strings.Join(errStrings, ", "))
|
return errors.New("close database failed: " + strings.Join(errStrings, ", "))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (this *FileListDB) WrapError(err error) error {
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return errors.New(err.Error() + "(file: " + this.dbPath + ")")
|
||||||
|
}
|
||||||
|
|
||||||
// 初始化
|
// 初始化
|
||||||
func (this *FileListDB) initTables(times int) error {
|
func (this *FileListDB) initTables(times int) error {
|
||||||
{
|
{
|
||||||
@@ -393,10 +404,10 @@ ON "` + this.itemsTableName + `" (
|
|||||||
if dropErr == nil {
|
if dropErr == nil {
|
||||||
return this.initTables(times + 1)
|
return this.initTables(times + 1)
|
||||||
}
|
}
|
||||||
return err
|
return this.WrapError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return err
|
return this.WrapError(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -421,10 +432,10 @@ ON "` + this.hitsTableName + `" (
|
|||||||
if dropErr == nil {
|
if dropErr == nil {
|
||||||
return this.initTables(times + 1)
|
return this.initTables(times + 1)
|
||||||
}
|
}
|
||||||
return err
|
return this.WrapError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return err
|
return this.WrapError(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -214,3 +214,15 @@ func (this *Manager) FindAllCachePaths() []string {
|
|||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FindAllStorages 读取所有缓存存储
|
||||||
|
func (this *Manager) FindAllStorages() []StorageInterface {
|
||||||
|
this.locker.Lock()
|
||||||
|
defer this.locker.Unlock()
|
||||||
|
|
||||||
|
var storages = []StorageInterface{}
|
||||||
|
for _, storage := range this.storageMap {
|
||||||
|
storages = append(storages, storage)
|
||||||
|
}
|
||||||
|
return storages
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,44 +3,24 @@
|
|||||||
package caches
|
package caches
|
||||||
|
|
||||||
import (
|
import (
|
||||||
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/goman"
|
"github.com/TeaOSLab/EdgeNode/internal/goman"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
minOpenFilesValue int32 = 2
|
|
||||||
maxOpenFilesValue int32 = 65535
|
|
||||||
|
|
||||||
modeSlow int32 = 1
|
modeSlow int32 = 1
|
||||||
modeFast int32 = 2
|
modeFast int32 = 2
|
||||||
)
|
)
|
||||||
|
|
||||||
// MaxOpenFiles max open files manager
|
// MaxOpenFiles max open files manager
|
||||||
type MaxOpenFiles struct {
|
type MaxOpenFiles struct {
|
||||||
step int32
|
ticker *time.Ticker
|
||||||
maxOpenFiles int32
|
mode int32
|
||||||
ptr *int32
|
|
||||||
ticker *time.Ticker
|
|
||||||
mode int32
|
|
||||||
|
|
||||||
lastOpens int32
|
|
||||||
currentOpens int32
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewMaxOpenFiles(step int32) *MaxOpenFiles {
|
func NewMaxOpenFiles() *MaxOpenFiles {
|
||||||
if step <= 0 {
|
var f = &MaxOpenFiles{}
|
||||||
step = 2
|
|
||||||
}
|
|
||||||
var f = &MaxOpenFiles{
|
|
||||||
step: step,
|
|
||||||
maxOpenFiles: 2,
|
|
||||||
}
|
|
||||||
if teaconst.DiskIsFast {
|
|
||||||
f.maxOpenFiles = 32
|
|
||||||
}
|
|
||||||
f.ptr = &f.maxOpenFiles
|
|
||||||
f.ticker = time.NewTicker(1 * time.Second)
|
f.ticker = time.NewTicker(1 * time.Second)
|
||||||
f.init()
|
f.init()
|
||||||
return f
|
return f
|
||||||
@@ -49,50 +29,24 @@ func NewMaxOpenFiles(step int32) *MaxOpenFiles {
|
|||||||
func (this *MaxOpenFiles) init() {
|
func (this *MaxOpenFiles) init() {
|
||||||
goman.New(func() {
|
goman.New(func() {
|
||||||
for range this.ticker.C {
|
for range this.ticker.C {
|
||||||
var mod = atomic.LoadInt32(&this.mode)
|
// reset mode
|
||||||
switch mod {
|
atomic.StoreInt32(&this.mode, modeFast)
|
||||||
case modeSlow:
|
|
||||||
// we decrease more quickly, with more steps
|
|
||||||
if atomic.AddInt32(this.ptr, -this.step*2) <= 0 {
|
|
||||||
atomic.StoreInt32(this.ptr, minOpenFilesValue)
|
|
||||||
}
|
|
||||||
case modeFast:
|
|
||||||
// we increase only when file opens increases
|
|
||||||
var currentOpens = atomic.LoadInt32(&this.currentOpens)
|
|
||||||
if currentOpens > this.lastOpens {
|
|
||||||
if atomic.AddInt32(this.ptr, this.step) >= maxOpenFilesValue {
|
|
||||||
atomic.StoreInt32(this.ptr, maxOpenFilesValue)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.lastOpens = currentOpens
|
|
||||||
atomic.StoreInt32(&this.currentOpens, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
// reset mod
|
|
||||||
atomic.StoreInt32(&this.mode, 0)
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (this *MaxOpenFiles) Fast() {
|
func (this *MaxOpenFiles) Fast() {
|
||||||
if atomic.LoadInt32(&this.mode) == 0 {
|
atomic.AddInt32(&this.mode, modeFast)
|
||||||
this.mode = modeFast
|
}
|
||||||
}
|
|
||||||
atomic.AddInt32(&this.currentOpens, 1)
|
func (this *MaxOpenFiles) FinishAll() {
|
||||||
|
this.Fast()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (this *MaxOpenFiles) Slow() {
|
func (this *MaxOpenFiles) Slow() {
|
||||||
atomic.StoreInt32(&this.mode, modeSlow)
|
atomic.StoreInt32(&this.mode, modeSlow)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (this *MaxOpenFiles) Max() int32 {
|
func (this *MaxOpenFiles) Next() bool {
|
||||||
if atomic.LoadInt32(&this.mode) == modeSlow {
|
return atomic.LoadInt32(&this.mode) != modeSlow
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
var v = atomic.LoadInt32(this.ptr)
|
|
||||||
if v <= minOpenFilesValue {
|
|
||||||
return minOpenFilesValue
|
|
||||||
}
|
|
||||||
return v
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,20 +9,27 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestNewMaxOpenFiles(t *testing.T) {
|
func TestNewMaxOpenFiles(t *testing.T) {
|
||||||
var maxOpenFiles = caches.NewMaxOpenFiles(2)
|
var maxOpenFiles = caches.NewMaxOpenFiles()
|
||||||
maxOpenFiles.Fast()
|
maxOpenFiles.Fast()
|
||||||
t.Log(maxOpenFiles.Max())
|
t.Log("fast:", maxOpenFiles.Next())
|
||||||
|
|
||||||
|
maxOpenFiles.Slow()
|
||||||
|
t.Log("slow:", maxOpenFiles.Next())
|
||||||
|
time.Sleep(1*time.Second + 1*time.Millisecond)
|
||||||
|
t.Log("slow 1 second:", maxOpenFiles.Next())
|
||||||
|
|
||||||
|
maxOpenFiles.Slow()
|
||||||
|
t.Log("slow:", maxOpenFiles.Next())
|
||||||
|
|
||||||
|
maxOpenFiles.Slow()
|
||||||
|
t.Log("slow:", maxOpenFiles.Next())
|
||||||
|
|
||||||
maxOpenFiles.Fast()
|
|
||||||
time.Sleep(1 * time.Second)
|
time.Sleep(1 * time.Second)
|
||||||
t.Log(maxOpenFiles.Max())
|
t.Log("slow 1 second:", maxOpenFiles.Next())
|
||||||
|
|
||||||
maxOpenFiles.Slow()
|
maxOpenFiles.Slow()
|
||||||
t.Log(maxOpenFiles.Max())
|
t.Log("slow:", maxOpenFiles.Next())
|
||||||
|
|
||||||
maxOpenFiles.Slow()
|
maxOpenFiles.Fast()
|
||||||
t.Log(maxOpenFiles.Max())
|
t.Log("fast:", maxOpenFiles.Next())
|
||||||
|
|
||||||
maxOpenFiles.Slow()
|
|
||||||
t.Log(maxOpenFiles.Max())
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ package caches
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"io/ioutil"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
// PartialRanges 内容分区范围定义
|
// PartialRanges 内容分区范围定义
|
||||||
@@ -30,7 +30,7 @@ func NewPartialRangesFromJSON(data []byte) (*PartialRanges, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewPartialRangesFromFile(path string) (*PartialRanges, error) {
|
func NewPartialRangesFromFile(path string) (*PartialRanges, error) {
|
||||||
data, err := ioutil.ReadFile(path)
|
data, err := os.ReadFile(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -116,12 +116,12 @@ func (this *PartialRanges) WriteToFile(path string) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.New("convert to json failed: " + err.Error())
|
return errors.New("convert to json failed: " + err.Error())
|
||||||
}
|
}
|
||||||
return ioutil.WriteFile(path, data, 0666)
|
return os.WriteFile(path, data, 0666)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReadFromFile 从文件中读取
|
// ReadFromFile 从文件中读取
|
||||||
func (this *PartialRanges) ReadFromFile(path string) (*PartialRanges, error) {
|
func (this *PartialRanges) ReadFromFile(path string) (*PartialRanges, error) {
|
||||||
data, err := ioutil.ReadFile(path)
|
data, err := os.ReadFile(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,13 +63,15 @@ const (
|
|||||||
var sharedWritingFileKeyMap = map[string]zero.Zero{} // key => bool
|
var sharedWritingFileKeyMap = map[string]zero.Zero{} // key => bool
|
||||||
var sharedWritingFileKeyLocker = sync.Mutex{}
|
var sharedWritingFileKeyLocker = sync.Mutex{}
|
||||||
|
|
||||||
var maxOpenFiles = NewMaxOpenFiles(2)
|
var maxOpenFiles = NewMaxOpenFiles()
|
||||||
|
|
||||||
const maxOpenFilesSlowCost = 500 * time.Microsecond // 0.5ms
|
const maxOpenFilesSlowCost = 1000 * time.Microsecond // us
|
||||||
|
const protectingLoadWhenDump = false
|
||||||
|
|
||||||
// FileStorage 文件缓存
|
// FileStorage 文件缓存
|
||||||
// 文件结构:
|
//
|
||||||
// [expires time] | [ status ] | [url length] | [header length] | [body length] | [url] [header data] [body data]
|
// 文件结构:
|
||||||
|
// [expires time] | [ status ] | [url length] | [header length] | [body length] | [url] [header data] [body data]
|
||||||
type FileStorage struct {
|
type FileStorage struct {
|
||||||
policy *serverconfigs.HTTPCachePolicy
|
policy *serverconfigs.HTTPCachePolicy
|
||||||
options *serverconfigs.HTTPFileCacheStorage // 二级缓存
|
options *serverconfigs.HTTPFileCacheStorage // 二级缓存
|
||||||
@@ -428,7 +430,7 @@ func (this *FileStorage) openWriter(key string, expiredAt int64, status int, siz
|
|||||||
return nil, ErrFileIsWriting
|
return nil, ErrFileIsWriting
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(sharedWritingFileKeyMap) >= int(maxOpenFiles.Max()) {
|
if !isFlushing && !maxOpenFiles.Next() {
|
||||||
sharedWritingFileKeyLocker.Unlock()
|
sharedWritingFileKeyLocker.Unlock()
|
||||||
return nil, ErrTooManyOpenFiles
|
return nil, ErrTooManyOpenFiles
|
||||||
}
|
}
|
||||||
@@ -439,6 +441,9 @@ func (this *FileStorage) openWriter(key string, expiredAt int64, status int, siz
|
|||||||
if !isOk {
|
if !isOk {
|
||||||
sharedWritingFileKeyLocker.Lock()
|
sharedWritingFileKeyLocker.Lock()
|
||||||
delete(sharedWritingFileKeyMap, key)
|
delete(sharedWritingFileKeyMap, key)
|
||||||
|
if len(sharedWritingFileKeyMap) == 0 {
|
||||||
|
maxOpenFiles.FinishAll()
|
||||||
|
}
|
||||||
sharedWritingFileKeyLocker.Unlock()
|
sharedWritingFileKeyLocker.Unlock()
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
@@ -481,11 +486,16 @@ func (this *FileStorage) openWriter(key string, expiredAt int64, status int, siz
|
|||||||
openFileCache.Close(cachePath)
|
openFileCache.Close(cachePath)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 查询当前已有缓存文件
|
||||||
stat, err := os.Stat(cachePath)
|
stat, err := os.Stat(cachePath)
|
||||||
if err == nil && time.Now().Sub(stat.ModTime()) <= 1*time.Second {
|
|
||||||
|
// 检查两次写入缓存的时间是否过于相近,分片内容不受此限制
|
||||||
|
if err == nil && !isPartial && time.Now().Sub(stat.ModTime()) <= 1*time.Second {
|
||||||
// 防止并发连续写入
|
// 防止并发连续写入
|
||||||
return nil, ErrFileIsWriting
|
return nil, ErrFileIsWriting
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 构造文件名
|
||||||
var tmpPath = cachePath
|
var tmpPath = cachePath
|
||||||
var existsFile = false
|
var existsFile = false
|
||||||
if stat != nil {
|
if stat != nil {
|
||||||
@@ -534,10 +544,12 @@ func (this *FileStorage) openWriter(key string, expiredAt int64, status int, siz
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if time.Since(before) >= maxOpenFilesSlowCost {
|
if !isFlushing {
|
||||||
maxOpenFiles.Slow()
|
if time.Since(before) >= maxOpenFilesSlowCost {
|
||||||
} else {
|
maxOpenFiles.Slow()
|
||||||
maxOpenFiles.Fast()
|
} else {
|
||||||
|
maxOpenFiles.Fast()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var removeOnFailure = true
|
var removeOnFailure = true
|
||||||
@@ -601,12 +613,18 @@ func (this *FileStorage) openWriter(key string, expiredAt int64, status int, siz
|
|||||||
return NewPartialFileWriter(writer, key, expiredAt, isNewCreated, isPartial, partialBodyOffset, ranges, func() {
|
return NewPartialFileWriter(writer, key, expiredAt, isNewCreated, isPartial, partialBodyOffset, ranges, func() {
|
||||||
sharedWritingFileKeyLocker.Lock()
|
sharedWritingFileKeyLocker.Lock()
|
||||||
delete(sharedWritingFileKeyMap, key)
|
delete(sharedWritingFileKeyMap, key)
|
||||||
|
if len(sharedWritingFileKeyMap) == 0 {
|
||||||
|
maxOpenFiles.FinishAll()
|
||||||
|
}
|
||||||
sharedWritingFileKeyLocker.Unlock()
|
sharedWritingFileKeyLocker.Unlock()
|
||||||
}), nil
|
}), nil
|
||||||
} else {
|
} else {
|
||||||
return NewFileWriter(this, writer, key, expiredAt, -1, func() {
|
return NewFileWriter(this, writer, key, expiredAt, -1, func() {
|
||||||
sharedWritingFileKeyLocker.Lock()
|
sharedWritingFileKeyLocker.Lock()
|
||||||
delete(sharedWritingFileKeyMap, key)
|
delete(sharedWritingFileKeyMap, key)
|
||||||
|
if len(sharedWritingFileKeyMap) == 0 {
|
||||||
|
maxOpenFiles.FinishAll()
|
||||||
|
}
|
||||||
sharedWritingFileKeyLocker.Unlock()
|
sharedWritingFileKeyLocker.Unlock()
|
||||||
}), nil
|
}), nil
|
||||||
}
|
}
|
||||||
@@ -767,9 +785,10 @@ func (this *FileStorage) Purge(keys []string, urlType string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// 文件
|
// URL
|
||||||
for _, key := range keys {
|
for _, key := range keys {
|
||||||
hash, path := this.keyPath(key)
|
hash, path := this.keyPath(key)
|
||||||
err := this.removeCacheFile(path)
|
err := this.removeCacheFile(path)
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"github.com/iwind/TeaGo/Tea"
|
"github.com/iwind/TeaGo/Tea"
|
||||||
_ "github.com/iwind/TeaGo/bootstrap"
|
_ "github.com/iwind/TeaGo/bootstrap"
|
||||||
"github.com/iwind/TeaGo/logs"
|
"github.com/iwind/TeaGo/logs"
|
||||||
"io/ioutil"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -152,7 +152,7 @@ func TestFileStorage_OpenWriter_HTTP(t *testing.T) {
|
|||||||
"Last-Modified": []string{"Wed, 06 Jan 2021 10:03:29 GMT"},
|
"Last-Modified": []string{"Wed, 06 Jan 2021 10:03:29 GMT"},
|
||||||
"Server": []string{"CDN-Server"},
|
"Server": []string{"CDN-Server"},
|
||||||
},
|
},
|
||||||
Body: ioutil.NopCloser(bytes.NewBuffer([]byte("THIS IS HTTP BODY"))),
|
Body: io.NopCloser(bytes.NewBuffer([]byte("THIS IS HTTP BODY"))),
|
||||||
}
|
}
|
||||||
|
|
||||||
for k, v := range resp.Header {
|
for k, v := range resp.Header {
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ type StorageInterface interface {
|
|||||||
CleanAll() error
|
CleanAll() error
|
||||||
|
|
||||||
// Purge 批量删除缓存
|
// Purge 批量删除缓存
|
||||||
|
// urlType 值为file|dir
|
||||||
Purge(keys []string, urlType string) error
|
Purge(keys []string, urlType string) error
|
||||||
|
|
||||||
// Stop 停止缓存策略
|
// Stop 停止缓存策略
|
||||||
|
|||||||
@@ -95,7 +95,8 @@ func (this *MemoryStorage) Init() error {
|
|||||||
// 启动定时Flush memory to disk任务
|
// 启动定时Flush memory to disk任务
|
||||||
if this.parentStorage != nil {
|
if this.parentStorage != nil {
|
||||||
// TODO 应该根据磁盘性能决定线程数
|
// TODO 应该根据磁盘性能决定线程数
|
||||||
var threads = 1
|
// TODO 线程数应该可以在缓存策略和节点中设定
|
||||||
|
var threads = runtime.NumCPU()
|
||||||
|
|
||||||
for i := 0; i < threads; i++ {
|
for i := 0; i < threads; i++ {
|
||||||
goman.New(func() {
|
goman.New(func() {
|
||||||
@@ -267,8 +268,10 @@ func (this *MemoryStorage) Purge(keys []string, urlType string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// URL
|
||||||
for _, key := range keys {
|
for _, key := range keys {
|
||||||
err := this.Delete(key)
|
err := this.Delete(key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -436,16 +439,18 @@ func (this *MemoryStorage) startFlush() {
|
|||||||
if statCount == 100 {
|
if statCount == 100 {
|
||||||
statCount = 0
|
statCount = 0
|
||||||
|
|
||||||
loadStat, err := load.Avg()
|
if protectingLoadWhenDump {
|
||||||
if err == nil && loadStat != nil {
|
loadStat, err := load.Avg()
|
||||||
if loadStat.Load1 > 10 {
|
if err == nil && loadStat != nil {
|
||||||
writeDelayMS = 100
|
if loadStat.Load1 > 10 {
|
||||||
} else if loadStat.Load1 > 3 {
|
writeDelayMS = 100
|
||||||
writeDelayMS = 50
|
} else if loadStat.Load1 > 3 {
|
||||||
} else if loadStat.Load1 > 2 {
|
writeDelayMS = 50
|
||||||
writeDelayMS = 10
|
} else if loadStat.Load1 > 2 {
|
||||||
} else {
|
writeDelayMS = 10
|
||||||
writeDelayMS = 0
|
} else {
|
||||||
|
writeDelayMS = 0
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"runtime"
|
"runtime"
|
||||||
"runtime/debug"
|
"runtime/debug"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -304,3 +305,30 @@ func TestMemoryStorage_Stop(t *testing.T) {
|
|||||||
|
|
||||||
t.Log(len(m))
|
t.Log(len(m))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func BenchmarkValuesMap(b *testing.B) {
|
||||||
|
var m = map[uint64]*MemoryItem{}
|
||||||
|
var count = 1_000_000
|
||||||
|
for i := 0; i < count; i++ {
|
||||||
|
m[uint64(i)] = &MemoryItem{
|
||||||
|
ExpiresAt: time.Now().Unix(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.Log(len(m))
|
||||||
|
|
||||||
|
var locker = sync.Mutex{}
|
||||||
|
b.ResetTimer()
|
||||||
|
|
||||||
|
b.RunParallel(func(pb *testing.PB) {
|
||||||
|
for pb.Next() {
|
||||||
|
locker.Lock()
|
||||||
|
_, ok := m[uint64(rands.Int(0, 1_000_000))]
|
||||||
|
_ = ok
|
||||||
|
locker.Unlock()
|
||||||
|
|
||||||
|
locker.Lock()
|
||||||
|
delete(m, uint64(rands.Int(2, 1000000)))
|
||||||
|
locker.Unlock()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ package caches_test
|
|||||||
import (
|
import (
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/caches"
|
"github.com/TeaOSLab/EdgeNode/internal/caches"
|
||||||
"github.com/iwind/TeaGo/types"
|
"github.com/iwind/TeaGo/types"
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
"os"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -16,7 +15,7 @@ func TestPartialFileWriter_Write(t *testing.T) {
|
|||||||
_ = os.Remove(path)
|
_ = os.Remove(path)
|
||||||
|
|
||||||
var reader = func() {
|
var reader = func() {
|
||||||
data, err := ioutil.ReadFile(path)
|
data, err := os.ReadFile(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
package compressions
|
package compressions
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"compress/gzip"
|
"github.com/klauspost/compress/gzip"
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
package compressions
|
package compressions
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
@@ -10,6 +11,10 @@ import (
|
|||||||
var sharedBrotliReaderPool *ReaderPool
|
var sharedBrotliReaderPool *ReaderPool
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
if teaconst.IsDaemon {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var maxSize = utils.SystemMemoryGB() * 256
|
var maxSize = utils.SystemMemoryGB() * 256
|
||||||
if maxSize == 0 {
|
if maxSize == 0 {
|
||||||
maxSize = 256
|
maxSize = 256
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
package compressions
|
package compressions
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
@@ -10,6 +11,10 @@ import (
|
|||||||
var sharedDeflateReaderPool *ReaderPool
|
var sharedDeflateReaderPool *ReaderPool
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
if teaconst.IsDaemon {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var maxSize = utils.SystemMemoryGB() * 256
|
var maxSize = utils.SystemMemoryGB() * 256
|
||||||
if maxSize == 0 {
|
if maxSize == 0 {
|
||||||
maxSize = 256
|
maxSize = 256
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
package compressions
|
package compressions
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
@@ -10,6 +11,10 @@ import (
|
|||||||
var sharedGzipReaderPool *ReaderPool
|
var sharedGzipReaderPool *ReaderPool
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
if teaconst.IsDaemon {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var maxSize = utils.SystemMemoryGB() * 256
|
var maxSize = utils.SystemMemoryGB() * 256
|
||||||
if maxSize == 0 {
|
if maxSize == 0 {
|
||||||
maxSize = 256
|
maxSize = 256
|
||||||
|
|||||||
25
internal/compressions/reader_pool_zstd.go
Normal file
25
internal/compressions/reader_pool_zstd.go
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
|
||||||
|
package compressions
|
||||||
|
|
||||||
|
import (
|
||||||
|
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
var sharedZSTDReaderPool *ReaderPool
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
if teaconst.IsDaemon {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var maxSize = utils.SystemMemoryGB() * 256
|
||||||
|
if maxSize == 0 {
|
||||||
|
maxSize = 256
|
||||||
|
}
|
||||||
|
sharedZSTDReaderPool = NewReaderPool(maxSize, func(reader io.Reader) (Reader, error) {
|
||||||
|
return newZSTDReader(reader)
|
||||||
|
})
|
||||||
|
}
|
||||||
45
internal/compressions/reader_zstd.go
Normal file
45
internal/compressions/reader_zstd.go
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
|
||||||
|
package compressions
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/klauspost/compress/zstd"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ZSTDReader struct {
|
||||||
|
BaseReader
|
||||||
|
|
||||||
|
reader *zstd.Decoder
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewZSTDReader(reader io.Reader) (Reader, error) {
|
||||||
|
return sharedZSTDReaderPool.Get(reader)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newZSTDReader(reader io.Reader) (Reader, error) {
|
||||||
|
r, err := zstd.NewReader(reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &ZSTDReader{
|
||||||
|
reader: r,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *ZSTDReader) Read(p []byte) (n int, err error) {
|
||||||
|
return this.reader.Read(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *ZSTDReader) Reset(reader io.Reader) error {
|
||||||
|
return this.reader.Reset(reader)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *ZSTDReader) RawClose() error {
|
||||||
|
this.reader.Close()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *ZSTDReader) Close() error {
|
||||||
|
return this.Finish(this)
|
||||||
|
}
|
||||||
106
internal/compressions/reader_zstd_test.go
Normal file
106
internal/compressions/reader_zstd_test.go
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
|
||||||
|
package compressions_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/compressions"
|
||||||
|
"github.com/iwind/TeaGo/rands"
|
||||||
|
"github.com/iwind/TeaGo/types"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestZSTDReader(t *testing.T) {
|
||||||
|
for _, testString := range []string{"Hello", "World", "Ni", "Hao"} {
|
||||||
|
t.Log("===", testString, "===")
|
||||||
|
var buf = &bytes.Buffer{}
|
||||||
|
writer, err := compressions.NewZSTDWriter(buf, 5)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err = writer.Write([]byte(testString))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
err = writer.Close()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
reader, err := compressions.NewZSTDReader(buf)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var data = make([]byte, 4096)
|
||||||
|
for {
|
||||||
|
n, err := reader.Read(data)
|
||||||
|
if n > 0 {
|
||||||
|
t.Log(string(data[:n]))
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
if err == io.EOF {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err = reader.Close()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkZSTDReader(b *testing.B) {
|
||||||
|
var randomData = func() []byte {
|
||||||
|
var b = strings.Builder{}
|
||||||
|
for i := 0; i < 1024; i++ {
|
||||||
|
b.WriteString(types.String(rands.Int64() % 10))
|
||||||
|
}
|
||||||
|
return []byte(b.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
var buf = &bytes.Buffer{}
|
||||||
|
writer, err := compressions.NewZSTDWriter(buf, 5)
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err = writer.Write(randomData())
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
err = writer.Close()
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
b.ResetTimer()
|
||||||
|
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
var newBytes = make([]byte, buf.Len())
|
||||||
|
copy(newBytes, buf.Bytes())
|
||||||
|
reader, err := compressions.NewZSTDReader(bytes.NewReader(newBytes))
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
var data = make([]byte, 4096)
|
||||||
|
for {
|
||||||
|
n, err := reader.Read(data)
|
||||||
|
if n > 0 {
|
||||||
|
_ = data[:n]
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
if err == io.EOF {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err = reader.Close()
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,13 +14,19 @@ const (
|
|||||||
ContentEncodingBr ContentEncoding = "br"
|
ContentEncodingBr ContentEncoding = "br"
|
||||||
ContentEncodingGzip ContentEncoding = "gzip"
|
ContentEncodingGzip ContentEncoding = "gzip"
|
||||||
ContentEncodingDeflate ContentEncoding = "deflate"
|
ContentEncodingDeflate ContentEncoding = "deflate"
|
||||||
|
ContentEncodingZSTD ContentEncoding = "zstd"
|
||||||
)
|
)
|
||||||
|
|
||||||
var ErrNotSupportedContentEncoding = errors.New("not supported content encoding")
|
var ErrNotSupportedContentEncoding = errors.New("not supported content encoding")
|
||||||
|
|
||||||
// AllEncodings 当前支持的所有编码
|
// AllEncodings 当前支持的所有编码
|
||||||
func AllEncodings() []ContentEncoding {
|
func AllEncodings() []ContentEncoding {
|
||||||
return []ContentEncoding{ContentEncodingBr, ContentEncodingGzip, ContentEncodingDeflate}
|
return []ContentEncoding{
|
||||||
|
ContentEncodingBr,
|
||||||
|
ContentEncodingGzip,
|
||||||
|
ContentEncodingZSTD,
|
||||||
|
ContentEncodingDeflate,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewReader 获取Reader
|
// NewReader 获取Reader
|
||||||
@@ -32,6 +38,8 @@ func NewReader(reader io.Reader, contentEncoding ContentEncoding) (Reader, error
|
|||||||
return NewGzipReader(reader)
|
return NewGzipReader(reader)
|
||||||
case ContentEncodingDeflate:
|
case ContentEncodingDeflate:
|
||||||
return NewDeflateReader(reader)
|
return NewDeflateReader(reader)
|
||||||
|
case ContentEncodingZSTD:
|
||||||
|
return NewZSTDReader(reader)
|
||||||
}
|
}
|
||||||
return nil, ErrNotSupportedContentEncoding
|
return nil, ErrNotSupportedContentEncoding
|
||||||
}
|
}
|
||||||
@@ -45,6 +53,8 @@ func NewWriter(writer io.Writer, compressType serverconfigs.HTTPCompressionType,
|
|||||||
return NewDeflateWriter(writer, level)
|
return NewDeflateWriter(writer, level)
|
||||||
case serverconfigs.HTTPCompressionTypeBrotli:
|
case serverconfigs.HTTPCompressionTypeBrotli:
|
||||||
return NewBrotliWriter(writer, level)
|
return NewBrotliWriter(writer, level)
|
||||||
|
case serverconfigs.HTTPCompressionTypeZSTD:
|
||||||
|
return NewZSTDWriter(writer, level)
|
||||||
}
|
}
|
||||||
return nil, errors.New("invalid compression type '" + compressType + "'")
|
return nil, errors.New("invalid compression type '" + compressType + "'")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,46 @@ package compressions_test
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/compressions"
|
"github.com/TeaOSLab/EdgeNode/internal/compressions"
|
||||||
|
stringutil "github.com/iwind/TeaGo/utils/string"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestBrotliWriter_LargeFile(t *testing.T) {
|
||||||
|
var data = []byte{}
|
||||||
|
for i := 0; i < 1024*1024; i++ {
|
||||||
|
data = append(data, stringutil.Rand(32)...)
|
||||||
|
}
|
||||||
|
t.Log(len(data)/1024/1024, "M")
|
||||||
|
|
||||||
|
var before = time.Now()
|
||||||
|
defer func() {
|
||||||
|
t.Log(time.Since(before).Seconds()*1000, "ms")
|
||||||
|
}()
|
||||||
|
|
||||||
|
var buf = &bytes.Buffer{}
|
||||||
|
writer, err := compressions.NewBrotliWriter(buf, 5)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var offset = 0
|
||||||
|
var size = 4096
|
||||||
|
for offset < len(data) {
|
||||||
|
_, err = writer.Write(data[offset : offset+size])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
offset += size
|
||||||
|
}
|
||||||
|
|
||||||
|
err = writer.Close()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func BenchmarkBrotliWriter_Write(b *testing.B) {
|
func BenchmarkBrotliWriter_Write(b *testing.B) {
|
||||||
var data = []byte(strings.Repeat("A", 1024))
|
var data = []byte(strings.Repeat("A", 1024))
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
package compressions
|
package compressions
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"compress/gzip"
|
"github.com/klauspost/compress/gzip"
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -34,3 +34,31 @@ func BenchmarkGzipWriter_Write(b *testing.B) {
|
|||||||
_ = writer.Close()
|
_ = writer.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func BenchmarkGzipWriter_Write_Parallel(b *testing.B) {
|
||||||
|
var data = []byte(strings.Repeat("A", 1024))
|
||||||
|
|
||||||
|
b.RunParallel(func(pb *testing.PB) {
|
||||||
|
for pb.Next() {
|
||||||
|
var buf = &bytes.Buffer{}
|
||||||
|
writer, err := compressions.NewGzipWriter(buf, 5)
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for j := 0; j < 100; j++ {
|
||||||
|
_, err = writer.Write(data)
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**err = writer.Flush()
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}**/
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = writer.Close()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
package compressions
|
package compressions
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
||||||
"github.com/andybalholm/brotli"
|
"github.com/andybalholm/brotli"
|
||||||
"io"
|
"io"
|
||||||
@@ -11,6 +12,10 @@ import (
|
|||||||
var sharedBrotliWriterPool *WriterPool
|
var sharedBrotliWriterPool *WriterPool
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
if teaconst.IsDaemon {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var maxSize = utils.SystemMemoryGB() * 256
|
var maxSize = utils.SystemMemoryGB() * 256
|
||||||
if maxSize == 0 {
|
if maxSize == 0 {
|
||||||
maxSize = 256
|
maxSize = 256
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ package compressions
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"compress/flate"
|
"compress/flate"
|
||||||
|
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
@@ -11,6 +12,10 @@ import (
|
|||||||
var sharedDeflateWriterPool *WriterPool
|
var sharedDeflateWriterPool *WriterPool
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
if teaconst.IsDaemon {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var maxSize = utils.SystemMemoryGB() * 256
|
var maxSize = utils.SystemMemoryGB() * 256
|
||||||
if maxSize == 0 {
|
if maxSize == 0 {
|
||||||
maxSize = 256
|
maxSize = 256
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ package compressions
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"compress/gzip"
|
"compress/gzip"
|
||||||
|
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
@@ -11,6 +12,10 @@ import (
|
|||||||
var sharedGzipWriterPool *WriterPool
|
var sharedGzipWriterPool *WriterPool
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
if teaconst.IsDaemon {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var maxSize = utils.SystemMemoryGB() * 256
|
var maxSize = utils.SystemMemoryGB() * 256
|
||||||
if maxSize == 0 {
|
if maxSize == 0 {
|
||||||
maxSize = 256
|
maxSize = 256
|
||||||
|
|||||||
26
internal/compressions/writer_pool_zstd.go
Normal file
26
internal/compressions/writer_pool_zstd.go
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
|
||||||
|
package compressions
|
||||||
|
|
||||||
|
import (
|
||||||
|
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
||||||
|
"github.com/klauspost/compress/zstd"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
var sharedZSTDWriterPool *WriterPool
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
if teaconst.IsDaemon {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var maxSize = utils.SystemMemoryGB() * 256
|
||||||
|
if maxSize == 0 {
|
||||||
|
maxSize = 256
|
||||||
|
}
|
||||||
|
sharedZSTDWriterPool = NewWriterPool(maxSize, int(zstd.SpeedBestCompression), func(writer io.Writer, level int) (Writer, error) {
|
||||||
|
return newZSTDWriter(writer, level)
|
||||||
|
})
|
||||||
|
}
|
||||||
57
internal/compressions/writer_zstd.go
Normal file
57
internal/compressions/writer_zstd.go
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
|
||||||
|
package compressions
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/klauspost/compress/zstd"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ZSTDWriter struct {
|
||||||
|
BaseWriter
|
||||||
|
|
||||||
|
writer *zstd.Encoder
|
||||||
|
level int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewZSTDWriter(writer io.Writer, level int) (Writer, error) {
|
||||||
|
return sharedZSTDWriterPool.Get(writer, level)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newZSTDWriter(writer io.Writer, level int) (Writer, error) {
|
||||||
|
var zstdLevel = zstd.EncoderLevelFromZstd(level)
|
||||||
|
|
||||||
|
zstdWriter, err := zstd.NewWriter(writer, zstd.WithEncoderLevel(zstdLevel))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &ZSTDWriter{
|
||||||
|
writer: zstdWriter,
|
||||||
|
level: level,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *ZSTDWriter) Write(p []byte) (int, error) {
|
||||||
|
return this.writer.Write(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *ZSTDWriter) Flush() error {
|
||||||
|
return this.writer.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *ZSTDWriter) Reset(writer io.Writer) {
|
||||||
|
this.writer.Reset(writer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *ZSTDWriter) RawClose() error {
|
||||||
|
return this.writer.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *ZSTDWriter) Close() error {
|
||||||
|
return this.Finish(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *ZSTDWriter) Level() int {
|
||||||
|
return this.level
|
||||||
|
}
|
||||||
82
internal/compressions/writer_zstd_test.go
Normal file
82
internal/compressions/writer_zstd_test.go
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
|
||||||
|
package compressions_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/compressions"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNewZSTDWriter(t *testing.T) {
|
||||||
|
var buf = &bytes.Buffer{}
|
||||||
|
writer, err := compressions.NewZSTDWriter(buf, 10)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var originData = []byte(strings.Repeat("Hello", 1024))
|
||||||
|
_, err = writer.Write(originData)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
err = writer.Close()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log("origin data:", len(originData), "result:", buf.Len())
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkZSTDWriter_Write(b *testing.B) {
|
||||||
|
var data = []byte(strings.Repeat("A", 1024))
|
||||||
|
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
var buf = &bytes.Buffer{}
|
||||||
|
writer, err := compressions.NewZSTDWriter(buf, 5)
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for j := 0; j < 100; j++ {
|
||||||
|
_, err = writer.Write(data)
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**err = writer.Flush()
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}**/
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = writer.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkZSTDWriter_Write_Parallel(b *testing.B) {
|
||||||
|
var data = []byte(strings.Repeat("A", 1024))
|
||||||
|
|
||||||
|
b.RunParallel(func(pb *testing.PB) {
|
||||||
|
for pb.Next() {
|
||||||
|
var buf = &bytes.Buffer{}
|
||||||
|
writer, err := compressions.NewZSTDWriter(buf, 5)
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for j := 0; j < 100; j++ {
|
||||||
|
_, err = writer.Write(data)
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**err = writer.Flush()
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}**/
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = writer.Close()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -3,20 +3,21 @@ package configs
|
|||||||
import (
|
import (
|
||||||
"github.com/iwind/TeaGo/Tea"
|
"github.com/iwind/TeaGo/Tea"
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
"io/ioutil"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
// APIConfig 节点API配置
|
// APIConfig 节点API配置
|
||||||
type APIConfig struct {
|
type APIConfig struct {
|
||||||
RPC struct {
|
RPC struct {
|
||||||
Endpoints []string `yaml:"endpoints"`
|
Endpoints []string `yaml:"endpoints"`
|
||||||
|
DisableUpdate bool `yaml:"disableUpdate"`
|
||||||
} `yaml:"rpc"`
|
} `yaml:"rpc"`
|
||||||
NodeId string `yaml:"nodeId"`
|
NodeId string `yaml:"nodeId"`
|
||||||
Secret string `yaml:"secret"`
|
Secret string `yaml:"secret"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func LoadAPIConfig() (*APIConfig, error) {
|
func LoadAPIConfig() (*APIConfig, error) {
|
||||||
data, err := ioutil.ReadFile(Tea.ConfigFile("api.yaml"))
|
data, err := os.ReadFile(Tea.ConfigFile("api.yaml"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -30,12 +31,12 @@ func LoadAPIConfig() (*APIConfig, error) {
|
|||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// 保存到文件
|
// WriteFile 保存到文件
|
||||||
func (this *APIConfig) WriteFile(path string) error {
|
func (this *APIConfig) WriteFile(path string) error {
|
||||||
data, err := yaml.Marshal(this)
|
data, err := yaml.Marshal(this)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
err = ioutil.WriteFile(path, data, 0666)
|
err = os.WriteFile(path, data, 0666)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
package configs
|
package configs_test
|
||||||
|
|
||||||
import "testing"
|
import (
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/configs"
|
||||||
|
_ "github.com/iwind/TeaGo/bootstrap"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
func TestLoadAPIConfig(t *testing.T) {
|
func TestLoadAPIConfig(t *testing.T) {
|
||||||
config, err := LoadAPIConfig()
|
config, err := configs.LoadAPIConfig()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
t.Log(config)
|
t.Logf("%+v", config)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
package configs
|
package configs
|
||||||
|
|
||||||
// 集群配置
|
// ClusterConfig 集群配置
|
||||||
type ClusterConfig struct {
|
type ClusterConfig struct {
|
||||||
RPC struct {
|
RPC struct {
|
||||||
Endpoints []string `yaml:"endpoints"`
|
Endpoints []string `yaml:"endpoints"`
|
||||||
|
DisableUpdate bool `yaml:"disableUpdate"`
|
||||||
} `yaml:"rpc"`
|
} `yaml:"rpc"`
|
||||||
ClusterId string `yaml:"clusterId"`
|
ClusterId string `yaml:"clusterId"`
|
||||||
Secret string `yaml:"secret"`
|
Secret string `yaml:"secret"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
//go:build community
|
//go:build !plus
|
||||||
// +build community
|
// +build !plus
|
||||||
|
|
||||||
package teaconst
|
package teaconst
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
package teaconst
|
package teaconst
|
||||||
|
|
||||||
const (
|
const (
|
||||||
Version = "0.4.7"
|
Version = "0.5.0"
|
||||||
|
|
||||||
ProductName = "Edge Node"
|
ProductName = "Edge Node"
|
||||||
ProcessName = "edge-node"
|
ProcessName = "edge-node"
|
||||||
@@ -13,4 +13,6 @@ const (
|
|||||||
|
|
||||||
// SystemdServiceName systemd
|
// SystemdServiceName systemd
|
||||||
SystemdServiceName = "edge-node"
|
SystemdServiceName = "edge-node"
|
||||||
|
|
||||||
|
AccessLogSockName = "edge-node.accesslog.sock"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,7 +2,10 @@
|
|||||||
|
|
||||||
package teaconst
|
package teaconst
|
||||||
|
|
||||||
import "github.com/TeaOSLab/EdgeCommon/pkg/nodeconfigs"
|
import (
|
||||||
|
"github.com/TeaOSLab/EdgeCommon/pkg/nodeconfigs"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
// 流量统计
|
// 流量统计
|
||||||
@@ -12,6 +15,7 @@ var (
|
|||||||
|
|
||||||
NodeId int64 = 0
|
NodeId int64 = 0
|
||||||
NodeIdString = ""
|
NodeIdString = ""
|
||||||
|
IsDaemon = len(os.Args) > 1 && os.Args[1] == "daemon"
|
||||||
|
|
||||||
GlobalProductName = nodeconfigs.DefaultProductName
|
GlobalProductName = nodeconfigs.DefaultProductName
|
||||||
|
|
||||||
|
|||||||
@@ -3,9 +3,10 @@ package events
|
|||||||
type Event = string
|
type Event = string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
EventStart Event = "start" // start loading
|
EventStart Event = "start" // start loading
|
||||||
EventLoaded Event = "loaded" // first load
|
EventLoaded Event = "loaded" // first load
|
||||||
EventQuit Event = "quit" // quit node gracefully
|
EventQuit Event = "quit" // quit node gracefully
|
||||||
EventReload Event = "reload" // reload config
|
EventReload Event = "reload" // reload config
|
||||||
EventTerminated Event = "terminated" // process terminated
|
EventTerminated Event = "terminated" // process terminated
|
||||||
|
EventNFTablesReady Event = "nftablesReady" // nftables ready
|
||||||
)
|
)
|
||||||
|
|||||||
1
internal/firewalls/.gitignore
vendored
1
internal/firewalls/.gitignore
vendored
@@ -1 +0,0 @@
|
|||||||
firewall_nftables_test.go
|
|
||||||
502
internal/firewalls/ddos_protection.go
Normal file
502
internal/firewalls/ddos_protection.go
Normal file
@@ -0,0 +1,502 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
//go:build linux
|
||||||
|
// +build linux
|
||||||
|
|
||||||
|
package firewalls
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"github.com/TeaOSLab/EdgeCommon/pkg/nodeconfigs"
|
||||||
|
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/ddosconfigs"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/events"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/firewalls/nftables"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/zero"
|
||||||
|
"github.com/iwind/TeaGo/lists"
|
||||||
|
"github.com/iwind/TeaGo/types"
|
||||||
|
stringutil "github.com/iwind/TeaGo/utils/string"
|
||||||
|
"net"
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
var SharedDDoSProtectionManager = NewDDoSProtectionManager()
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
events.On(events.EventReload, func() {
|
||||||
|
if nftablesInstance == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
nodeConfig, _ := nodeconfigs.SharedNodeConfig()
|
||||||
|
if nodeConfig != nil {
|
||||||
|
err := SharedDDoSProtectionManager.Apply(nodeConfig.DDoSProtection)
|
||||||
|
if err != nil {
|
||||||
|
remotelogs.Error("FIREWALL", "apply DDoS protection failed: "+err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
events.On(events.EventNFTablesReady, func() {
|
||||||
|
nodeConfig, _ := nodeconfigs.SharedNodeConfig()
|
||||||
|
if nodeConfig != nil {
|
||||||
|
err := SharedDDoSProtectionManager.Apply(nodeConfig.DDoSProtection)
|
||||||
|
if err != nil {
|
||||||
|
remotelogs.Error("FIREWALL", "apply DDoS protection failed: "+err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// DDoSProtectionManager DDoS防护
|
||||||
|
type DDoSProtectionManager struct {
|
||||||
|
nftPath string
|
||||||
|
|
||||||
|
lastAllowIPList []string
|
||||||
|
lastConfig []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewDDoSProtectionManager 获取新对象
|
||||||
|
func NewDDoSProtectionManager() *DDoSProtectionManager {
|
||||||
|
nftPath, _ := exec.LookPath("nft")
|
||||||
|
|
||||||
|
return &DDoSProtectionManager{
|
||||||
|
nftPath: nftPath,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply 应用配置
|
||||||
|
func (this *DDoSProtectionManager) Apply(config *ddosconfigs.ProtectionConfig) error {
|
||||||
|
// 同集群节点IP白名单
|
||||||
|
var allowIPListChanged = false
|
||||||
|
nodeConfig, _ := nodeconfigs.SharedNodeConfig()
|
||||||
|
if nodeConfig != nil {
|
||||||
|
var allowIPList = nodeConfig.AllowedIPs
|
||||||
|
if !utils.ContainsSameStrings(allowIPList, this.lastAllowIPList) {
|
||||||
|
allowIPListChanged = true
|
||||||
|
this.lastAllowIPList = allowIPList
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 对比配置
|
||||||
|
configJSON, err := json.Marshal(config)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("encode config to json failed: " + err.Error())
|
||||||
|
}
|
||||||
|
if !allowIPListChanged && bytes.Equal(this.lastConfig, configJSON) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
remotelogs.Println("FIREWALL", "change DDoS protection config")
|
||||||
|
|
||||||
|
if len(this.nftPath) == 0 {
|
||||||
|
return errors.New("can not find nft command")
|
||||||
|
}
|
||||||
|
|
||||||
|
if nftablesInstance == nil {
|
||||||
|
return errors.New("nftables instance should not be nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
if config == nil {
|
||||||
|
// TCP
|
||||||
|
err := this.removeTCPRules()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO other protocols
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TCP
|
||||||
|
if config.TCP == nil {
|
||||||
|
err := this.removeTCPRules()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// allow ip list
|
||||||
|
var allowIPList = []string{}
|
||||||
|
for _, ipConfig := range config.TCP.AllowIPList {
|
||||||
|
allowIPList = append(allowIPList, ipConfig.IP)
|
||||||
|
}
|
||||||
|
for _, ip := range this.lastAllowIPList {
|
||||||
|
if !lists.ContainsString(allowIPList, ip) {
|
||||||
|
allowIPList = append(allowIPList, ip)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err = this.updateAllowIPList(allowIPList)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// tcp
|
||||||
|
if config.TCP.IsOn {
|
||||||
|
err := this.addTCPRules(config.TCP)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
err := this.removeTCPRules()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.lastConfig = configJSON
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加TCP规则
|
||||||
|
func (this *DDoSProtectionManager) addTCPRules(tcpConfig *ddosconfigs.TCPConfig) error {
|
||||||
|
// 检查nft版本不能小于0.9
|
||||||
|
if len(nftablesInstance.version) > 0 && stringutil.VersionCompare("0.9", nftablesInstance.version) > 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var ports = []int32{}
|
||||||
|
for _, portConfig := range tcpConfig.Ports {
|
||||||
|
if !lists.ContainsInt32(ports, portConfig.Port) {
|
||||||
|
ports = append(ports, portConfig.Port)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(ports) == 0 {
|
||||||
|
ports = []int32{80, 443}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, filter := range nftablesFilters {
|
||||||
|
chain, oldRules, err := this.getRules(filter)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("get old rules failed: " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
var protocol = filter.protocol()
|
||||||
|
|
||||||
|
// max connections
|
||||||
|
var maxConnections = tcpConfig.MaxConnections
|
||||||
|
if maxConnections <= 0 {
|
||||||
|
maxConnections = nodeconfigs.DefaultTCPMaxConnections
|
||||||
|
if maxConnections <= 0 {
|
||||||
|
maxConnections = 100000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// max connections per ip
|
||||||
|
var maxConnectionsPerIP = tcpConfig.MaxConnectionsPerIP
|
||||||
|
if maxConnectionsPerIP <= 0 {
|
||||||
|
maxConnectionsPerIP = nodeconfigs.DefaultTCPMaxConnectionsPerIP
|
||||||
|
if maxConnectionsPerIP <= 0 {
|
||||||
|
maxConnectionsPerIP = 100000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// new connections rate
|
||||||
|
var newConnectionsRate = tcpConfig.NewConnectionsRate
|
||||||
|
if newConnectionsRate <= 0 {
|
||||||
|
newConnectionsRate = nodeconfigs.DefaultTCPNewConnectionsRate
|
||||||
|
if newConnectionsRate <= 0 {
|
||||||
|
newConnectionsRate = 100000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否有变化
|
||||||
|
var hasChanges = false
|
||||||
|
for _, port := range ports {
|
||||||
|
if !this.existsRule(oldRules, []string{"tcp", types.String(port), "maxConnections", types.String(maxConnections)}) {
|
||||||
|
hasChanges = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if !this.existsRule(oldRules, []string{"tcp", types.String(port), "maxConnectionsPerIP", types.String(maxConnectionsPerIP)}) {
|
||||||
|
hasChanges = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if !this.existsRule(oldRules, []string{"tcp", types.String(port), "newConnectionsRate", types.String(newConnectionsRate)}) {
|
||||||
|
hasChanges = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !hasChanges {
|
||||||
|
// 检查是否有多余的端口
|
||||||
|
var oldPorts = this.getTCPPorts(oldRules)
|
||||||
|
if !this.eqPorts(ports, oldPorts) {
|
||||||
|
hasChanges = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !hasChanges {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 先清空所有相关规则
|
||||||
|
err = this.removeOldTCPRules(chain, oldRules)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("delete old rules failed: " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加新规则
|
||||||
|
for _, port := range ports {
|
||||||
|
if maxConnections > 0 {
|
||||||
|
var cmd = exec.Command(this.nftPath, "add", "rule", protocol, filter.Name, nftablesChainName, "tcp", "dport", types.String(port), "ct", "count", "over", types.String(maxConnections), "counter", "drop", "comment", this.encodeUserData([]string{"tcp", types.String(port), "maxConnections", types.String(maxConnections)}))
|
||||||
|
var stderr = &bytes.Buffer{}
|
||||||
|
cmd.Stderr = stderr
|
||||||
|
err := cmd.Run()
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("add nftables rule '" + cmd.String() + "' failed: " + err.Error() + " (" + stderr.String() + ")")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if maxConnectionsPerIP > 0 {
|
||||||
|
var cmd = exec.Command(this.nftPath, "add", "rule", protocol, filter.Name, nftablesChainName, "tcp", "dport", types.String(port), "meter", "meter-"+protocol+"-"+types.String(port)+"-max-connections", "{ "+protocol+" saddr ct count over "+types.String(maxConnectionsPerIP)+" }", "counter", "drop", "comment", this.encodeUserData([]string{"tcp", types.String(port), "maxConnectionsPerIP", types.String(maxConnectionsPerIP)}))
|
||||||
|
var stderr = &bytes.Buffer{}
|
||||||
|
cmd.Stderr = stderr
|
||||||
|
err := cmd.Run()
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("add nftables rule '" + cmd.String() + "' failed: " + err.Error() + " (" + stderr.String() + ")")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if newConnectionsRate > 0 {
|
||||||
|
// TODO 思考是否有惩罚机制
|
||||||
|
var cmd = exec.Command(this.nftPath, "add", "rule", protocol, filter.Name, nftablesChainName, "tcp", "dport", types.String(port), "ct", "state", "new", "meter", "meter-"+protocol+"-"+types.String(port)+"-new-connections-rate", "{ "+protocol+" saddr limit rate over "+types.String(newConnectionsRate)+"/minute burst "+types.String(newConnectionsRate+3)+" packets }" /**"add", "@deny_set", "{"+protocol+" saddr}",**/, "counter", "drop", "comment", this.encodeUserData([]string{"tcp", types.String(port), "newConnectionsRate", types.String(newConnectionsRate)}))
|
||||||
|
var stderr = &bytes.Buffer{}
|
||||||
|
cmd.Stderr = stderr
|
||||||
|
err := cmd.Run()
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("add nftables rule '" + cmd.String() + "' failed: " + err.Error() + " (" + stderr.String() + ")")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 删除TCP规则
|
||||||
|
func (this *DDoSProtectionManager) removeTCPRules() error {
|
||||||
|
for _, filter := range nftablesFilters {
|
||||||
|
chain, rules, err := this.getRules(filter)
|
||||||
|
|
||||||
|
// TCP
|
||||||
|
err = this.removeOldTCPRules(chain, rules)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 组合user data
|
||||||
|
// 数据中不能包含字母、数字、下划线以外的数据
|
||||||
|
func (this *DDoSProtectionManager) encodeUserData(attrs []string) string {
|
||||||
|
if attrs == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
return "ZZ" + strings.Join(attrs, "_") + "ZZ"
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解码user data
|
||||||
|
func (this *DDoSProtectionManager) decodeUserData(data []byte) []string {
|
||||||
|
if len(data) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var dataCopy = make([]byte, len(data))
|
||||||
|
copy(dataCopy, data)
|
||||||
|
|
||||||
|
var separatorLen = 2
|
||||||
|
var index1 = bytes.Index(dataCopy, []byte{'Z', 'Z'})
|
||||||
|
if index1 < 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
dataCopy = dataCopy[index1+separatorLen:]
|
||||||
|
var index2 = bytes.LastIndex(dataCopy, []byte{'Z', 'Z'})
|
||||||
|
if index2 < 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var s = string(dataCopy[:index2])
|
||||||
|
var pieces = strings.Split(s, "_")
|
||||||
|
for index, piece := range pieces {
|
||||||
|
pieces[index] = strings.TrimSpace(piece)
|
||||||
|
}
|
||||||
|
return pieces
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清除规则
|
||||||
|
func (this *DDoSProtectionManager) removeOldTCPRules(chain *nftables.Chain, rules []*nftables.Rule) error {
|
||||||
|
for _, rule := range rules {
|
||||||
|
var pieces = this.decodeUserData(rule.UserData())
|
||||||
|
if len(pieces) != 4 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if pieces[0] != "tcp" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
switch pieces[2] {
|
||||||
|
case "maxConnections", "maxConnectionsPerIP", "newConnectionsRate":
|
||||||
|
err := chain.DeleteRule(rule)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据参数检查规则是否存在
|
||||||
|
func (this *DDoSProtectionManager) existsRule(rules []*nftables.Rule, attrs []string) (exists bool) {
|
||||||
|
if len(attrs) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, oldRule := range rules {
|
||||||
|
var pieces = this.decodeUserData(oldRule.UserData())
|
||||||
|
if len(attrs) != len(pieces) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var isSame = true
|
||||||
|
for index, piece := range pieces {
|
||||||
|
if strings.TrimSpace(piece) != attrs[index] {
|
||||||
|
isSame = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if isSame {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取规则中的端口号
|
||||||
|
func (this *DDoSProtectionManager) getTCPPorts(rules []*nftables.Rule) []int32 {
|
||||||
|
var ports = []int32{}
|
||||||
|
for _, rule := range rules {
|
||||||
|
var pieces = this.decodeUserData(rule.UserData())
|
||||||
|
if len(pieces) != 4 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if pieces[0] != "tcp" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var port = types.Int32(pieces[1])
|
||||||
|
if port > 0 && !lists.ContainsInt32(ports, port) {
|
||||||
|
ports = append(ports, port)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ports
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查端口是否一样
|
||||||
|
func (this *DDoSProtectionManager) eqPorts(ports1 []int32, ports2 []int32) bool {
|
||||||
|
if len(ports1) != len(ports2) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
var portMap = map[int32]bool{}
|
||||||
|
for _, port := range ports2 {
|
||||||
|
portMap[port] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, port := range ports1 {
|
||||||
|
_, ok := portMap[port]
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查找Table
|
||||||
|
func (this *DDoSProtectionManager) getTable(filter *nftablesTableDefinition) (*nftables.Table, error) {
|
||||||
|
var family nftables.TableFamily
|
||||||
|
if filter.IsIPv4 {
|
||||||
|
family = nftables.TableFamilyIPv4
|
||||||
|
} else if filter.IsIPv6 {
|
||||||
|
family = nftables.TableFamilyIPv6
|
||||||
|
} else {
|
||||||
|
return nil, errors.New("table '" + filter.Name + "' should be IPv4 or IPv6")
|
||||||
|
}
|
||||||
|
return nftablesInstance.conn.GetTable(filter.Name, family)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查找所有规则
|
||||||
|
func (this *DDoSProtectionManager) getRules(filter *nftablesTableDefinition) (*nftables.Chain, []*nftables.Rule, error) {
|
||||||
|
table, err := this.getTable(filter)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, errors.New("get table failed: " + err.Error())
|
||||||
|
}
|
||||||
|
chain, err := table.GetChain(nftablesChainName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, errors.New("get chain failed: " + err.Error())
|
||||||
|
}
|
||||||
|
rules, err := chain.GetRules()
|
||||||
|
return chain, rules, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新白名单
|
||||||
|
func (this *DDoSProtectionManager) updateAllowIPList(allIPList []string) error {
|
||||||
|
if nftablesInstance == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var allMap = map[string]zero.Zero{}
|
||||||
|
for _, ip := range allIPList {
|
||||||
|
allMap[ip] = zero.New()
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, set := range []*nftables.Set{nftablesInstance.allowIPv4Set, nftablesInstance.allowIPv6Set} {
|
||||||
|
var isIPv4 = set == nftablesInstance.allowIPv4Set
|
||||||
|
var isIPv6 = !isIPv4
|
||||||
|
|
||||||
|
// 现有的
|
||||||
|
oldList, err := set.GetIPElements()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var oldMap = map[string]zero.Zero{} // ip=> zero
|
||||||
|
for _, ip := range oldList {
|
||||||
|
oldMap[ip] = zero.New()
|
||||||
|
|
||||||
|
if (utils.IsIPv4(ip) && isIPv4) || (utils.IsIPv6(ip) && isIPv6) {
|
||||||
|
_, ok := allMap[ip]
|
||||||
|
if !ok {
|
||||||
|
// 不存在则删除
|
||||||
|
err = set.DeleteIPElement(ip)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("delete ip element '" + ip + "' failed: " + err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 新增的
|
||||||
|
for _, ip := range allIPList {
|
||||||
|
var ipObj = net.ParseIP(ip)
|
||||||
|
if ipObj == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (utils.IsIPv4(ip) && isIPv4) || (utils.IsIPv6(ip) && isIPv6) {
|
||||||
|
_, ok := oldMap[ip]
|
||||||
|
if !ok {
|
||||||
|
// 不存在则添加
|
||||||
|
err = set.AddIPElement(ip, nil)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("add ip '" + ip + "' failed: " + err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
23
internal/firewalls/ddos_protection_others.go
Normal file
23
internal/firewalls/ddos_protection_others.go
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
//go:build !linux
|
||||||
|
// +build !linux
|
||||||
|
|
||||||
|
package firewalls
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/ddosconfigs"
|
||||||
|
)
|
||||||
|
|
||||||
|
var SharedDDoSProtectionManager = NewDDoSProtectionManager()
|
||||||
|
|
||||||
|
type DDoSProtectionManager struct {
|
||||||
|
nftPath string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDDoSProtectionManager() *DDoSProtectionManager {
|
||||||
|
return &DDoSProtectionManager{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *DDoSProtectionManager) Apply(config *ddosconfigs.ProtectionConfig) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -1,6 +1,4 @@
|
|||||||
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
//go:build !plus
|
|
||||||
// +build !plus
|
|
||||||
|
|
||||||
package firewalls
|
package firewalls
|
||||||
|
|
||||||
@@ -8,9 +6,11 @@ import (
|
|||||||
"github.com/TeaOSLab/EdgeNode/internal/events"
|
"github.com/TeaOSLab/EdgeNode/internal/events"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
|
"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
var currentFirewall FirewallInterface
|
var currentFirewall FirewallInterface
|
||||||
|
var firewallLocker = &sync.Mutex{}
|
||||||
|
|
||||||
// 初始化
|
// 初始化
|
||||||
func init() {
|
func init() {
|
||||||
@@ -24,10 +24,28 @@ func init() {
|
|||||||
|
|
||||||
// Firewall 查找当前系统中最适合的防火墙
|
// Firewall 查找当前系统中最适合的防火墙
|
||||||
func Firewall() FirewallInterface {
|
func Firewall() FirewallInterface {
|
||||||
|
firewallLocker.Lock()
|
||||||
|
defer firewallLocker.Unlock()
|
||||||
if currentFirewall != nil {
|
if currentFirewall != nil {
|
||||||
return currentFirewall
|
return currentFirewall
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// nftables
|
||||||
|
if runtime.GOOS == "linux" {
|
||||||
|
nftables, err := NewNFTablesFirewall()
|
||||||
|
if err != nil {
|
||||||
|
remotelogs.Warn("FIREWALL", "'nftables' should be installed on the system to enhance security (init failed: "+err.Error()+")")
|
||||||
|
} else {
|
||||||
|
if nftables.IsReady() {
|
||||||
|
currentFirewall = nftables
|
||||||
|
events.Notify(events.EventNFTablesReady)
|
||||||
|
return nftables
|
||||||
|
} else {
|
||||||
|
remotelogs.Warn("FIREWALL", "'nftables' should be enabled on the system to enhance security")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// firewalld
|
// firewalld
|
||||||
if runtime.GOOS == "linux" {
|
if runtime.GOOS == "linux" {
|
||||||
var firewalld = NewFirewalld()
|
var firewalld = NewFirewalld()
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
package firewalls
|
package firewalls
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/goman"
|
"github.com/TeaOSLab/EdgeNode/internal/goman"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
|
"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
|
||||||
"github.com/iwind/TeaGo/types"
|
"github.com/iwind/TeaGo/types"
|
||||||
@@ -23,12 +24,13 @@ func NewFirewalld() *Firewalld {
|
|||||||
|
|
||||||
path, err := exec.LookPath("firewall-cmd")
|
path, err := exec.LookPath("firewall-cmd")
|
||||||
if err == nil && len(path) > 0 {
|
if err == nil && len(path) > 0 {
|
||||||
var cmd = exec.Command(path, "-V")
|
var cmd = exec.Command(path, "--state")
|
||||||
err := cmd.Run()
|
err := cmd.Run()
|
||||||
if err == nil {
|
if err == nil {
|
||||||
firewalld.exe = path
|
firewalld.exe = path
|
||||||
// TODO check firewalld status with 'firewall-cmd --state' (running or not running),
|
// TODO check firewalld status with 'firewall-cmd --state' (running or not running),
|
||||||
// but we should recover the state when firewalld state changes, maybe check it every minutes
|
// but we should recover the state when firewalld state changes, maybe check it every minutes
|
||||||
|
|
||||||
firewalld.isReady = true
|
firewalld.isReady = true
|
||||||
firewalld.init()
|
firewalld.init()
|
||||||
}
|
}
|
||||||
@@ -74,6 +76,24 @@ func (this *Firewalld) AllowPort(port int, protocol string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (this *Firewalld) AllowPortRangesPermanently(portRanges [][2]int, protocol string) error {
|
||||||
|
for _, portRange := range portRanges {
|
||||||
|
var port = this.PortRangeString(portRange, protocol)
|
||||||
|
|
||||||
|
{
|
||||||
|
var cmd = exec.Command(this.exe, "--add-port="+port, "--permanent")
|
||||||
|
this.pushCmd(cmd)
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
var cmd = exec.Command(this.exe, "--add-port="+port)
|
||||||
|
this.pushCmd(cmd)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (this *Firewalld) RemovePort(port int, protocol string) error {
|
func (this *Firewalld) RemovePort(port int, protocol string) error {
|
||||||
if !this.isReady {
|
if !this.isReady {
|
||||||
return nil
|
return nil
|
||||||
@@ -83,6 +103,30 @@ func (this *Firewalld) RemovePort(port int, protocol string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (this *Firewalld) RemovePortRangePermanently(portRange [2]int, protocol string) error {
|
||||||
|
var port = this.PortRangeString(portRange, protocol)
|
||||||
|
|
||||||
|
{
|
||||||
|
var cmd = exec.Command(this.exe, "--remove-port="+port, "--permanent")
|
||||||
|
this.pushCmd(cmd)
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
var cmd = exec.Command(this.exe, "--remove-port="+port)
|
||||||
|
this.pushCmd(cmd)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Firewalld) PortRangeString(portRange [2]int, protocol string) string {
|
||||||
|
if portRange[0] == portRange[1] {
|
||||||
|
return types.String(portRange[0]) + "/" + protocol
|
||||||
|
} else {
|
||||||
|
return types.String(portRange[0]) + "-" + types.String(portRange[1]) + "/" + protocol
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (this *Firewalld) RejectSourceIP(ip string, timeoutSeconds int) error {
|
func (this *Firewalld) RejectSourceIP(ip string, timeoutSeconds int) error {
|
||||||
if !this.isReady {
|
if !this.isReady {
|
||||||
return nil
|
return nil
|
||||||
@@ -100,7 +144,7 @@ func (this *Firewalld) RejectSourceIP(ip string, timeoutSeconds int) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (this *Firewalld) DropSourceIP(ip string, timeoutSeconds int) error {
|
func (this *Firewalld) DropSourceIP(ip string, timeoutSeconds int, async bool) error {
|
||||||
if !this.isReady {
|
if !this.isReady {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -113,7 +157,15 @@ func (this *Firewalld) DropSourceIP(ip string, timeoutSeconds int) error {
|
|||||||
args = append(args, "--timeout="+types.String(timeoutSeconds)+"s")
|
args = append(args, "--timeout="+types.String(timeoutSeconds)+"s")
|
||||||
}
|
}
|
||||||
var cmd = exec.Command(this.exe, args...)
|
var cmd = exec.Command(this.exe, args...)
|
||||||
this.pushCmd(cmd)
|
if async {
|
||||||
|
this.pushCmd(cmd)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
err := cmd.Run()
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("run command failed '" + cmd.String() + "': " + err.Error())
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,10 @@ type FirewallInterface interface {
|
|||||||
RejectSourceIP(ip string, timeoutSeconds int) error
|
RejectSourceIP(ip string, timeoutSeconds int) error
|
||||||
|
|
||||||
// DropSourceIP 丢弃某个源IP数据
|
// DropSourceIP 丢弃某个源IP数据
|
||||||
DropSourceIP(ip string, timeoutSeconds int) error
|
// ip 要封禁的IP
|
||||||
|
// timeoutSeconds 过期时间
|
||||||
|
// async 是否异步
|
||||||
|
DropSourceIP(ip string, timeoutSeconds int, async bool) error
|
||||||
|
|
||||||
// RemoveSourceIP 删除某个源IP
|
// RemoveSourceIP 删除某个源IP
|
||||||
RemoveSourceIP(ip string) error
|
RemoveSourceIP(ip string) error
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ func (this *MockFirewall) RejectSourceIP(ip string, timeoutSeconds int) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DropSourceIP 丢弃某个源IP数据
|
// DropSourceIP 丢弃某个源IP数据
|
||||||
func (this *MockFirewall) DropSourceIP(ip string, timeoutSeconds int) error {
|
func (this *MockFirewall) DropSourceIP(ip string, timeoutSeconds int, async bool) error {
|
||||||
_ = ip
|
_ = ip
|
||||||
_ = timeoutSeconds
|
_ = timeoutSeconds
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
435
internal/firewalls/firewall_nftables.go
Normal file
435
internal/firewalls/firewall_nftables.go
Normal file
@@ -0,0 +1,435 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
//go:build linux
|
||||||
|
// +build linux
|
||||||
|
|
||||||
|
package firewalls
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/events"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/firewalls/nftables"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/goman"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
|
||||||
|
"github.com/iwind/TeaGo/types"
|
||||||
|
"net"
|
||||||
|
"os/exec"
|
||||||
|
"regexp"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// check nft status, if being enabled we load it automatically
|
||||||
|
func init() {
|
||||||
|
if teaconst.IsDaemon {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if runtime.GOOS == "linux" {
|
||||||
|
var ticker = time.NewTicker(3 * time.Minute)
|
||||||
|
goman.New(func() {
|
||||||
|
for range ticker.C {
|
||||||
|
// if already ready, we break
|
||||||
|
if nftablesIsReady {
|
||||||
|
ticker.Stop()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
_, err := exec.LookPath("nft")
|
||||||
|
if err == nil {
|
||||||
|
nftablesFirewall, err := NewNFTablesFirewall()
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
currentFirewall = nftablesFirewall
|
||||||
|
remotelogs.Println("FIREWALL", "nftables is ready")
|
||||||
|
|
||||||
|
// fire event
|
||||||
|
if nftablesFirewall.IsReady() {
|
||||||
|
events.Notify(events.EventNFTablesReady)
|
||||||
|
}
|
||||||
|
|
||||||
|
ticker.Stop()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var nftablesInstance *NFTablesFirewall
|
||||||
|
var nftablesIsReady = false
|
||||||
|
var nftablesFilters = []*nftablesTableDefinition{
|
||||||
|
// we shorten the name for table name length restriction
|
||||||
|
{Name: "edge_dft_v4", IsIPv4: true},
|
||||||
|
{Name: "edge_dft_v6", IsIPv6: true},
|
||||||
|
}
|
||||||
|
var nftablesChainName = "input"
|
||||||
|
|
||||||
|
type nftablesTableDefinition struct {
|
||||||
|
Name string
|
||||||
|
IsIPv4 bool
|
||||||
|
IsIPv6 bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *nftablesTableDefinition) protocol() string {
|
||||||
|
if this.IsIPv6 {
|
||||||
|
return "ip6"
|
||||||
|
}
|
||||||
|
return "ip"
|
||||||
|
}
|
||||||
|
|
||||||
|
type blockIPItem struct {
|
||||||
|
action string
|
||||||
|
ip string
|
||||||
|
timeoutSeconds int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewNFTablesFirewall() (*NFTablesFirewall, error) {
|
||||||
|
var firewall = &NFTablesFirewall{
|
||||||
|
conn: nftables.NewConn(),
|
||||||
|
dropIPQueue: make(chan *blockIPItem, 4096),
|
||||||
|
}
|
||||||
|
err := firewall.init()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return firewall, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type NFTablesFirewall struct {
|
||||||
|
conn *nftables.Conn
|
||||||
|
isReady bool
|
||||||
|
version string
|
||||||
|
|
||||||
|
allowIPv4Set *nftables.Set
|
||||||
|
allowIPv6Set *nftables.Set
|
||||||
|
|
||||||
|
denyIPv4Set *nftables.Set
|
||||||
|
denyIPv6Set *nftables.Set
|
||||||
|
|
||||||
|
firewalld *Firewalld
|
||||||
|
|
||||||
|
dropIPQueue chan *blockIPItem
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *NFTablesFirewall) init() error {
|
||||||
|
// check nft
|
||||||
|
nftPath, err := exec.LookPath("nft")
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("nft not found")
|
||||||
|
}
|
||||||
|
this.version = this.readVersion(nftPath)
|
||||||
|
|
||||||
|
// table
|
||||||
|
for _, tableDef := range nftablesFilters {
|
||||||
|
var family nftables.TableFamily
|
||||||
|
if tableDef.IsIPv4 {
|
||||||
|
family = nftables.TableFamilyIPv4
|
||||||
|
} else if tableDef.IsIPv6 {
|
||||||
|
family = nftables.TableFamilyIPv6
|
||||||
|
} else {
|
||||||
|
return errors.New("invalid table family: " + types.String(tableDef))
|
||||||
|
}
|
||||||
|
table, err := this.conn.GetTable(tableDef.Name, family)
|
||||||
|
if err != nil {
|
||||||
|
if nftables.IsNotFound(err) {
|
||||||
|
if tableDef.IsIPv4 {
|
||||||
|
table, err = this.conn.AddIPv4Table(tableDef.Name)
|
||||||
|
} else if tableDef.IsIPv6 {
|
||||||
|
table, err = this.conn.AddIPv6Table(tableDef.Name)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("create table '" + tableDef.Name + "' failed: " + err.Error())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return errors.New("get table '" + tableDef.Name + "' failed: " + err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if table == nil {
|
||||||
|
return errors.New("can not create table '" + tableDef.Name + "'")
|
||||||
|
}
|
||||||
|
|
||||||
|
// chain
|
||||||
|
var chainName = nftablesChainName
|
||||||
|
chain, err := table.GetChain(chainName)
|
||||||
|
if err != nil {
|
||||||
|
if nftables.IsNotFound(err) {
|
||||||
|
chain, err = table.AddAcceptChain(chainName)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("create chain '" + chainName + "' failed: " + err.Error())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return errors.New("get chain '" + chainName + "' failed: " + err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if chain == nil {
|
||||||
|
return errors.New("can not create chain '" + chainName + "'")
|
||||||
|
}
|
||||||
|
|
||||||
|
// allow lo
|
||||||
|
var loRuleName = []byte("lo")
|
||||||
|
_, err = chain.GetRuleWithUserData(loRuleName)
|
||||||
|
if err != nil {
|
||||||
|
if nftables.IsNotFound(err) {
|
||||||
|
_, err = chain.AddAcceptInterfaceRule("lo", loRuleName)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("add 'lo' rule failed: " + err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// allow set
|
||||||
|
// "allow" should be always first
|
||||||
|
for _, setAction := range []string{"allow", "deny"} {
|
||||||
|
var setName = setAction + "_set"
|
||||||
|
|
||||||
|
set, err := table.GetSet(setName)
|
||||||
|
if err != nil {
|
||||||
|
if nftables.IsNotFound(err) {
|
||||||
|
var keyType nftables.SetDataType
|
||||||
|
if tableDef.IsIPv4 {
|
||||||
|
keyType = nftables.TypeIPAddr
|
||||||
|
} else if tableDef.IsIPv6 {
|
||||||
|
keyType = nftables.TypeIP6Addr
|
||||||
|
}
|
||||||
|
set, err = table.AddSet(setName, &nftables.SetOptions{
|
||||||
|
KeyType: keyType,
|
||||||
|
HasTimeout: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("create set '" + setName + "' failed: " + err.Error())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return errors.New("get set '" + setName + "' failed: " + err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if set == nil {
|
||||||
|
return errors.New("can not create set '" + setName + "'")
|
||||||
|
}
|
||||||
|
if tableDef.IsIPv4 {
|
||||||
|
if setAction == "allow" {
|
||||||
|
this.allowIPv4Set = set
|
||||||
|
} else {
|
||||||
|
this.denyIPv4Set = set
|
||||||
|
}
|
||||||
|
} else if tableDef.IsIPv6 {
|
||||||
|
if setAction == "allow" {
|
||||||
|
this.allowIPv6Set = set
|
||||||
|
} else {
|
||||||
|
this.denyIPv6Set = set
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// rule
|
||||||
|
var ruleName = []byte(setAction)
|
||||||
|
rule, err := chain.GetRuleWithUserData(ruleName)
|
||||||
|
if err != nil {
|
||||||
|
if nftables.IsNotFound(err) {
|
||||||
|
if tableDef.IsIPv4 {
|
||||||
|
if setAction == "allow" {
|
||||||
|
rule, err = chain.AddAcceptIPv4SetRule(setName, ruleName)
|
||||||
|
} else {
|
||||||
|
rule, err = chain.AddDropIPv4SetRule(setName, ruleName)
|
||||||
|
}
|
||||||
|
} else if tableDef.IsIPv6 {
|
||||||
|
if setAction == "allow" {
|
||||||
|
rule, err = chain.AddAcceptIPv6SetRule(setName, ruleName)
|
||||||
|
} else {
|
||||||
|
rule, err = chain.AddDropIPv6SetRule(setName, ruleName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("add rule failed: " + err.Error())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return errors.New("get rule failed: " + err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if rule == nil {
|
||||||
|
return errors.New("can not create rule '" + string(ruleName) + "'")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isReady = true
|
||||||
|
nftablesIsReady = true
|
||||||
|
nftablesInstance = this
|
||||||
|
|
||||||
|
goman.New(func() {
|
||||||
|
for ipItem := range this.dropIPQueue {
|
||||||
|
switch ipItem.action {
|
||||||
|
case "drop":
|
||||||
|
err = this.DropSourceIP(ipItem.ip, ipItem.timeoutSeconds, false)
|
||||||
|
if err != nil {
|
||||||
|
remotelogs.Warn("NFTABLES", "drop ip '"+ipItem.ip+"' failed: "+err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// load firewalld
|
||||||
|
var firewalld = NewFirewalld()
|
||||||
|
if firewalld.IsReady() {
|
||||||
|
this.firewalld = firewalld
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Name 名称
|
||||||
|
func (this *NFTablesFirewall) Name() string {
|
||||||
|
return "nftables"
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsReady 是否已准备被调用
|
||||||
|
func (this *NFTablesFirewall) IsReady() bool {
|
||||||
|
return this.isReady
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsMock 是否为模拟
|
||||||
|
func (this *NFTablesFirewall) IsMock() bool {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// AllowPort 允许端口
|
||||||
|
func (this *NFTablesFirewall) AllowPort(port int, protocol string) error {
|
||||||
|
if this.firewalld != nil {
|
||||||
|
return this.firewalld.AllowPort(port, protocol)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemovePort 删除端口
|
||||||
|
func (this *NFTablesFirewall) RemovePort(port int, protocol string) error {
|
||||||
|
if this.firewalld != nil {
|
||||||
|
return this.firewalld.RemovePort(port, protocol)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AllowSourceIP Allow把IP加入白名单
|
||||||
|
func (this *NFTablesFirewall) AllowSourceIP(ip string) error {
|
||||||
|
var data = net.ParseIP(ip)
|
||||||
|
if data == nil {
|
||||||
|
return errors.New("invalid ip '" + ip + "'")
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.Contains(ip, ":") { // ipv6
|
||||||
|
if this.allowIPv6Set == nil {
|
||||||
|
return errors.New("ipv6 ip set is nil")
|
||||||
|
}
|
||||||
|
return this.allowIPv6Set.AddElement(data.To16(), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ipv4
|
||||||
|
if this.allowIPv4Set == nil {
|
||||||
|
return errors.New("ipv4 ip set is nil")
|
||||||
|
}
|
||||||
|
return this.allowIPv4Set.AddElement(data.To4(), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RejectSourceIP 拒绝某个源IP连接
|
||||||
|
// we did not create set for drop ip, so we reuse DropSourceIP() method here
|
||||||
|
func (this *NFTablesFirewall) RejectSourceIP(ip string, timeoutSeconds int) error {
|
||||||
|
return this.DropSourceIP(ip, timeoutSeconds, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DropSourceIP 丢弃某个源IP数据
|
||||||
|
func (this *NFTablesFirewall) DropSourceIP(ip string, timeoutSeconds int, async bool) error {
|
||||||
|
var data = net.ParseIP(ip)
|
||||||
|
if data == nil {
|
||||||
|
return errors.New("invalid ip '" + ip + "'")
|
||||||
|
}
|
||||||
|
|
||||||
|
if async {
|
||||||
|
select {
|
||||||
|
case this.dropIPQueue <- &blockIPItem{
|
||||||
|
action: "drop",
|
||||||
|
ip: ip,
|
||||||
|
timeoutSeconds: timeoutSeconds,
|
||||||
|
}:
|
||||||
|
default:
|
||||||
|
return errors.New("drop ip queue is full")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.Contains(ip, ":") { // ipv6
|
||||||
|
if this.denyIPv6Set == nil {
|
||||||
|
return errors.New("ipv6 ip set is nil")
|
||||||
|
}
|
||||||
|
return this.denyIPv6Set.AddElement(data.To16(), &nftables.ElementOptions{
|
||||||
|
Timeout: time.Duration(timeoutSeconds) * time.Second,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ipv4
|
||||||
|
if this.denyIPv4Set == nil {
|
||||||
|
return errors.New("ipv4 ip set is nil")
|
||||||
|
}
|
||||||
|
return this.denyIPv4Set.AddElement(data.To4(), &nftables.ElementOptions{
|
||||||
|
Timeout: time.Duration(timeoutSeconds) * time.Second,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveSourceIP 删除某个源IP
|
||||||
|
func (this *NFTablesFirewall) RemoveSourceIP(ip string) error {
|
||||||
|
var data = net.ParseIP(ip)
|
||||||
|
if data == nil {
|
||||||
|
return errors.New("invalid ip '" + ip + "'")
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.Contains(ip, ":") { // ipv6
|
||||||
|
if this.denyIPv6Set != nil {
|
||||||
|
err := this.denyIPv6Set.DeleteElement(data.To16())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if this.allowIPv6Set != nil {
|
||||||
|
err := this.allowIPv6Set.DeleteElement(data.To16())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ipv4
|
||||||
|
if this.allowIPv4Set != nil {
|
||||||
|
err := this.denyIPv4Set.DeleteElement(data.To4())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = this.allowIPv4Set.DeleteElement(data.To4())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 读取版本号
|
||||||
|
func (this *NFTablesFirewall) readVersion(nftPath string) string {
|
||||||
|
var cmd = exec.Command(nftPath, "--version")
|
||||||
|
var output = &bytes.Buffer{}
|
||||||
|
cmd.Stdout = output
|
||||||
|
err := cmd.Run()
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
var outputString = output.String()
|
||||||
|
var versionMatches = regexp.MustCompile(`nftables v([\d.]+)`).FindStringSubmatch(outputString)
|
||||||
|
if len(versionMatches) <= 1 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return versionMatches[1]
|
||||||
|
}
|
||||||
61
internal/firewalls/firewall_nftables_others.go
Normal file
61
internal/firewalls/firewall_nftables_others.go
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
//go:build !linux
|
||||||
|
// +build !linux
|
||||||
|
|
||||||
|
package firewalls
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewNFTablesFirewall() (*NFTablesFirewall, error) {
|
||||||
|
return nil, errors.New("not implemented")
|
||||||
|
}
|
||||||
|
|
||||||
|
type NFTablesFirewall struct {
|
||||||
|
}
|
||||||
|
|
||||||
|
// Name 名称
|
||||||
|
func (this *NFTablesFirewall) Name() string {
|
||||||
|
return "nftables"
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsReady 是否已准备被调用
|
||||||
|
func (this *NFTablesFirewall) IsReady() bool {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsMock 是否为模拟
|
||||||
|
func (this *NFTablesFirewall) IsMock() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// AllowPort 允许端口
|
||||||
|
func (this *NFTablesFirewall) AllowPort(port int, protocol string) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemovePort 删除端口
|
||||||
|
func (this *NFTablesFirewall) RemovePort(port int, protocol string) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AllowSourceIP Allow把IP加入白名单
|
||||||
|
func (this *NFTablesFirewall) AllowSourceIP(ip string) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RejectSourceIP 拒绝某个源IP连接
|
||||||
|
func (this *NFTablesFirewall) RejectSourceIP(ip string, timeoutSeconds int) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DropSourceIP 丢弃某个源IP数据
|
||||||
|
func (this *NFTablesFirewall) DropSourceIP(ip string, timeoutSeconds int, async bool) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveSourceIP 删除某个源IP
|
||||||
|
func (this *NFTablesFirewall) RemoveSourceIP(ip string) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
1
internal/firewalls/nftables/.gitignore
vendored
Normal file
1
internal/firewalls/nftables/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
build_remote.sh
|
||||||
370
internal/firewalls/nftables/chain.go
Normal file
370
internal/firewalls/nftables/chain.go
Normal file
@@ -0,0 +1,370 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
//go:build linux
|
||||||
|
// +build linux
|
||||||
|
|
||||||
|
package nftables
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
nft "github.com/google/nftables"
|
||||||
|
"github.com/google/nftables/expr"
|
||||||
|
)
|
||||||
|
|
||||||
|
const MaxChainNameLength = 31
|
||||||
|
|
||||||
|
type RuleOptions struct {
|
||||||
|
Exprs []expr.Any
|
||||||
|
UserData []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// Chain chain object in table
|
||||||
|
type Chain struct {
|
||||||
|
conn *Conn
|
||||||
|
rawTable *nft.Table
|
||||||
|
rawChain *nft.Chain
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewChain(conn *Conn, rawTable *nft.Table, rawChain *nft.Chain) *Chain {
|
||||||
|
return &Chain{
|
||||||
|
conn: conn,
|
||||||
|
rawTable: rawTable,
|
||||||
|
rawChain: rawChain,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) Raw() *nft.Chain {
|
||||||
|
return this.rawChain
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) Name() string {
|
||||||
|
return this.rawChain.Name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) AddRule(options *RuleOptions) (*Rule, error) {
|
||||||
|
var rawRule = this.conn.Raw().AddRule(&nft.Rule{
|
||||||
|
Table: this.rawTable,
|
||||||
|
Chain: this.rawChain,
|
||||||
|
Exprs: options.Exprs,
|
||||||
|
UserData: options.UserData,
|
||||||
|
})
|
||||||
|
err := this.conn.Commit()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return NewRule(rawRule), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) AddAcceptIPv4Rule(ip []byte, userData []byte) (*Rule, error) {
|
||||||
|
return this.AddRule(&RuleOptions{
|
||||||
|
Exprs: []expr.Any{
|
||||||
|
&expr.Payload{
|
||||||
|
DestRegister: 1,
|
||||||
|
Base: expr.PayloadBaseNetworkHeader,
|
||||||
|
Offset: 12,
|
||||||
|
Len: 4,
|
||||||
|
},
|
||||||
|
&expr.Cmp{
|
||||||
|
Op: expr.CmpOpEq,
|
||||||
|
Register: 1,
|
||||||
|
Data: ip,
|
||||||
|
},
|
||||||
|
&expr.Verdict{
|
||||||
|
Kind: expr.VerdictAccept,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
UserData: userData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) AddAcceptIPv6Rule(ip []byte, userData []byte) (*Rule, error) {
|
||||||
|
return this.AddRule(&RuleOptions{
|
||||||
|
Exprs: []expr.Any{
|
||||||
|
&expr.Payload{
|
||||||
|
DestRegister: 1,
|
||||||
|
Base: expr.PayloadBaseNetworkHeader,
|
||||||
|
Offset: 8,
|
||||||
|
Len: 16,
|
||||||
|
},
|
||||||
|
&expr.Cmp{
|
||||||
|
Op: expr.CmpOpEq,
|
||||||
|
Register: 1,
|
||||||
|
Data: ip,
|
||||||
|
},
|
||||||
|
&expr.Verdict{
|
||||||
|
Kind: expr.VerdictAccept,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
UserData: userData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) AddDropIPv4Rule(ip []byte, userData []byte) (*Rule, error) {
|
||||||
|
return this.AddRule(&RuleOptions{
|
||||||
|
Exprs: []expr.Any{
|
||||||
|
&expr.Payload{
|
||||||
|
DestRegister: 1,
|
||||||
|
Base: expr.PayloadBaseNetworkHeader,
|
||||||
|
Offset: 12,
|
||||||
|
Len: 4,
|
||||||
|
},
|
||||||
|
&expr.Cmp{
|
||||||
|
Op: expr.CmpOpEq,
|
||||||
|
Register: 1,
|
||||||
|
Data: ip,
|
||||||
|
},
|
||||||
|
&expr.Verdict{
|
||||||
|
Kind: expr.VerdictDrop,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
UserData: userData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) AddDropIPv6Rule(ip []byte, userData []byte) (*Rule, error) {
|
||||||
|
return this.AddRule(&RuleOptions{
|
||||||
|
Exprs: []expr.Any{
|
||||||
|
&expr.Payload{
|
||||||
|
DestRegister: 1,
|
||||||
|
Base: expr.PayloadBaseNetworkHeader,
|
||||||
|
Offset: 8,
|
||||||
|
Len: 16,
|
||||||
|
},
|
||||||
|
&expr.Cmp{
|
||||||
|
Op: expr.CmpOpEq,
|
||||||
|
Register: 1,
|
||||||
|
Data: ip,
|
||||||
|
},
|
||||||
|
&expr.Verdict{
|
||||||
|
Kind: expr.VerdictDrop,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
UserData: userData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) AddRejectIPv4Rule(ip []byte, userData []byte) (*Rule, error) {
|
||||||
|
return this.AddRule(&RuleOptions{
|
||||||
|
Exprs: []expr.Any{
|
||||||
|
&expr.Payload{
|
||||||
|
DestRegister: 1,
|
||||||
|
Base: expr.PayloadBaseNetworkHeader,
|
||||||
|
Offset: 12,
|
||||||
|
Len: 4,
|
||||||
|
},
|
||||||
|
&expr.Cmp{
|
||||||
|
Op: expr.CmpOpEq,
|
||||||
|
Register: 1,
|
||||||
|
Data: ip,
|
||||||
|
},
|
||||||
|
&expr.Reject{},
|
||||||
|
},
|
||||||
|
UserData: userData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) AddRejectIPv6Rule(ip []byte, userData []byte) (*Rule, error) {
|
||||||
|
return this.AddRule(&RuleOptions{
|
||||||
|
Exprs: []expr.Any{
|
||||||
|
&expr.Payload{
|
||||||
|
DestRegister: 1,
|
||||||
|
Base: expr.PayloadBaseNetworkHeader,
|
||||||
|
Offset: 8,
|
||||||
|
Len: 16,
|
||||||
|
},
|
||||||
|
&expr.Cmp{
|
||||||
|
Op: expr.CmpOpEq,
|
||||||
|
Register: 1,
|
||||||
|
Data: ip,
|
||||||
|
},
|
||||||
|
&expr.Reject{},
|
||||||
|
},
|
||||||
|
UserData: userData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) AddAcceptIPv4SetRule(setName string, userData []byte) (*Rule, error) {
|
||||||
|
return this.AddRule(&RuleOptions{
|
||||||
|
Exprs: []expr.Any{
|
||||||
|
&expr.Payload{
|
||||||
|
DestRegister: 1,
|
||||||
|
Base: expr.PayloadBaseNetworkHeader,
|
||||||
|
Offset: 12,
|
||||||
|
Len: 4,
|
||||||
|
},
|
||||||
|
&expr.Lookup{
|
||||||
|
SourceRegister: 1,
|
||||||
|
SetName: setName,
|
||||||
|
},
|
||||||
|
&expr.Verdict{
|
||||||
|
Kind: expr.VerdictAccept,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
UserData: userData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) AddAcceptIPv6SetRule(setName string, userData []byte) (*Rule, error) {
|
||||||
|
return this.AddRule(&RuleOptions{
|
||||||
|
Exprs: []expr.Any{
|
||||||
|
&expr.Payload{
|
||||||
|
DestRegister: 1,
|
||||||
|
Base: expr.PayloadBaseNetworkHeader,
|
||||||
|
Offset: 8,
|
||||||
|
Len: 16,
|
||||||
|
},
|
||||||
|
&expr.Lookup{
|
||||||
|
SourceRegister: 1,
|
||||||
|
SetName: setName,
|
||||||
|
},
|
||||||
|
&expr.Verdict{
|
||||||
|
Kind: expr.VerdictAccept,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
UserData: userData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) AddDropIPv4SetRule(setName string, userData []byte) (*Rule, error) {
|
||||||
|
return this.AddRule(&RuleOptions{
|
||||||
|
Exprs: []expr.Any{
|
||||||
|
&expr.Payload{
|
||||||
|
DestRegister: 1,
|
||||||
|
Base: expr.PayloadBaseNetworkHeader,
|
||||||
|
Offset: 12,
|
||||||
|
Len: 4,
|
||||||
|
},
|
||||||
|
&expr.Lookup{
|
||||||
|
SourceRegister: 1,
|
||||||
|
SetName: setName,
|
||||||
|
},
|
||||||
|
&expr.Verdict{
|
||||||
|
Kind: expr.VerdictDrop,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
UserData: userData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) AddDropIPv6SetRule(setName string, userData []byte) (*Rule, error) {
|
||||||
|
return this.AddRule(&RuleOptions{
|
||||||
|
Exprs: []expr.Any{
|
||||||
|
&expr.Payload{
|
||||||
|
DestRegister: 1,
|
||||||
|
Base: expr.PayloadBaseNetworkHeader,
|
||||||
|
Offset: 8,
|
||||||
|
Len: 16,
|
||||||
|
},
|
||||||
|
&expr.Lookup{
|
||||||
|
SourceRegister: 1,
|
||||||
|
SetName: setName,
|
||||||
|
},
|
||||||
|
&expr.Verdict{
|
||||||
|
Kind: expr.VerdictDrop,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
UserData: userData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) AddRejectIPv4SetRule(setName string, userData []byte) (*Rule, error) {
|
||||||
|
return this.AddRule(&RuleOptions{
|
||||||
|
Exprs: []expr.Any{
|
||||||
|
&expr.Payload{
|
||||||
|
DestRegister: 1,
|
||||||
|
Base: expr.PayloadBaseNetworkHeader,
|
||||||
|
Offset: 12,
|
||||||
|
Len: 4,
|
||||||
|
},
|
||||||
|
&expr.Lookup{
|
||||||
|
SourceRegister: 1,
|
||||||
|
SetName: setName,
|
||||||
|
},
|
||||||
|
&expr.Reject{},
|
||||||
|
},
|
||||||
|
UserData: userData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) AddRejectIPv6SetRule(setName string, userData []byte) (*Rule, error) {
|
||||||
|
return this.AddRule(&RuleOptions{
|
||||||
|
Exprs: []expr.Any{
|
||||||
|
&expr.Payload{
|
||||||
|
DestRegister: 1,
|
||||||
|
Base: expr.PayloadBaseNetworkHeader,
|
||||||
|
Offset: 8,
|
||||||
|
Len: 16,
|
||||||
|
},
|
||||||
|
&expr.Lookup{
|
||||||
|
SourceRegister: 1,
|
||||||
|
SetName: setName,
|
||||||
|
},
|
||||||
|
&expr.Reject{},
|
||||||
|
},
|
||||||
|
UserData: userData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) AddAcceptInterfaceRule(interfaceName string, userData []byte) (*Rule, error) {
|
||||||
|
if len(interfaceName) >= 16 {
|
||||||
|
return nil, errors.New("invalid interface name '" + interfaceName + "'")
|
||||||
|
}
|
||||||
|
var ifname = make([]byte, 16)
|
||||||
|
copy(ifname, interfaceName+"\x00")
|
||||||
|
|
||||||
|
return this.AddRule(&RuleOptions{
|
||||||
|
Exprs: []expr.Any{
|
||||||
|
&expr.Meta{
|
||||||
|
Key: expr.MetaKeyIIFNAME,
|
||||||
|
Register: 1,
|
||||||
|
},
|
||||||
|
&expr.Cmp{
|
||||||
|
Op: expr.CmpOpEq,
|
||||||
|
Register: 1,
|
||||||
|
Data: ifname,
|
||||||
|
},
|
||||||
|
&expr.Verdict{
|
||||||
|
Kind: expr.VerdictAccept,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
UserData: userData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) GetRuleWithUserData(userData []byte) (*Rule, error) {
|
||||||
|
rawRules, err := this.conn.Raw().GetRule(this.rawTable, this.rawChain)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, rawRule := range rawRules {
|
||||||
|
if bytes.Compare(rawRule.UserData, userData) == 0 {
|
||||||
|
return NewRule(rawRule), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, ErrRuleNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) GetRules() ([]*Rule, error) {
|
||||||
|
rawRules, err := this.conn.Raw().GetRule(this.rawTable, this.rawChain)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var result = []*Rule{}
|
||||||
|
for _, rawRule := range rawRules {
|
||||||
|
result = append(result, NewRule(rawRule))
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) DeleteRule(rule *Rule) error {
|
||||||
|
err := this.conn.Raw().DelRule(rule.Raw())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return this.conn.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Chain) Flush() error {
|
||||||
|
this.conn.Raw().FlushChain(this.rawChain)
|
||||||
|
return this.conn.Commit()
|
||||||
|
}
|
||||||
13
internal/firewalls/nftables/chain_policy.go
Normal file
13
internal/firewalls/nftables/chain_policy.go
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
|
||||||
|
package nftables
|
||||||
|
|
||||||
|
import nft "github.com/google/nftables"
|
||||||
|
|
||||||
|
type ChainPolicy = nft.ChainPolicy
|
||||||
|
|
||||||
|
// Possible ChainPolicy values.
|
||||||
|
const (
|
||||||
|
ChainPolicyDrop = nft.ChainPolicyDrop
|
||||||
|
ChainPolicyAccept = nft.ChainPolicyAccept
|
||||||
|
)
|
||||||
130
internal/firewalls/nftables/chain_test.go
Normal file
130
internal/firewalls/nftables/chain_test.go
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
//go:build linux
|
||||||
|
// +build linux
|
||||||
|
|
||||||
|
package nftables_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/firewalls/nftables"
|
||||||
|
"net"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func getIPv4Chain(t *testing.T) *nftables.Chain {
|
||||||
|
var conn = nftables.NewConn()
|
||||||
|
table, err := conn.GetTable("test_ipv4", nftables.TableFamilyIPv4)
|
||||||
|
if err != nil {
|
||||||
|
if err == nftables.ErrTableNotFound {
|
||||||
|
table, err = conn.AddIPv4Table("test_ipv4")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
chain, err := table.GetChain("test_chain")
|
||||||
|
if err != nil {
|
||||||
|
if err == nftables.ErrChainNotFound {
|
||||||
|
chain, err = table.AddAcceptChain("test_chain")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return chain
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChain_AddAcceptIPRule(t *testing.T) {
|
||||||
|
var chain = getIPv4Chain(t)
|
||||||
|
_, err := chain.AddAcceptIPv4Rule(net.ParseIP("192.168.2.40").To4(), nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChain_AddDropIPRule(t *testing.T) {
|
||||||
|
var chain = getIPv4Chain(t)
|
||||||
|
_, err := chain.AddDropIPv4Rule(net.ParseIP("192.168.2.31").To4(), nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChain_AddAcceptSetRule(t *testing.T) {
|
||||||
|
var chain = getIPv4Chain(t)
|
||||||
|
_, err := chain.AddAcceptIPv4SetRule("ipv4_black_set", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChain_AddDropSetRule(t *testing.T) {
|
||||||
|
var chain = getIPv4Chain(t)
|
||||||
|
_, err := chain.AddDropIPv4SetRule("ipv4_black_set", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChain_AddRejectSetRule(t *testing.T) {
|
||||||
|
var chain = getIPv4Chain(t)
|
||||||
|
_, err := chain.AddRejectIPv4SetRule("ipv4_black_set", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChain_GetRuleWithUserData(t *testing.T) {
|
||||||
|
var chain = getIPv4Chain(t)
|
||||||
|
rule, err := chain.GetRuleWithUserData([]byte("test"))
|
||||||
|
if err != nil {
|
||||||
|
if err == nftables.ErrRuleNotFound {
|
||||||
|
t.Log("rule not found")
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Log("rule:", rule)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChain_GetRules(t *testing.T) {
|
||||||
|
var chain = getIPv4Chain(t)
|
||||||
|
rules, err := chain.GetRules()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, rule := range rules {
|
||||||
|
t.Log("handle:", rule.Handle(), "set name:", rule.LookupSetName(),
|
||||||
|
"verdict:", rule.VerDict(), "user data:", string(rule.UserData()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChain_DeleteRule(t *testing.T) {
|
||||||
|
var chain = getIPv4Chain(t)
|
||||||
|
rule, err := chain.GetRuleWithUserData([]byte("test"))
|
||||||
|
if err != nil {
|
||||||
|
if err == nftables.ErrRuleNotFound {
|
||||||
|
t.Log("rule not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
err = chain.DeleteRule(rule)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChain_Flush(t *testing.T) {
|
||||||
|
var chain = getIPv4Chain(t)
|
||||||
|
err := chain.Flush()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log("ok")
|
||||||
|
}
|
||||||
84
internal/firewalls/nftables/conn.go
Normal file
84
internal/firewalls/nftables/conn.go
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
//go:build linux
|
||||||
|
// +build linux
|
||||||
|
|
||||||
|
package nftables
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
nft "github.com/google/nftables"
|
||||||
|
"github.com/iwind/TeaGo/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
const MaxTableNameLength = 27
|
||||||
|
|
||||||
|
type Conn struct {
|
||||||
|
rawConn *nft.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewConn() *Conn {
|
||||||
|
return &Conn{
|
||||||
|
rawConn: &nft.Conn{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Conn) Raw() *nft.Conn {
|
||||||
|
return this.rawConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Conn) GetTable(name string, family TableFamily) (*Table, error) {
|
||||||
|
rawTables, err := this.rawConn.ListTables()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, rawTable := range rawTables {
|
||||||
|
if rawTable.Name == name && rawTable.Family == family {
|
||||||
|
return NewTable(this, rawTable), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, ErrTableNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Conn) AddTable(name string, family TableFamily) (*Table, error) {
|
||||||
|
if len(name) > MaxTableNameLength {
|
||||||
|
return nil, errors.New("table name too long (max " + types.String(MaxTableNameLength) + ")")
|
||||||
|
}
|
||||||
|
|
||||||
|
var rawTable = this.rawConn.AddTable(&nft.Table{
|
||||||
|
Family: family,
|
||||||
|
Name: name,
|
||||||
|
})
|
||||||
|
|
||||||
|
err := this.Commit()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewTable(this, rawTable), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Conn) AddIPv4Table(name string) (*Table, error) {
|
||||||
|
return this.AddTable(name, TableFamilyIPv4)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Conn) AddIPv6Table(name string) (*Table, error) {
|
||||||
|
return this.AddTable(name, TableFamilyIPv6)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Conn) DeleteTable(name string, family TableFamily) error {
|
||||||
|
table, err := this.GetTable(name, family)
|
||||||
|
if err != nil {
|
||||||
|
if err == ErrTableNotFound {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
this.rawConn.DelTable(table.Raw())
|
||||||
|
return this.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Conn) Commit() error {
|
||||||
|
return this.rawConn.Flush()
|
||||||
|
}
|
||||||
78
internal/firewalls/nftables/conn_test.go
Normal file
78
internal/firewalls/nftables/conn_test.go
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
//go:build linux
|
||||||
|
// +build linux
|
||||||
|
|
||||||
|
package nftables_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/firewalls/nftables"
|
||||||
|
"os/exec"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestConn_Test(t *testing.T) {
|
||||||
|
_, err := exec.LookPath("nft")
|
||||||
|
if err == nil {
|
||||||
|
t.Log("ok")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
t.Log(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConn_GetTable_NotFound(t *testing.T) {
|
||||||
|
var conn = nftables.NewConn()
|
||||||
|
|
||||||
|
table, err := conn.GetTable("a", nftables.TableFamilyIPv4)
|
||||||
|
if err != nil {
|
||||||
|
if err == nftables.ErrTableNotFound {
|
||||||
|
t.Log("table not found")
|
||||||
|
} else {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
t.Log("table:", table)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConn_GetTable(t *testing.T) {
|
||||||
|
var conn = nftables.NewConn()
|
||||||
|
|
||||||
|
table, err := conn.GetTable("myFilter", nftables.TableFamilyIPv4)
|
||||||
|
if err != nil {
|
||||||
|
if err == nftables.ErrTableNotFound {
|
||||||
|
t.Log("table not found")
|
||||||
|
} else {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
t.Log("table:", table)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConn_AddTable(t *testing.T) {
|
||||||
|
var conn = nftables.NewConn()
|
||||||
|
|
||||||
|
{
|
||||||
|
table, err := conn.AddIPv4Table("test_ipv4")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log(table.Name())
|
||||||
|
}
|
||||||
|
{
|
||||||
|
table, err := conn.AddIPv6Table("test_ipv6")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log(table.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConn_DeleteTable(t *testing.T) {
|
||||||
|
var conn = nftables.NewConn()
|
||||||
|
err := conn.DeleteTable("test_ipv4", nftables.TableFamilyIPv4)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log("ok")
|
||||||
|
}
|
||||||
8
internal/firewalls/nftables/element.go
Normal file
8
internal/firewalls/nftables/element.go
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
//go:build linux
|
||||||
|
// +build linux
|
||||||
|
|
||||||
|
package nftables
|
||||||
|
|
||||||
|
type Element struct {
|
||||||
|
}
|
||||||
19
internal/firewalls/nftables/errors.go
Normal file
19
internal/firewalls/nftables/errors.go
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
//go:build linux
|
||||||
|
// +build linux
|
||||||
|
|
||||||
|
package nftables
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
var ErrTableNotFound = errors.New("table not found")
|
||||||
|
var ErrChainNotFound = errors.New("chain not found")
|
||||||
|
var ErrSetNotFound = errors.New("set not found")
|
||||||
|
var ErrRuleNotFound = errors.New("rule not found")
|
||||||
|
|
||||||
|
func IsNotFound(err error) bool {
|
||||||
|
if err == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return err == ErrTableNotFound || err == ErrChainNotFound || err == ErrSetNotFound || err == ErrRuleNotFound
|
||||||
|
}
|
||||||
18
internal/firewalls/nftables/family.go
Normal file
18
internal/firewalls/nftables/family.go
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
|
||||||
|
package nftables
|
||||||
|
|
||||||
|
import (
|
||||||
|
nft "github.com/google/nftables"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TableFamily = nft.TableFamily
|
||||||
|
|
||||||
|
const (
|
||||||
|
TableFamilyINet TableFamily = nft.TableFamilyINet
|
||||||
|
TableFamilyIPv4 TableFamily = nft.TableFamilyIPv4
|
||||||
|
TableFamilyIPv6 TableFamily = nft.TableFamilyIPv6
|
||||||
|
TableFamilyARP TableFamily = nft.TableFamilyARP
|
||||||
|
TableFamilyNetdev TableFamily = nft.TableFamilyNetdev
|
||||||
|
TableFamilyBridge TableFamily = nft.TableFamilyBridge
|
||||||
|
)
|
||||||
51
internal/firewalls/nftables/rule.go
Normal file
51
internal/firewalls/nftables/rule.go
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
|
||||||
|
package nftables
|
||||||
|
|
||||||
|
import (
|
||||||
|
nft "github.com/google/nftables"
|
||||||
|
"github.com/google/nftables/expr"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Rule struct {
|
||||||
|
rawRule *nft.Rule
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRule(rawRule *nft.Rule) *Rule {
|
||||||
|
return &Rule{
|
||||||
|
rawRule: rawRule,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Rule) Raw() *nft.Rule {
|
||||||
|
return this.rawRule
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Rule) LookupSetName() string {
|
||||||
|
for _, e := range this.rawRule.Exprs {
|
||||||
|
exp, ok := e.(*expr.Lookup)
|
||||||
|
if ok {
|
||||||
|
return exp.SetName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Rule) VerDict() expr.VerdictKind {
|
||||||
|
for _, e := range this.rawRule.Exprs {
|
||||||
|
exp, ok := e.(*expr.Verdict)
|
||||||
|
if ok {
|
||||||
|
return exp.Kind
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return -100
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Rule) Handle() uint64 {
|
||||||
|
return this.rawRule.Handle
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Rule) UserData() []byte {
|
||||||
|
return this.rawRule.UserData
|
||||||
|
}
|
||||||
161
internal/firewalls/nftables/set.go
Normal file
161
internal/firewalls/nftables/set.go
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
//go:build linux
|
||||||
|
// +build linux
|
||||||
|
|
||||||
|
package nftables
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
||||||
|
nft "github.com/google/nftables"
|
||||||
|
"net"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const MaxSetNameLength = 15
|
||||||
|
|
||||||
|
type SetOptions struct {
|
||||||
|
Id uint32
|
||||||
|
HasTimeout bool
|
||||||
|
Timeout time.Duration
|
||||||
|
KeyType SetDataType
|
||||||
|
DataType SetDataType
|
||||||
|
Constant bool
|
||||||
|
Interval bool
|
||||||
|
Anonymous bool
|
||||||
|
IsMap bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type ElementOptions struct {
|
||||||
|
Timeout time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
type Set struct {
|
||||||
|
conn *Conn
|
||||||
|
rawSet *nft.Set
|
||||||
|
batch *SetBatch
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSet(conn *Conn, rawSet *nft.Set) *Set {
|
||||||
|
return &Set{
|
||||||
|
conn: conn,
|
||||||
|
rawSet: rawSet,
|
||||||
|
batch: &SetBatch{
|
||||||
|
conn: conn,
|
||||||
|
rawSet: rawSet,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Set) Raw() *nft.Set {
|
||||||
|
return this.rawSet
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Set) Name() string {
|
||||||
|
return this.rawSet.Name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Set) AddElement(key []byte, options *ElementOptions) error {
|
||||||
|
var rawElement = nft.SetElement{
|
||||||
|
Key: key,
|
||||||
|
}
|
||||||
|
if options != nil {
|
||||||
|
rawElement.Timeout = options.Timeout
|
||||||
|
}
|
||||||
|
err := this.conn.Raw().SetAddElements(this.rawSet, []nft.SetElement{
|
||||||
|
rawElement,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = this.conn.Commit()
|
||||||
|
if err != nil {
|
||||||
|
// retry if exists
|
||||||
|
if strings.Contains(err.Error(), "file exists") {
|
||||||
|
deleteErr := this.conn.Raw().SetDeleteElements(this.rawSet, []nft.SetElement{
|
||||||
|
{
|
||||||
|
Key: key,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if deleteErr == nil {
|
||||||
|
err = this.conn.Raw().SetAddElements(this.rawSet, []nft.SetElement{
|
||||||
|
rawElement,
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
err = this.conn.Commit()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Set) AddIPElement(ip string, options *ElementOptions) error {
|
||||||
|
var ipObj = net.ParseIP(ip)
|
||||||
|
if ipObj == nil {
|
||||||
|
return errors.New("invalid ip '" + ip + "'")
|
||||||
|
}
|
||||||
|
|
||||||
|
if utils.IsIPv4(ip) {
|
||||||
|
return this.AddElement(ipObj.To4(), options)
|
||||||
|
} else {
|
||||||
|
return this.AddElement(ipObj.To16(), options)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Set) DeleteElement(key []byte) error {
|
||||||
|
err := this.conn.Raw().SetDeleteElements(this.rawSet, []nft.SetElement{
|
||||||
|
{
|
||||||
|
Key: key,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = this.conn.Commit()
|
||||||
|
if err != nil {
|
||||||
|
if strings.Contains(err.Error(), "no such file or directory") {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Set) DeleteIPElement(ip string) error {
|
||||||
|
var ipObj = net.ParseIP(ip)
|
||||||
|
if ipObj == nil {
|
||||||
|
return errors.New("invalid ip '" + ip + "'")
|
||||||
|
}
|
||||||
|
|
||||||
|
if utils.IsIPv4(ip) {
|
||||||
|
return this.DeleteElement(ipObj.To4())
|
||||||
|
} else {
|
||||||
|
return this.DeleteElement(ipObj.To16())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Set) Batch() *SetBatch {
|
||||||
|
return this.batch
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Set) GetIPElements() ([]string, error) {
|
||||||
|
elements, err := this.conn.Raw().GetSetElements(this.rawSet)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = []string{}
|
||||||
|
for _, element := range elements {
|
||||||
|
result = append(result, net.IP(element.Key).String())
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// not work current time
|
||||||
|
/**func (this *Set) Flush() error {
|
||||||
|
this.conn.Raw().FlushSet(this.rawSet)
|
||||||
|
return this.conn.Commit()
|
||||||
|
}**/
|
||||||
36
internal/firewalls/nftables/set_batch.go
Normal file
36
internal/firewalls/nftables/set_batch.go
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
|
||||||
|
package nftables
|
||||||
|
|
||||||
|
import (
|
||||||
|
nft "github.com/google/nftables"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SetBatch struct {
|
||||||
|
conn *Conn
|
||||||
|
rawSet *nft.Set
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *SetBatch) AddElement(key []byte, options *ElementOptions) error {
|
||||||
|
var rawElement = nft.SetElement{
|
||||||
|
Key: key,
|
||||||
|
}
|
||||||
|
if options != nil {
|
||||||
|
rawElement.Timeout = options.Timeout
|
||||||
|
}
|
||||||
|
return this.conn.Raw().SetAddElements(this.rawSet, []nft.SetElement{
|
||||||
|
rawElement,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *SetBatch) DeleteElement(key []byte) error {
|
||||||
|
return this.conn.Raw().SetDeleteElements(this.rawSet, []nft.SetElement{
|
||||||
|
{
|
||||||
|
Key: key,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *SetBatch) Commit() error {
|
||||||
|
return this.conn.Commit()
|
||||||
|
}
|
||||||
57
internal/firewalls/nftables/set_data_type.go
Normal file
57
internal/firewalls/nftables/set_data_type.go
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
|
||||||
|
package nftables
|
||||||
|
|
||||||
|
import nft "github.com/google/nftables"
|
||||||
|
|
||||||
|
type SetDataType = nft.SetDatatype
|
||||||
|
|
||||||
|
var (
|
||||||
|
TypeInvalid = nft.TypeInvalid
|
||||||
|
TypeVerdict = nft.TypeVerdict
|
||||||
|
TypeNFProto = nft.TypeNFProto
|
||||||
|
TypeBitmask = nft.TypeBitmask
|
||||||
|
TypeInteger = nft.TypeInteger
|
||||||
|
TypeString = nft.TypeString
|
||||||
|
TypeLLAddr = nft.TypeLLAddr
|
||||||
|
TypeIPAddr = nft.TypeIPAddr
|
||||||
|
TypeIP6Addr = nft.TypeIP6Addr
|
||||||
|
TypeEtherAddr = nft.TypeEtherAddr
|
||||||
|
TypeEtherType = nft.TypeEtherType
|
||||||
|
TypeARPOp = nft.TypeARPOp
|
||||||
|
TypeInetProto = nft.TypeInetProto
|
||||||
|
TypeInetService = nft.TypeInetService
|
||||||
|
TypeICMPType = nft.TypeICMPType
|
||||||
|
TypeTCPFlag = nft.TypeTCPFlag
|
||||||
|
TypeDCCPPktType = nft.TypeDCCPPktType
|
||||||
|
TypeMHType = nft.TypeMHType
|
||||||
|
TypeTime = nft.TypeTime
|
||||||
|
TypeMark = nft.TypeMark
|
||||||
|
TypeIFIndex = nft.TypeIFIndex
|
||||||
|
TypeARPHRD = nft.TypeARPHRD
|
||||||
|
TypeRealm = nft.TypeRealm
|
||||||
|
TypeClassID = nft.TypeClassID
|
||||||
|
TypeUID = nft.TypeUID
|
||||||
|
TypeGID = nft.TypeGID
|
||||||
|
TypeCTState = nft.TypeCTState
|
||||||
|
TypeCTDir = nft.TypeCTDir
|
||||||
|
TypeCTStatus = nft.TypeCTStatus
|
||||||
|
TypeICMP6Type = nft.TypeICMP6Type
|
||||||
|
TypeCTLabel = nft.TypeCTLabel
|
||||||
|
TypePktType = nft.TypePktType
|
||||||
|
TypeICMPCode = nft.TypeICMPCode
|
||||||
|
TypeICMPV6Code = nft.TypeICMPV6Code
|
||||||
|
TypeICMPXCode = nft.TypeICMPXCode
|
||||||
|
TypeDevGroup = nft.TypeDevGroup
|
||||||
|
TypeDSCP = nft.TypeDSCP
|
||||||
|
TypeECN = nft.TypeECN
|
||||||
|
TypeFIBAddr = nft.TypeFIBAddr
|
||||||
|
TypeBoolean = nft.TypeBoolean
|
||||||
|
TypeCTEventBit = nft.TypeCTEventBit
|
||||||
|
TypeIFName = nft.TypeIFName
|
||||||
|
TypeIGMPType = nft.TypeIGMPType
|
||||||
|
TypeTimeDate = nft.TypeTimeDate
|
||||||
|
TypeTimeHour = nft.TypeTimeHour
|
||||||
|
TypeTimeDay = nft.TypeTimeDay
|
||||||
|
TypeCGroupV2 = nft.TypeCGroupV2
|
||||||
|
)
|
||||||
110
internal/firewalls/nftables/set_test.go
Normal file
110
internal/firewalls/nftables/set_test.go
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
|
||||||
|
package nftables_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/firewalls/nftables"
|
||||||
|
"github.com/iwind/TeaGo/types"
|
||||||
|
"github.com/mdlayher/netlink"
|
||||||
|
"net"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func getIPv4Set(t *testing.T) *nftables.Set {
|
||||||
|
var table = getIPv4Table(t)
|
||||||
|
set, err := table.GetSet("test_ipv4_set")
|
||||||
|
if err != nil {
|
||||||
|
if err == nftables.ErrSetNotFound {
|
||||||
|
set, err = table.AddSet("test_ipv4_set", &nftables.SetOptions{
|
||||||
|
KeyType: nftables.TypeIPAddr,
|
||||||
|
HasTimeout: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return set
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSet_AddElement(t *testing.T) {
|
||||||
|
var set = getIPv4Set(t)
|
||||||
|
err := set.AddElement(net.ParseIP("192.168.2.31").To4(), &nftables.ElementOptions{Timeout: 86400 * time.Second})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log("ok")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSet_DeleteElement(t *testing.T) {
|
||||||
|
var set = getIPv4Set(t)
|
||||||
|
err := set.DeleteElement(net.ParseIP("192.168.2.31").To4())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log("ok")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSet_Batch(t *testing.T) {
|
||||||
|
var batch = getIPv4Set(t).Batch()
|
||||||
|
|
||||||
|
for _, ip := range []string{"192.168.2.30", "192.168.2.31", "192.168.2.32", "192.168.2.33", "192.168.2.34"} {
|
||||||
|
var ipData = net.ParseIP(ip).To4()
|
||||||
|
//err := batch.DeleteElement(ipData)
|
||||||
|
//if err != nil {
|
||||||
|
// t.Fatal(err)
|
||||||
|
//}
|
||||||
|
err := batch.AddElement(ipData, &nftables.ElementOptions{Timeout: 10 * time.Second})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
err := batch.Commit()
|
||||||
|
if err != nil {
|
||||||
|
t.Logf("%#v", errors.Unwrap(err).(*netlink.OpError))
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log("ok")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSet_Add_Many(t *testing.T) {
|
||||||
|
var set = getIPv4Set(t)
|
||||||
|
|
||||||
|
for i := 0; i < 255; i++ {
|
||||||
|
t.Log(i)
|
||||||
|
for j := 0; j < 255; j++ {
|
||||||
|
var ip = "192.167." + types.String(i) + "." + types.String(j)
|
||||||
|
var ipData = net.ParseIP(ip).To4()
|
||||||
|
err := set.Batch().AddElement(ipData, &nftables.ElementOptions{Timeout: 3600 * time.Second})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if j%10 == 0 {
|
||||||
|
err = set.Batch().Commit()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err := set.Batch().Commit()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Log("ok")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**func TestSet_Flush(t *testing.T) {
|
||||||
|
var set = getIPv4Set(t)
|
||||||
|
err := set.Flush()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log("ok")
|
||||||
|
}**/
|
||||||
157
internal/firewalls/nftables/table.go
Normal file
157
internal/firewalls/nftables/table.go
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
//go:build linux
|
||||||
|
// +build linux
|
||||||
|
|
||||||
|
package nftables
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
nft "github.com/google/nftables"
|
||||||
|
"github.com/iwind/TeaGo/types"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Table struct {
|
||||||
|
conn *Conn
|
||||||
|
rawTable *nft.Table
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTable(conn *Conn, rawTable *nft.Table) *Table {
|
||||||
|
return &Table{
|
||||||
|
conn: conn,
|
||||||
|
rawTable: rawTable,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Table) Raw() *nft.Table {
|
||||||
|
return this.rawTable
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Table) Name() string {
|
||||||
|
return this.rawTable.Name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Table) Family() TableFamily {
|
||||||
|
return this.rawTable.Family
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Table) GetChain(name string) (*Chain, error) {
|
||||||
|
rawChains, err := this.conn.Raw().ListChains()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, rawChain := range rawChains {
|
||||||
|
// must compare table name
|
||||||
|
if rawChain.Name == name && rawChain.Table.Name == this.rawTable.Name {
|
||||||
|
return NewChain(this.conn, this.rawTable, rawChain), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, ErrChainNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Table) AddChain(name string, chainPolicy *ChainPolicy) (*Chain, error) {
|
||||||
|
if len(name) > MaxChainNameLength {
|
||||||
|
return nil, errors.New("chain name too long (max " + types.String(MaxChainNameLength) + ")")
|
||||||
|
}
|
||||||
|
|
||||||
|
var rawChain = this.conn.Raw().AddChain(&nft.Chain{
|
||||||
|
Name: name,
|
||||||
|
Table: this.rawTable,
|
||||||
|
Hooknum: nft.ChainHookInput,
|
||||||
|
Priority: nft.ChainPriorityFilter,
|
||||||
|
Type: nft.ChainTypeFilter,
|
||||||
|
Policy: chainPolicy,
|
||||||
|
})
|
||||||
|
|
||||||
|
err := this.conn.Commit()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return NewChain(this.conn, this.rawTable, rawChain), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Table) AddAcceptChain(name string) (*Chain, error) {
|
||||||
|
var policy = ChainPolicyAccept
|
||||||
|
return this.AddChain(name, &policy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Table) AddDropChain(name string) (*Chain, error) {
|
||||||
|
var policy = ChainPolicyDrop
|
||||||
|
return this.AddChain(name, &policy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Table) DeleteChain(name string) error {
|
||||||
|
chain, err := this.GetChain(name)
|
||||||
|
if err != nil {
|
||||||
|
if err == ErrChainNotFound {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
this.conn.Raw().DelChain(chain.Raw())
|
||||||
|
return this.conn.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Table) GetSet(name string) (*Set, error) {
|
||||||
|
rawSet, err := this.conn.Raw().GetSetByName(this.rawTable, name)
|
||||||
|
if err != nil {
|
||||||
|
if strings.Contains(err.Error(), "no such file or directory") {
|
||||||
|
return nil, ErrSetNotFound
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewSet(this.conn, rawSet), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Table) AddSet(name string, options *SetOptions) (*Set, error) {
|
||||||
|
if len(name) > MaxSetNameLength {
|
||||||
|
return nil, errors.New("set name too long (max " + types.String(MaxSetNameLength) + ")")
|
||||||
|
}
|
||||||
|
|
||||||
|
if options == nil {
|
||||||
|
options = &SetOptions{}
|
||||||
|
}
|
||||||
|
var rawSet = &nft.Set{
|
||||||
|
Table: this.rawTable,
|
||||||
|
ID: options.Id,
|
||||||
|
Name: name,
|
||||||
|
Anonymous: options.Anonymous,
|
||||||
|
Constant: options.Constant,
|
||||||
|
Interval: options.Interval,
|
||||||
|
IsMap: options.IsMap,
|
||||||
|
HasTimeout: options.HasTimeout,
|
||||||
|
Timeout: options.Timeout,
|
||||||
|
KeyType: options.KeyType,
|
||||||
|
DataType: options.DataType,
|
||||||
|
}
|
||||||
|
err := this.conn.Raw().AddSet(rawSet, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = this.conn.Commit()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewSet(this.conn, rawSet), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Table) DeleteSet(name string) error {
|
||||||
|
set, err := this.GetSet(name)
|
||||||
|
if err != nil {
|
||||||
|
if err == ErrSetNotFound {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
this.conn.Raw().DelSet(set.Raw())
|
||||||
|
return this.conn.Commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *Table) Flush() error {
|
||||||
|
this.conn.Raw().FlushTable(this.rawTable)
|
||||||
|
return this.conn.Commit()
|
||||||
|
}
|
||||||
140
internal/firewalls/nftables/table_test.go
Normal file
140
internal/firewalls/nftables/table_test.go
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
|
||||||
|
//go:build linux
|
||||||
|
// +build linux
|
||||||
|
|
||||||
|
package nftables_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/firewalls/nftables"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func getIPv4Table(t *testing.T) *nftables.Table {
|
||||||
|
var conn = nftables.NewConn()
|
||||||
|
table, err := conn.GetTable("test_ipv4", nftables.TableFamilyIPv4)
|
||||||
|
if err != nil {
|
||||||
|
if err == nftables.ErrTableNotFound {
|
||||||
|
table, err = conn.AddIPv4Table("test_ipv4")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return table
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTable_AddChain(t *testing.T) {
|
||||||
|
var table = getIPv4Table(t)
|
||||||
|
|
||||||
|
{
|
||||||
|
chain, err := table.AddChain("test_default_chain", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log("created:", chain.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
chain, err := table.AddAcceptChain("test_accept_chain")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log("created:", chain.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do not test drop chain before adding accept rule, you will drop yourself!!!!!!!
|
||||||
|
/**{
|
||||||
|
chain, err := table.AddDropChain("test_drop_chain")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log("created:", chain.Name())
|
||||||
|
}**/
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTable_GetChain(t *testing.T) {
|
||||||
|
var table = getIPv4Table(t)
|
||||||
|
for _, chainName := range []string{"not_found_chain", "test_default_chain"} {
|
||||||
|
chain, err := table.GetChain(chainName)
|
||||||
|
if err != nil {
|
||||||
|
if err == nftables.ErrChainNotFound {
|
||||||
|
t.Log(chainName, ":", "not found")
|
||||||
|
} else {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
t.Log(chainName, ":", chain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTable_DeleteChain(t *testing.T) {
|
||||||
|
var table = getIPv4Table(t)
|
||||||
|
err := table.DeleteChain("test_default_chain")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log("ok")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTable_AddSet(t *testing.T) {
|
||||||
|
var table = getIPv4Table(t)
|
||||||
|
{
|
||||||
|
set, err := table.AddSet("ipv4_black_set", &nftables.SetOptions{
|
||||||
|
HasTimeout: false,
|
||||||
|
KeyType: nftables.TypeIPAddr,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log(set.Name())
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
set, err := table.AddSet("ipv6_black_set", &nftables.SetOptions{
|
||||||
|
HasTimeout: true,
|
||||||
|
//Timeout: 3600 * time.Second,
|
||||||
|
KeyType: nftables.TypeIP6Addr,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log(set.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTable_GetSet(t *testing.T) {
|
||||||
|
var table = getIPv4Table(t)
|
||||||
|
for _, setName := range []string{"not_found_set", "ipv4_black_set"} {
|
||||||
|
set, err := table.GetSet(setName)
|
||||||
|
if err != nil {
|
||||||
|
if err == nftables.ErrSetNotFound {
|
||||||
|
t.Log(setName, ": not found")
|
||||||
|
} else {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
t.Log(setName, ":", set)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTable_DeleteSet(t *testing.T) {
|
||||||
|
var table = getIPv4Table(t)
|
||||||
|
err := table.DeleteSet("ipv4_black_set")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log("ok")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTable_Flush(t *testing.T) {
|
||||||
|
var table = getIPv4Table(t)
|
||||||
|
err := table.Flush()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log("ok")
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
package goman
|
package goman
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
||||||
"runtime"
|
"runtime"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -14,6 +15,10 @@ var instanceId = uint64(0)
|
|||||||
|
|
||||||
// New 新创建goroutine
|
// New 新创建goroutine
|
||||||
func New(f func()) {
|
func New(f func()) {
|
||||||
|
if teaconst.IsDaemon {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
_, file, line, _ := runtime.Caller(1)
|
_, file, line, _ := runtime.Caller(1)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
@@ -42,6 +47,10 @@ func New(f func()) {
|
|||||||
|
|
||||||
// NewWithArgs 创建带有参数的goroutine
|
// NewWithArgs 创建带有参数的goroutine
|
||||||
func NewWithArgs(f func(args ...interface{}), args ...interface{}) {
|
func NewWithArgs(f func(args ...interface{}), args ...interface{}) {
|
||||||
|
if teaconst.IsDaemon {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
_, file, line, _ := runtime.Caller(1)
|
_, file, line, _ := runtime.Caller(1)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ package iplibrary
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"io/ioutil"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
@@ -62,7 +62,7 @@ func getIpInfo(cityId int64, line []byte) *IpInfo {
|
|||||||
|
|
||||||
func NewIP2Region(path string) (*IP2Region, error) {
|
func NewIP2Region(path string) (*IP2Region, error) {
|
||||||
var region = &IP2Region{}
|
var region = &IP2Region{}
|
||||||
region.dbData, err = ioutil.ReadFile(path)
|
region.dbData, err = os.ReadFile(path)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ func TestIPItem_Memory(t *testing.T) {
|
|||||||
for i := 0; i < 2_000_000; i ++ {
|
for i := 0; i < 2_000_000; i ++ {
|
||||||
list.Add(&IPItem{
|
list.Add(&IPItem{
|
||||||
Type: "ip",
|
Type: "ip",
|
||||||
Id: int64(i),
|
Id: uint64(i),
|
||||||
IPFrom: utils.IP2Long("192.168.1.1"),
|
IPFrom: utils.IP2Long("192.168.1.1"),
|
||||||
IPTo: 0,
|
IPTo: 0,
|
||||||
ExpiredAt: time.Now().Unix(),
|
ExpiredAt: time.Now().Unix(),
|
||||||
|
|||||||
@@ -28,6 +28,8 @@ type IPListDB struct {
|
|||||||
cleanTicker *time.Ticker
|
cleanTicker *time.Ticker
|
||||||
|
|
||||||
dir string
|
dir string
|
||||||
|
|
||||||
|
isClosed bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewIPListDB() (*IPListDB, error) {
|
func NewIPListDB() (*IPListDB, error) {
|
||||||
@@ -48,7 +50,7 @@ func (this *IPListDB) init() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
remotelogs.Println("CACHE", "create cache dir '"+this.dir+"'")
|
remotelogs.Println("IP_LIST_DB", "create data dir '"+this.dir+"'")
|
||||||
}
|
}
|
||||||
|
|
||||||
db, err := sql.Open("sqlite3", "file:"+this.dir+"/ip_list.db?cache=shared&mode=rwc&_journal_mode=WAL&_sync=OFF")
|
db, err := sql.Open("sqlite3", "file:"+this.dir+"/ip_list.db?cache=shared&mode=rwc&_journal_mode=WAL&_sync=OFF")
|
||||||
@@ -56,6 +58,12 @@ func (this *IPListDB) init() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
db.SetMaxOpenConns(1)
|
db.SetMaxOpenConns(1)
|
||||||
|
|
||||||
|
//_, err = db.Exec("VACUUM")
|
||||||
|
//if err != nil {
|
||||||
|
// return err
|
||||||
|
//}
|
||||||
|
|
||||||
this.db = db
|
this.db = db
|
||||||
|
|
||||||
// 初始化数据库
|
// 初始化数据库
|
||||||
@@ -117,6 +125,7 @@ ON "` + this.itemTableName + `" (
|
|||||||
|
|
||||||
goman.New(func() {
|
goman.New(func() {
|
||||||
events.On(events.EventQuit, func() {
|
events.On(events.EventQuit, func() {
|
||||||
|
_ = this.Close()
|
||||||
this.cleanTicker.Stop()
|
this.cleanTicker.Stop()
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -133,11 +142,19 @@ ON "` + this.itemTableName + `" (
|
|||||||
|
|
||||||
// DeleteExpiredItems 删除过期的条目
|
// DeleteExpiredItems 删除过期的条目
|
||||||
func (this *IPListDB) DeleteExpiredItems() error {
|
func (this *IPListDB) DeleteExpiredItems() error {
|
||||||
|
if this.isClosed {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
_, err := this.deleteExpiredItemsStmt.Exec(time.Now().Unix() - 7*86400)
|
_, err := this.deleteExpiredItemsStmt.Exec(time.Now().Unix() - 7*86400)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (this *IPListDB) AddItem(item *pb.IPItem) error {
|
func (this *IPListDB) AddItem(item *pb.IPItem) error {
|
||||||
|
if this.isClosed {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
_, err := this.deleteItemStmt.Exec(item.Id)
|
_, err := this.deleteItemStmt.Exec(item.Id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -147,6 +164,10 @@ func (this *IPListDB) AddItem(item *pb.IPItem) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (this *IPListDB) ReadItems(offset int64, size int64) (items []*pb.IPItem, err error) {
|
func (this *IPListDB) ReadItems(offset int64, size int64) (items []*pb.IPItem, err error) {
|
||||||
|
if this.isClosed {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
rows, err := this.selectItemsStmt.Query(offset, size)
|
rows, err := this.selectItemsStmt.Query(offset, size)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -169,6 +190,10 @@ func (this *IPListDB) ReadItems(offset int64, size int64) (items []*pb.IPItem, e
|
|||||||
|
|
||||||
// ReadMaxVersion 读取当前最大版本号
|
// ReadMaxVersion 读取当前最大版本号
|
||||||
func (this *IPListDB) ReadMaxVersion() int64 {
|
func (this *IPListDB) ReadMaxVersion() int64 {
|
||||||
|
if this.isClosed {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
row := this.selectMaxVersionStmt.QueryRow()
|
row := this.selectMaxVersionStmt.QueryRow()
|
||||||
if row == nil {
|
if row == nil {
|
||||||
return 0
|
return 0
|
||||||
@@ -182,6 +207,8 @@ func (this *IPListDB) ReadMaxVersion() int64 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (this *IPListDB) Close() error {
|
func (this *IPListDB) Close() error {
|
||||||
|
this.isClosed = true
|
||||||
|
|
||||||
if this.db != nil {
|
if this.db != nil {
|
||||||
_ = this.deleteExpiredItemsStmt.Close()
|
_ = this.deleteExpiredItemsStmt.Close()
|
||||||
_ = this.deleteItemStmt.Close()
|
_ = this.deleteItemStmt.Close()
|
||||||
|
|||||||
@@ -53,6 +53,11 @@ func TestIPListDB_ReadItems(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
_ = db.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
items, err := db.ReadItems(0, 2)
|
items, err := db.ReadItems(0, 2)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
|
|||||||
@@ -144,7 +144,7 @@ func TestIPList_Contains(t *testing.T) {
|
|||||||
list := NewIPList()
|
list := NewIPList()
|
||||||
for i := 0; i < 255; i++ {
|
for i := 0; i < 255; i++ {
|
||||||
list.AddDelay(&IPItem{
|
list.AddDelay(&IPItem{
|
||||||
Id: int64(i),
|
Id: uint64(i),
|
||||||
IPFrom: utils.IP2Long(strconv.Itoa(i) + ".168.0.1"),
|
IPFrom: utils.IP2Long(strconv.Itoa(i) + ".168.0.1"),
|
||||||
IPTo: utils.IP2Long(strconv.Itoa(i) + ".168.255.1"),
|
IPTo: utils.IP2Long(strconv.Itoa(i) + ".168.255.1"),
|
||||||
ExpiredAt: 0,
|
ExpiredAt: 0,
|
||||||
@@ -152,7 +152,7 @@ func TestIPList_Contains(t *testing.T) {
|
|||||||
}
|
}
|
||||||
for i := 0; i < 255; i++ {
|
for i := 0; i < 255; i++ {
|
||||||
list.AddDelay(&IPItem{
|
list.AddDelay(&IPItem{
|
||||||
Id: int64(1000 + i),
|
Id: uint64(1000 + i),
|
||||||
IPFrom: utils.IP2Long("192.167.2." + strconv.Itoa(i)),
|
IPFrom: utils.IP2Long("192.167.2." + strconv.Itoa(i)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -172,7 +172,7 @@ func TestIPList_Contains_Many(t *testing.T) {
|
|||||||
list := NewIPList()
|
list := NewIPList()
|
||||||
for i := 0; i < 1_000_000; i++ {
|
for i := 0; i < 1_000_000; i++ {
|
||||||
list.AddDelay(&IPItem{
|
list.AddDelay(&IPItem{
|
||||||
Id: int64(i),
|
Id: uint64(i),
|
||||||
IPFrom: utils.IP2Long(strconv.Itoa(rands.Int(0, 255)) + "." + strconv.Itoa(rands.Int(0, 255)) + "." + strconv.Itoa(rands.Int(0, 255)) + "." + strconv.Itoa(rands.Int(0, 255))),
|
IPFrom: utils.IP2Long(strconv.Itoa(rands.Int(0, 255)) + "." + strconv.Itoa(rands.Int(0, 255)) + "." + strconv.Itoa(rands.Int(0, 255)) + "." + strconv.Itoa(rands.Int(0, 255))),
|
||||||
IPTo: utils.IP2Long(strconv.Itoa(rands.Int(0, 255)) + "." + strconv.Itoa(rands.Int(0, 255)) + "." + strconv.Itoa(rands.Int(0, 255)) + "." + strconv.Itoa(rands.Int(0, 255))),
|
IPTo: utils.IP2Long(strconv.Itoa(rands.Int(0, 255)) + "." + strconv.Itoa(rands.Int(0, 255)) + "." + strconv.Itoa(rands.Int(0, 255)) + "." + strconv.Itoa(rands.Int(0, 255))),
|
||||||
ExpiredAt: 0,
|
ExpiredAt: 0,
|
||||||
@@ -217,7 +217,7 @@ func TestIPList_ContainsIPStrings(t *testing.T) {
|
|||||||
list := NewIPList()
|
list := NewIPList()
|
||||||
for i := 0; i < 255; i++ {
|
for i := 0; i < 255; i++ {
|
||||||
list.Add(&IPItem{
|
list.Add(&IPItem{
|
||||||
Id: int64(i),
|
Id: uint64(i),
|
||||||
IPFrom: utils.IP2Long(strconv.Itoa(i) + ".168.0.1"),
|
IPFrom: utils.IP2Long(strconv.Itoa(i) + ".168.0.1"),
|
||||||
IPTo: utils.IP2Long(strconv.Itoa(i) + ".168.255.1"),
|
IPTo: utils.IP2Long(strconv.Itoa(i) + ".168.255.1"),
|
||||||
ExpiredAt: 0,
|
ExpiredAt: 0,
|
||||||
@@ -305,7 +305,7 @@ func BenchmarkIPList_Contains(b *testing.B) {
|
|||||||
var list = NewIPList()
|
var list = NewIPList()
|
||||||
for i := 1; i < 200_000; i++ {
|
for i := 1; i < 200_000; i++ {
|
||||||
list.AddDelay(&IPItem{
|
list.AddDelay(&IPItem{
|
||||||
Id: int64(i),
|
Id: uint64(i),
|
||||||
IPFrom: utils.IP2Long(strconv.Itoa(rands.Int(0, 255)) + "." + strconv.Itoa(rands.Int(0, 255)) + ".0.1"),
|
IPFrom: utils.IP2Long(strconv.Itoa(rands.Int(0, 255)) + "." + strconv.Itoa(rands.Int(0, 255)) + ".0.1"),
|
||||||
IPTo: utils.IP2Long(strconv.Itoa(rands.Int(0, 255)) + "." + strconv.Itoa(rands.Int(0, 255)) + ".0.1"),
|
IPTo: utils.IP2Long(strconv.Itoa(rands.Int(0, 255)) + "." + strconv.Itoa(rands.Int(0, 255)) + ".0.1"),
|
||||||
ExpiredAt: time.Now().Unix() + 60,
|
ExpiredAt: time.Now().Unix() + 60,
|
||||||
|
|||||||
@@ -106,6 +106,7 @@ func BenchmarkIP2RegionLibrary_Lookup(b *testing.B) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
b.Fatal(err)
|
b.Fatal(err)
|
||||||
}
|
}
|
||||||
|
b.ResetTimer()
|
||||||
|
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
_, _ = library.Lookup("8.8.8.8")
|
_, _ = library.Lookup("8.8.8.8")
|
||||||
|
|||||||
@@ -3,12 +3,27 @@
|
|||||||
package iplibrary
|
package iplibrary
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/TeaOSLab/EdgeCommon/pkg/nodeconfigs"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
||||||
|
"github.com/iwind/TeaGo/Tea"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AllowIP 检查IP是否被允许访问
|
// AllowIP 检查IP是否被允许访问
|
||||||
// 如果一个IP不在任何名单中,则允许访问
|
// 如果一个IP不在任何名单中,则允许访问
|
||||||
func AllowIP(ip string, serverId int64) (canGoNext bool, inAllowList bool) {
|
func AllowIP(ip string, serverId int64) (canGoNext bool, inAllowList bool) {
|
||||||
|
if !Tea.IsTesting() { // 如果在测试环境,我们不加入一些白名单,以便于可以在本地和局域网正常测试
|
||||||
|
// 放行lo
|
||||||
|
if ip == "127.0.0.1" || ip == "::1" {
|
||||||
|
return true, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// check node
|
||||||
|
nodeConfig, err := nodeconfigs.SharedNodeConfig()
|
||||||
|
if err == nil && nodeConfig.IPIsAutoAllowed(ip) {
|
||||||
|
return true, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var ipLong = utils.IP2Long(ip)
|
var ipLong = utils.IP2Long(ip)
|
||||||
if ipLong == 0 {
|
if ipLong == 0 {
|
||||||
return false, false
|
return false, false
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import (
|
|||||||
"github.com/iwind/TeaGo/Tea"
|
"github.com/iwind/TeaGo/Tea"
|
||||||
_ "github.com/iwind/TeaGo/bootstrap"
|
_ "github.com/iwind/TeaGo/bootstrap"
|
||||||
"github.com/iwind/TeaGo/types"
|
"github.com/iwind/TeaGo/types"
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
"os"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -90,7 +89,7 @@ func (this *CityManager) Lookup(provinceId int64, cityName string) (cityId int64
|
|||||||
|
|
||||||
// 从缓存中读取
|
// 从缓存中读取
|
||||||
func (this *CityManager) load() error {
|
func (this *CityManager) load() error {
|
||||||
data, err := ioutil.ReadFile(this.cacheFile)
|
data, err := os.ReadFile(this.cacheFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
return nil
|
return nil
|
||||||
@@ -119,7 +118,7 @@ func (this *CityManager) loop() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
resp, err := rpcClient.RegionCityRPC().FindAllEnabledRegionCities(rpcClient.Context(), &pb.FindAllEnabledRegionCitiesRequest{})
|
resp, err := rpcClient.RegionCityRPC().FindAllRegionCities(rpcClient.Context(), &pb.FindAllRegionCitiesRequest{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -151,6 +150,6 @@ func (this *CityManager) loop() error {
|
|||||||
|
|
||||||
// 保存到本地缓存
|
// 保存到本地缓存
|
||||||
|
|
||||||
err = ioutil.WriteFile(this.cacheFile, data, 0666)
|
err = os.WriteFile(this.cacheFile, data, 0666)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import (
|
|||||||
"github.com/TeaOSLab/EdgeNode/internal/rpc"
|
"github.com/TeaOSLab/EdgeNode/internal/rpc"
|
||||||
"github.com/iwind/TeaGo/Tea"
|
"github.com/iwind/TeaGo/Tea"
|
||||||
_ "github.com/iwind/TeaGo/bootstrap"
|
_ "github.com/iwind/TeaGo/bootstrap"
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
"os"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -89,7 +88,7 @@ func (this *CountryManager) Lookup(countryName string) (countryId int64) {
|
|||||||
|
|
||||||
// 从缓存中读取
|
// 从缓存中读取
|
||||||
func (this *CountryManager) load() error {
|
func (this *CountryManager) load() error {
|
||||||
data, err := ioutil.ReadFile(this.cacheFile)
|
data, err := os.ReadFile(this.cacheFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
return nil
|
return nil
|
||||||
@@ -118,7 +117,7 @@ func (this *CountryManager) loop() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
resp, err := rpcClient.RegionCountryRPC().FindAllEnabledRegionCountries(rpcClient.Context(), &pb.FindAllEnabledRegionCountriesRequest{})
|
resp, err := rpcClient.RegionCountryRPC().FindAllRegionCountries(rpcClient.Context(), &pb.FindAllRegionCountriesRequest{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -149,6 +148,6 @@ func (this *CountryManager) loop() error {
|
|||||||
this.locker.Unlock()
|
this.locker.Unlock()
|
||||||
|
|
||||||
// 保存到本地缓存
|
// 保存到本地缓存
|
||||||
err = ioutil.WriteFile(this.cacheFile, data, 0666)
|
err = os.WriteFile(this.cacheFile, data, 0666)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import (
|
|||||||
"github.com/TeaOSLab/EdgeNode/internal/rpc"
|
"github.com/TeaOSLab/EdgeNode/internal/rpc"
|
||||||
"github.com/iwind/TeaGo/Tea"
|
"github.com/iwind/TeaGo/Tea"
|
||||||
_ "github.com/iwind/TeaGo/bootstrap"
|
_ "github.com/iwind/TeaGo/bootstrap"
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
"os"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -89,7 +88,7 @@ func (this *ProviderManager) Lookup(providerName string) (providerId int64) {
|
|||||||
|
|
||||||
// 从缓存中读取
|
// 从缓存中读取
|
||||||
func (this *ProviderManager) load() error {
|
func (this *ProviderManager) load() error {
|
||||||
data, err := ioutil.ReadFile(this.cacheFile)
|
data, err := os.ReadFile(this.cacheFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
return nil
|
return nil
|
||||||
@@ -118,7 +117,7 @@ func (this *ProviderManager) loop() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
resp, err := rpcClient.RegionProviderRPC().FindAllEnabledRegionProviders(rpcClient.Context(), &pb.FindAllEnabledRegionProvidersRequest{})
|
resp, err := rpcClient.RegionProviderRPC().FindAllRegionProviders(rpcClient.Context(), &pb.FindAllRegionProvidersRequest{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -150,6 +149,6 @@ func (this *ProviderManager) loop() error {
|
|||||||
|
|
||||||
// 保存到本地缓存
|
// 保存到本地缓存
|
||||||
|
|
||||||
err = ioutil.WriteFile(this.cacheFile, data, 0666)
|
err = os.WriteFile(this.cacheFile, data, 0666)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import (
|
|||||||
"github.com/TeaOSLab/EdgeNode/internal/rpc"
|
"github.com/TeaOSLab/EdgeNode/internal/rpc"
|
||||||
"github.com/iwind/TeaGo/Tea"
|
"github.com/iwind/TeaGo/Tea"
|
||||||
_ "github.com/iwind/TeaGo/bootstrap"
|
_ "github.com/iwind/TeaGo/bootstrap"
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
"os"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -93,7 +92,7 @@ func (this *ProvinceManager) Lookup(provinceName string) (provinceId int64) {
|
|||||||
|
|
||||||
// 从缓存中读取
|
// 从缓存中读取
|
||||||
func (this *ProvinceManager) load() error {
|
func (this *ProvinceManager) load() error {
|
||||||
data, err := ioutil.ReadFile(this.cacheFile)
|
data, err := os.ReadFile(this.cacheFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
return nil
|
return nil
|
||||||
@@ -122,7 +121,7 @@ func (this *ProvinceManager) loop() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
resp, err := rpcClient.RegionProvinceRPC().FindAllEnabledRegionProvincesWithCountryId(rpcClient.Context(), &pb.FindAllEnabledRegionProvincesWithCountryIdRequest{
|
resp, err := rpcClient.RegionProvinceRPC().FindAllRegionProvincesWithRegionCountryId(rpcClient.Context(), &pb.FindAllRegionProvincesWithRegionCountryIdRequest{
|
||||||
RegionCountryId: ChinaCountryId,
|
RegionCountryId: ChinaCountryId,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -156,6 +155,6 @@ func (this *ProvinceManager) loop() error {
|
|||||||
|
|
||||||
// 保存到本地缓存
|
// 保存到本地缓存
|
||||||
|
|
||||||
err = ioutil.WriteFile(this.cacheFile, data, 0666)
|
err = os.WriteFile(this.cacheFile, data, 0666)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,18 +23,19 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
const MaxQueueSize = 10240
|
const MaxQueueSize = 256 // TODO 可以配置,可以在单个任务里配置
|
||||||
|
|
||||||
// Task 单个指标任务
|
// Task 单个指标任务
|
||||||
// 数据库存储:
|
// 数据库存储:
|
||||||
// data/
|
//
|
||||||
// metric.$ID.db
|
// data/
|
||||||
// stats
|
// metric.$ID.db
|
||||||
// id, keys, value, time, serverId, hash
|
// stats
|
||||||
// 原理:
|
// id, keys, value, time, serverId, hash
|
||||||
// 添加或者有变更时 isUploaded = false
|
// 原理:
|
||||||
// 上传时检查 isUploaded 状态
|
// 添加或者有变更时 isUploaded = false
|
||||||
// 只上传每个服务中排序最前面的 N 个数据
|
// 上传时检查 isUploaded 状态
|
||||||
|
// 只上传每个服务中排序最前面的 N 个数据
|
||||||
type Task struct {
|
type Task struct {
|
||||||
item *serverconfigs.MetricItemConfig
|
item *serverconfigs.MetricItemConfig
|
||||||
isLoaded bool
|
isLoaded bool
|
||||||
@@ -58,7 +59,7 @@ type Task struct {
|
|||||||
timeMap map[string]zero.Zero // time => bool
|
timeMap map[string]zero.Zero // time => bool
|
||||||
serverIdMapLocker sync.Mutex
|
serverIdMapLocker sync.Mutex
|
||||||
|
|
||||||
statsMap map[string]*Stat
|
statsMap map[string]*Stat // 待写入队列,hash => *Stat
|
||||||
statsLocker sync.Mutex
|
statsLocker sync.Mutex
|
||||||
statsTicker *utils.Ticker
|
statsTicker *utils.Ticker
|
||||||
}
|
}
|
||||||
@@ -210,7 +211,7 @@ func (this *Task) Start() error {
|
|||||||
var tr = trackers.Begin("[METRIC]UPLOAD_STATS")
|
var tr = trackers.Begin("[METRIC]UPLOAD_STATS")
|
||||||
err := this.Upload(1 * time.Second)
|
err := this.Upload(1 * time.Second)
|
||||||
tr.End()
|
tr.End()
|
||||||
if err != nil {
|
if err != nil && !rpc.IsConnError(err) {
|
||||||
remotelogs.Error("METRIC", "upload stats failed: "+err.Error())
|
remotelogs.Error("METRIC", "upload stats failed: "+err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -372,7 +373,9 @@ func (this *Task) Upload(pauseDuration time.Duration) error {
|
|||||||
for _, serverId := range serverIds {
|
for _, serverId := range serverIds {
|
||||||
for _, currentTime := range times {
|
for _, currentTime := range times {
|
||||||
idStrings, err := func(serverId int64, currentTime string) (ids []string, err error) {
|
idStrings, err := func(serverId int64, currentTime string) (ids []string, err error) {
|
||||||
|
var t = trackers.Begin("[METRIC]SELECT_TOP_STMT")
|
||||||
rows, err := this.selectTopStmt.Query(serverId, this.item.Version, currentTime)
|
rows, err := this.selectTopStmt.Query(serverId, this.item.Version, currentTime)
|
||||||
|
t.End()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,32 +1,30 @@
|
|||||||
package nodes
|
package nodes
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/TeaOSLab/EdgeCommon/pkg/messageconfigs"
|
"github.com/TeaOSLab/EdgeCommon/pkg/messageconfigs"
|
||||||
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
||||||
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
|
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/caches"
|
"github.com/TeaOSLab/EdgeNode/internal/caches"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/compressions"
|
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/configs"
|
"github.com/TeaOSLab/EdgeNode/internal/configs"
|
||||||
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/errors"
|
"github.com/TeaOSLab/EdgeNode/internal/errors"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/events"
|
"github.com/TeaOSLab/EdgeNode/internal/events"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/firewalls"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/goman"
|
"github.com/TeaOSLab/EdgeNode/internal/goman"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
|
"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/rpc"
|
"github.com/TeaOSLab/EdgeNode/internal/rpc"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
||||||
"github.com/iwind/TeaGo/Tea"
|
"github.com/iwind/TeaGo/Tea"
|
||||||
"io"
|
"github.com/iwind/TeaGo/maps"
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
"net/url"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
|
"regexp"
|
||||||
|
"runtime"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -111,14 +109,12 @@ func (this *APIStream) loop() error {
|
|||||||
err = this.handleStatCache(message)
|
err = this.handleStatCache(message)
|
||||||
case messageconfigs.MessageCodeCleanCache: // 清理缓存
|
case messageconfigs.MessageCodeCleanCache: // 清理缓存
|
||||||
err = this.handleCleanCache(message)
|
err = this.handleCleanCache(message)
|
||||||
case messageconfigs.MessageCodePurgeCache: // 删除缓存
|
|
||||||
err = this.handlePurgeCache(message)
|
|
||||||
case messageconfigs.MessageCodePreheatCache: // 预热缓存
|
|
||||||
err = this.handlePreheatCache(message)
|
|
||||||
case messageconfigs.MessageCodeNewNodeTask: // 有新的任务
|
case messageconfigs.MessageCodeNewNodeTask: // 有新的任务
|
||||||
err = this.handleNewNodeTask(message)
|
err = this.handleNewNodeTask(message)
|
||||||
case messageconfigs.MessageCodeCheckSystemdService: // 检查Systemd服务
|
case messageconfigs.MessageCodeCheckSystemdService: // 检查Systemd服务
|
||||||
err = this.handleCheckSystemdService(message)
|
err = this.handleCheckSystemdService(message)
|
||||||
|
case messageconfigs.MessageCodeCheckLocalFirewall: // 检查本地防火墙
|
||||||
|
err = this.handleCheckLocalFirewall(message)
|
||||||
case messageconfigs.MessageCodeChangeAPINode: // 修改API节点地址
|
case messageconfigs.MessageCodeChangeAPINode: // 修改API节点地址
|
||||||
err = this.handleChangeAPINode(message)
|
err = this.handleChangeAPINode(message)
|
||||||
default:
|
default:
|
||||||
@@ -328,224 +324,6 @@ func (this *APIStream) handleCleanCache(message *pb.NodeStreamMessage) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// 删除缓存
|
|
||||||
func (this *APIStream) handlePurgeCache(message *pb.NodeStreamMessage) error {
|
|
||||||
msg := &messageconfigs.PurgeCacheMessage{}
|
|
||||||
err := json.Unmarshal(message.DataJSON, msg)
|
|
||||||
if err != nil {
|
|
||||||
this.replyFail(message.RequestId, "decode message data failed: "+err.Error())
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
storage, shouldStop, err := this.cacheStorage(message, msg.CachePolicyJSON)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if shouldStop {
|
|
||||||
defer func() {
|
|
||||||
storage.Stop()
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
// WEBP缓存
|
|
||||||
if msg.Type == "file" {
|
|
||||||
var keys = msg.Keys
|
|
||||||
for _, key := range keys {
|
|
||||||
keys = append(keys,
|
|
||||||
key+caches.SuffixMethod+"HEAD",
|
|
||||||
key+caches.SuffixWebP,
|
|
||||||
key+caches.SuffixPartial,
|
|
||||||
)
|
|
||||||
// TODO 根据实际缓存的内容进行组合
|
|
||||||
for _, encoding := range compressions.AllEncodings() {
|
|
||||||
keys = append(keys, key+caches.SuffixCompression+encoding)
|
|
||||||
keys = append(keys, key+caches.SuffixWebP+caches.SuffixCompression+encoding)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
msg.Keys = keys
|
|
||||||
}
|
|
||||||
|
|
||||||
err = storage.Purge(msg.Keys, msg.Type)
|
|
||||||
if err != nil {
|
|
||||||
this.replyFail(message.RequestId, "purge keys failed: "+err.Error())
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
this.replyOk(message.RequestId, "ok")
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// 预热缓存
|
|
||||||
func (this *APIStream) handlePreheatCache(message *pb.NodeStreamMessage) error {
|
|
||||||
msg := &messageconfigs.PreheatCacheMessage{}
|
|
||||||
err := json.Unmarshal(message.DataJSON, msg)
|
|
||||||
if err != nil {
|
|
||||||
this.replyFail(message.RequestId, "decode message data failed: "+err.Error())
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
storage, shouldStop, err := this.cacheStorage(message, msg.CachePolicyJSON)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if shouldStop {
|
|
||||||
defer func() {
|
|
||||||
storage.Stop()
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(msg.Keys) == 0 {
|
|
||||||
this.replyOk(message.RequestId, "ok")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
wg := sync.WaitGroup{}
|
|
||||||
wg.Add(len(msg.Keys))
|
|
||||||
client := &http.Client{
|
|
||||||
Timeout: 30 * time.Second, // TODO 可以设置请求超时时间
|
|
||||||
Transport: &http.Transport{
|
|
||||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
||||||
_, port, err := net.SplitHostPort(addr)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return net.Dial(network, "127.0.0.1:"+port)
|
|
||||||
},
|
|
||||||
MaxIdleConns: 4096,
|
|
||||||
MaxIdleConnsPerHost: 32,
|
|
||||||
MaxConnsPerHost: 32,
|
|
||||||
IdleConnTimeout: 2 * time.Minute,
|
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
|
||||||
TLSHandshakeTimeout: 0,
|
|
||||||
TLSClientConfig: &tls.Config{
|
|
||||||
InsecureSkipVerify: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
defer client.CloseIdleConnections()
|
|
||||||
errorMessages := []string{}
|
|
||||||
locker := sync.Mutex{}
|
|
||||||
for _, key := range msg.Keys {
|
|
||||||
go func(key string) {
|
|
||||||
defer wg.Done()
|
|
||||||
|
|
||||||
req, err := http.NewRequest(http.MethodGet, key, nil)
|
|
||||||
if err != nil {
|
|
||||||
locker.Lock()
|
|
||||||
errorMessages = append(errorMessages, "invalid url: "+key+": "+err.Error())
|
|
||||||
locker.Unlock()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO 可以在管理界面自定义Header
|
|
||||||
req.Header.Set("X-Cache-Action", "preheat")
|
|
||||||
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36")
|
|
||||||
req.Header.Set("Accept-Encoding", "gzip, deflate, br") // TODO 这里需要记录下缓存是否为gzip的
|
|
||||||
resp, err := client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
locker.Lock()
|
|
||||||
errorMessages = append(errorMessages, "request failed: "+key+": "+err.Error())
|
|
||||||
locker.Unlock()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if resp.StatusCode != 200 {
|
|
||||||
locker.Lock()
|
|
||||||
errorMessages = append(errorMessages, "request failed: "+key+": status code '"+strconv.Itoa(resp.StatusCode)+"'")
|
|
||||||
locker.Unlock()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
_ = resp.Body.Close()
|
|
||||||
}()
|
|
||||||
|
|
||||||
// 检查最大内容长度
|
|
||||||
// TODO 需要解决Chunked Transfer Encoding的长度判断问题
|
|
||||||
maxSize := storage.Policy().MaxSizeBytes()
|
|
||||||
if maxSize > 0 && resp.ContentLength > maxSize {
|
|
||||||
locker.Lock()
|
|
||||||
errorMessages = append(errorMessages, "request failed: the content is too larger than policy setting")
|
|
||||||
locker.Unlock()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
expiredAt := time.Now().Unix() + 8600
|
|
||||||
writer, err := storage.OpenWriter(key, expiredAt, 200, resp.ContentLength, -1, false) // TODO 可以设置缓存过期时间
|
|
||||||
if err != nil {
|
|
||||||
locker.Lock()
|
|
||||||
errorMessages = append(errorMessages, "open cache writer failed: "+key+": "+err.Error())
|
|
||||||
locker.Unlock()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
buf := make([]byte, 16*1024)
|
|
||||||
isClosed := false
|
|
||||||
|
|
||||||
// 写入Header
|
|
||||||
for k, v := range resp.Header {
|
|
||||||
for _, v1 := range v {
|
|
||||||
_, err = writer.WriteHeader([]byte(k + ":" + v1 + "\n"))
|
|
||||||
if err != nil {
|
|
||||||
locker.Lock()
|
|
||||||
errorMessages = append(errorMessages, "write failed: "+key+": "+err.Error())
|
|
||||||
locker.Unlock()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 写入Body
|
|
||||||
for {
|
|
||||||
n, err := resp.Body.Read(buf)
|
|
||||||
if n > 0 {
|
|
||||||
_, writerErr := writer.Write(buf[:n])
|
|
||||||
if writerErr != nil {
|
|
||||||
locker.Lock()
|
|
||||||
errorMessages = append(errorMessages, "write failed: "+key+": "+writerErr.Error())
|
|
||||||
locker.Unlock()
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
if err == io.EOF {
|
|
||||||
|
|
||||||
err = writer.Close()
|
|
||||||
if err == nil {
|
|
||||||
storage.AddToList(&caches.Item{
|
|
||||||
Type: writer.ItemType(),
|
|
||||||
Key: key,
|
|
||||||
ExpiredAt: expiredAt,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
isClosed = true
|
|
||||||
} else {
|
|
||||||
locker.Lock()
|
|
||||||
errorMessages = append(errorMessages, "read url failed: "+key+": "+err.Error())
|
|
||||||
locker.Unlock()
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !isClosed {
|
|
||||||
_ = writer.Close()
|
|
||||||
}
|
|
||||||
}(key)
|
|
||||||
}
|
|
||||||
wg.Wait()
|
|
||||||
|
|
||||||
if len(errorMessages) > 0 {
|
|
||||||
this.replyFail(message.RequestId, strings.Join(errorMessages, ", "))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
this.replyOk(message.RequestId, "ok")
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// 处理配置变化
|
// 处理配置变化
|
||||||
func (this *APIStream) handleNewNodeTask(message *pb.NodeStreamMessage) error {
|
func (this *APIStream) handleNewNodeTask(message *pb.NodeStreamMessage) error {
|
||||||
select {
|
select {
|
||||||
@@ -569,7 +347,7 @@ func (this *APIStream) handleCheckSystemdService(message *pb.NodeStreamMessage)
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
cmd := utils.NewCommandExecutor()
|
var cmd = utils.NewCommandExecutor()
|
||||||
shortName := teaconst.SystemdServiceName
|
shortName := teaconst.SystemdServiceName
|
||||||
cmd.Add(systemctl, "is-enabled", shortName)
|
cmd.Add(systemctl, "is-enabled", shortName)
|
||||||
output, err := cmd.Run()
|
output, err := cmd.Run()
|
||||||
@@ -585,6 +363,63 @@ func (this *APIStream) handleCheckSystemdService(message *pb.NodeStreamMessage)
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 检查本地防火墙
|
||||||
|
func (this *APIStream) handleCheckLocalFirewall(message *pb.NodeStreamMessage) error {
|
||||||
|
var dataMessage = &messageconfigs.CheckLocalFirewallMessage{}
|
||||||
|
err := json.Unmarshal(message.DataJSON, dataMessage)
|
||||||
|
if err != nil {
|
||||||
|
this.replyFail(message.RequestId, "decode message data failed: "+err.Error())
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// nft
|
||||||
|
if dataMessage.Name == "nftables" {
|
||||||
|
if runtime.GOOS != "linux" {
|
||||||
|
this.replyFail(message.RequestId, "not Linux system")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
nft, err := exec.LookPath("nft")
|
||||||
|
if err != nil {
|
||||||
|
this.replyFail(message.RequestId, "'nft' not found: "+err.Error())
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var cmd = exec.Command(nft, "--version")
|
||||||
|
var output = &bytes.Buffer{}
|
||||||
|
cmd.Stdout = output
|
||||||
|
err = cmd.Run()
|
||||||
|
if err != nil {
|
||||||
|
this.replyFail(message.RequestId, "get version failed: "+err.Error())
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var outputString = output.String()
|
||||||
|
var versionMatches = regexp.MustCompile(`nftables v([\d.]+)`).FindStringSubmatch(outputString)
|
||||||
|
if len(versionMatches) <= 1 {
|
||||||
|
this.replyFail(message.RequestId, "can not get nft version")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var version = versionMatches[1]
|
||||||
|
|
||||||
|
var result = maps.Map{
|
||||||
|
"version": version,
|
||||||
|
}
|
||||||
|
|
||||||
|
var protectionConfig = sharedNodeConfig.DDoSProtection
|
||||||
|
err = firewalls.SharedDDoSProtectionManager.Apply(protectionConfig)
|
||||||
|
if err != nil {
|
||||||
|
this.replyFail(message.RequestId, dataMessage.Name+"was installed, but apply DDoS protection config failed: "+err.Error())
|
||||||
|
} else {
|
||||||
|
this.replyOk(message.RequestId, string(result.AsJSON()))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.replyFail(message.RequestId, "invalid firewall name '"+dataMessage.Name+"'")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// 修改API地址
|
// 修改API地址
|
||||||
func (this *APIStream) handleChangeAPINode(message *pb.NodeStreamMessage) error {
|
func (this *APIStream) handleChangeAPINode(message *pb.NodeStreamMessage) error {
|
||||||
config, err := configs.LoadAPIConfig()
|
config, err := configs.LoadAPIConfig()
|
||||||
@@ -660,6 +495,11 @@ func (this *APIStream) replyOk(requestId int64, message string) {
|
|||||||
_ = this.stream.Send(&pb.NodeStreamMessage{RequestId: requestId, IsOk: true, Message: message})
|
_ = this.stream.Send(&pb.NodeStreamMessage{RequestId: requestId, IsOk: true, Message: message})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 回复成功并包含数据
|
||||||
|
func (this *APIStream) replyOkData(requestId int64, message string, dataJSON []byte) {
|
||||||
|
_ = this.stream.Send(&pb.NodeStreamMessage{RequestId: requestId, IsOk: true, Message: message, DataJSON: dataJSON})
|
||||||
|
}
|
||||||
|
|
||||||
// 获取缓存存取对象
|
// 获取缓存存取对象
|
||||||
func (this *APIStream) cacheStorage(message *pb.NodeStreamMessage, cachePolicyJSON []byte) (storage caches.StorageInterface, shouldStop bool, err error) {
|
func (this *APIStream) cacheStorage(message *pb.NodeStreamMessage, cachePolicyJSON []byte) (storage caches.StorageInterface, shouldStop bool, err error) {
|
||||||
cachePolicy := &serverconfigs.HTTPCachePolicy{}
|
cachePolicy := &serverconfigs.HTTPCachePolicy{}
|
||||||
|
|||||||
@@ -7,13 +7,14 @@ import (
|
|||||||
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
|
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
|
||||||
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/iplibrary"
|
"github.com/TeaOSLab/EdgeNode/internal/iplibrary"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/ratelimit"
|
"github.com/TeaOSLab/EdgeNode/internal/stats"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/ttlcache"
|
"github.com/TeaOSLab/EdgeNode/internal/ttlcache"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/waf"
|
"github.com/TeaOSLab/EdgeNode/internal/waf"
|
||||||
"github.com/iwind/TeaGo/types"
|
"github.com/iwind/TeaGo/types"
|
||||||
"net"
|
"net"
|
||||||
"os"
|
"os"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
@@ -21,19 +22,20 @@ import (
|
|||||||
|
|
||||||
// ClientConn 客户端连接
|
// ClientConn 客户端连接
|
||||||
type ClientConn struct {
|
type ClientConn struct {
|
||||||
once sync.Once
|
once sync.Once
|
||||||
globalLimiter *ratelimit.Counter
|
|
||||||
|
|
||||||
isTLS bool
|
isTLS bool
|
||||||
hasDeadline bool
|
hasDeadline bool
|
||||||
hasRead bool
|
hasRead bool
|
||||||
|
|
||||||
|
isLO bool // 是否为环路
|
||||||
|
|
||||||
hasResetSYNFlood bool
|
hasResetSYNFlood bool
|
||||||
|
|
||||||
BaseClientConn
|
BaseClientConn
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewClientConn(conn net.Conn, isTLS bool, quickClose bool, globalLimiter *ratelimit.Counter) net.Conn {
|
func NewClientConn(conn net.Conn, isTLS bool, quickClose bool) net.Conn {
|
||||||
if quickClose {
|
if quickClose {
|
||||||
// TCP
|
// TCP
|
||||||
tcpConn, ok := conn.(*net.TCPConn)
|
tcpConn, ok := conn.(*net.TCPConn)
|
||||||
@@ -43,10 +45,28 @@ func NewClientConn(conn net.Conn, isTLS bool, quickClose bool, globalLimiter *ra
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &ClientConn{BaseClientConn: BaseClientConn{rawConn: conn}, isTLS: isTLS, globalLimiter: globalLimiter}
|
// 是否为环路
|
||||||
|
var remoteAddr = conn.RemoteAddr().String()
|
||||||
|
var isLO = strings.HasPrefix(remoteAddr, "127.0.0.1:") || strings.HasPrefix(remoteAddr, "[::1]:")
|
||||||
|
|
||||||
|
return &ClientConn{
|
||||||
|
BaseClientConn: BaseClientConn{rawConn: conn},
|
||||||
|
isTLS: isTLS,
|
||||||
|
isLO: isLO,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (this *ClientConn) Read(b []byte) (n int, err error) {
|
func (this *ClientConn) Read(b []byte) (n int, err error) {
|
||||||
|
// 环路直接读取
|
||||||
|
if this.isLO {
|
||||||
|
n, err = this.rawConn.Read(b)
|
||||||
|
if n > 0 {
|
||||||
|
atomic.AddUint64(&teaconst.InTrafficBytes, uint64(n))
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// TLS
|
||||||
if this.isTLS {
|
if this.isTLS {
|
||||||
if !this.hasDeadline {
|
if !this.hasDeadline {
|
||||||
_ = this.rawConn.SetReadDeadline(time.Now().Add(time.Duration(nodeconfigs.DefaultTLSHandshakeTimeout) * time.Second)) // TODO 握手超时时间可以设置
|
_ = this.rawConn.SetReadDeadline(time.Now().Add(time.Duration(nodeconfigs.DefaultTLSHandshakeTimeout) * time.Second)) // TODO 握手超时时间可以设置
|
||||||
@@ -57,6 +77,7 @@ func (this *ClientConn) Read(b []byte) (n int, err error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 开始读取
|
||||||
n, err = this.rawConn.Read(b)
|
n, err = this.rawConn.Read(b)
|
||||||
if n > 0 {
|
if n > 0 {
|
||||||
atomic.AddUint64(&teaconst.InTrafficBytes, uint64(n))
|
atomic.AddUint64(&teaconst.InTrafficBytes, uint64(n))
|
||||||
@@ -65,18 +86,21 @@ func (this *ClientConn) Read(b []byte) (n int, err error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SYN Flood检测
|
|
||||||
var isHandshakeError = err != nil && os.IsTimeout(err) && !this.hasRead
|
var isHandshakeError = err != nil && os.IsTimeout(err) && !this.hasRead
|
||||||
if isHandshakeError {
|
if isHandshakeError {
|
||||||
_ = this.SetLinger(0)
|
_ = this.SetLinger(0)
|
||||||
}
|
}
|
||||||
var synFloodConfig = sharedNodeConfig.SYNFloodConfig()
|
|
||||||
if synFloodConfig != nil && synFloodConfig.IsOn {
|
// SYN Flood检测
|
||||||
if isHandshakeError {
|
if this.serverId == 0 || !this.hasResetSYNFlood {
|
||||||
this.increaseSYNFlood(synFloodConfig)
|
var synFloodConfig = sharedNodeConfig.SYNFloodConfig()
|
||||||
} else if err == nil && !this.hasResetSYNFlood {
|
if synFloodConfig != nil && synFloodConfig.IsOn {
|
||||||
this.hasResetSYNFlood = true
|
if isHandshakeError {
|
||||||
this.resetSYNFlood()
|
this.increaseSYNFlood(synFloodConfig)
|
||||||
|
} else if err == nil && !this.hasResetSYNFlood {
|
||||||
|
this.hasResetSYNFlood = true
|
||||||
|
this.resetSYNFlood()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,7 +111,15 @@ func (this *ClientConn) Write(b []byte) (n int, err error) {
|
|||||||
n, err = this.rawConn.Write(b)
|
n, err = this.rawConn.Write(b)
|
||||||
if n > 0 {
|
if n > 0 {
|
||||||
atomic.AddUint64(&teaconst.OutTrafficBytes, uint64(n))
|
atomic.AddUint64(&teaconst.OutTrafficBytes, uint64(n))
|
||||||
|
|
||||||
|
// 统计当前服务带宽
|
||||||
|
if this.serverId > 0 {
|
||||||
|
if !this.isLO { // 环路不统计带宽,避免缓存预热等行为产生带宽
|
||||||
|
stats.SharedBandwidthStatManager.Add(this.userId, this.serverId, int64(n))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,14 +128,8 @@ func (this *ClientConn) Close() error {
|
|||||||
|
|
||||||
err := this.rawConn.Close()
|
err := this.rawConn.Close()
|
||||||
|
|
||||||
// 全局并发数限制
|
|
||||||
this.once.Do(func() {
|
|
||||||
if this.globalLimiter != nil {
|
|
||||||
this.globalLimiter.Release()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// 单个服务并发数限制
|
// 单个服务并发数限制
|
||||||
|
// 不能加条件限制,因为服务配置随时有变化
|
||||||
sharedClientConnLimiter.Remove(this.rawConn.RemoteAddr().String())
|
sharedClientConnLimiter.Remove(this.rawConn.RemoteAddr().String())
|
||||||
|
|
||||||
return err
|
return err
|
||||||
@@ -137,7 +163,7 @@ func (this *ClientConn) increaseSYNFlood(synFloodConfig *firewallconfigs.SYNFloo
|
|||||||
var ip = this.RawIP()
|
var ip = this.RawIP()
|
||||||
if len(ip) > 0 && !iplibrary.IsInWhiteList(ip) && (!synFloodConfig.IgnoreLocal || !utils.IsLocalIP(ip)) {
|
if len(ip) > 0 && !iplibrary.IsInWhiteList(ip) && (!synFloodConfig.IgnoreLocal || !utils.IsLocalIP(ip)) {
|
||||||
var timestamp = utils.NextMinuteUnixTime()
|
var timestamp = utils.NextMinuteUnixTime()
|
||||||
var result = ttlcache.SharedCache.IncreaseInt64("SYN_FLOOD:"+ip, 1, timestamp)
|
var result = ttlcache.SharedCache.IncreaseInt64("SYN_FLOOD:"+ip, 1, timestamp, true)
|
||||||
var minAttempts = synFloodConfig.MinAttempts
|
var minAttempts = synFloodConfig.MinAttempts
|
||||||
if minAttempts < 5 {
|
if minAttempts < 5 {
|
||||||
minAttempts = 5
|
minAttempts = 5
|
||||||
|
|||||||
@@ -8,8 +8,10 @@ type BaseClientConn struct {
|
|||||||
rawConn net.Conn
|
rawConn net.Conn
|
||||||
|
|
||||||
isBound bool
|
isBound bool
|
||||||
|
userId int64
|
||||||
serverId int64
|
serverId int64
|
||||||
remoteAddr string
|
remoteAddr string
|
||||||
|
hasLimit bool
|
||||||
|
|
||||||
isClosed bool
|
isClosed bool
|
||||||
}
|
}
|
||||||
@@ -31,11 +33,32 @@ func (this *BaseClientConn) Bind(serverId int64, remoteAddr string, maxConnsPerS
|
|||||||
this.isBound = true
|
this.isBound = true
|
||||||
this.serverId = serverId
|
this.serverId = serverId
|
||||||
this.remoteAddr = remoteAddr
|
this.remoteAddr = remoteAddr
|
||||||
|
this.hasLimit = true
|
||||||
|
|
||||||
// 检查是否可以连接
|
// 检查是否可以连接
|
||||||
return sharedClientConnLimiter.Add(this.rawConn.RemoteAddr().String(), serverId, remoteAddr, maxConnsPerServer, maxConnsPerIP)
|
return sharedClientConnLimiter.Add(this.rawConn.RemoteAddr().String(), serverId, remoteAddr, maxConnsPerServer, maxConnsPerIP)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetServerId 设置服务ID
|
||||||
|
func (this *BaseClientConn) SetServerId(serverId int64) {
|
||||||
|
this.serverId = serverId
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServerId 读取当前连接绑定的服务ID
|
||||||
|
func (this *BaseClientConn) ServerId() int64 {
|
||||||
|
return this.serverId
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetUserId 设置所属服务的用户ID
|
||||||
|
func (this *BaseClientConn) SetUserId(userId int64) {
|
||||||
|
this.userId = userId
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserId 获取当前连接所属服务的用户ID
|
||||||
|
func (this *BaseClientConn) UserId() int64 {
|
||||||
|
return this.userId
|
||||||
|
}
|
||||||
|
|
||||||
// RawIP 原本IP
|
// RawIP 原本IP
|
||||||
func (this *BaseClientConn) RawIP() string {
|
func (this *BaseClientConn) RawIP() string {
|
||||||
ip, _, _ := net.SplitHostPort(this.rawConn.RemoteAddr().String())
|
ip, _, _ := net.SplitHostPort(this.rawConn.RemoteAddr().String())
|
||||||
|
|||||||
@@ -11,4 +11,16 @@ type ClientConnInterface interface {
|
|||||||
|
|
||||||
// Bind 绑定服务
|
// Bind 绑定服务
|
||||||
Bind(serverId int64, remoteAddr string, maxConnsPerServer int, maxConnsPerIP int) bool
|
Bind(serverId int64, remoteAddr string, maxConnsPerServer int, maxConnsPerIP int) bool
|
||||||
|
|
||||||
|
// ServerId 获取服务ID
|
||||||
|
ServerId() int64
|
||||||
|
|
||||||
|
// SetServerId 设置服务ID
|
||||||
|
SetServerId(serverId int64)
|
||||||
|
|
||||||
|
// SetUserId 设置所属服务的用户ID
|
||||||
|
SetUserId(userId int64)
|
||||||
|
|
||||||
|
// UserId 获取当前连接所属服务的用户ID
|
||||||
|
UserId() int64
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,16 +3,13 @@
|
|||||||
package nodes
|
package nodes
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/TeaOSLab/EdgeCommon/pkg/nodeconfigs"
|
|
||||||
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
|
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/firewalls"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/iplibrary"
|
"github.com/TeaOSLab/EdgeNode/internal/iplibrary"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/ratelimit"
|
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/waf"
|
"github.com/TeaOSLab/EdgeNode/internal/waf"
|
||||||
"net"
|
"net"
|
||||||
)
|
)
|
||||||
|
|
||||||
var sharedConnectionsLimiter = ratelimit.NewCounter(nodeconfigs.DefaultTCPMaxConnections)
|
|
||||||
|
|
||||||
// ClientListener 客户端网络监听
|
// ClientListener 客户端网络监听
|
||||||
type ClientListener struct {
|
type ClientListener struct {
|
||||||
rawListener net.Listener
|
rawListener net.Listener
|
||||||
@@ -36,13 +33,8 @@ func (this *ClientListener) IsTLS() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (this *ClientListener) Accept() (net.Conn, error) {
|
func (this *ClientListener) Accept() (net.Conn, error) {
|
||||||
// 限制并发连接数
|
|
||||||
var limiter = sharedConnectionsLimiter
|
|
||||||
limiter.Ack()
|
|
||||||
|
|
||||||
conn, err := this.rawListener.Accept()
|
conn, err := this.rawListener.Accept()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
limiter.Release()
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,22 +42,30 @@ func (this *ClientListener) Accept() (net.Conn, error) {
|
|||||||
ip, _, err := net.SplitHostPort(conn.RemoteAddr().String())
|
ip, _, err := net.SplitHostPort(conn.RemoteAddr().String())
|
||||||
if err == nil {
|
if err == nil {
|
||||||
canGoNext, _ := iplibrary.AllowIP(ip, 0)
|
canGoNext, _ := iplibrary.AllowIP(ip, 0)
|
||||||
|
var beingDenied = !waf.SharedIPWhiteList.Contains(waf.IPTypeAll, firewallconfigs.FirewallScopeGlobal, 0, ip) &&
|
||||||
|
waf.SharedIPBlackList.Contains(waf.IPTypeAll, firewallconfigs.FirewallScopeGlobal, 0, ip)
|
||||||
|
|
||||||
if !canGoNext ||
|
if !canGoNext || beingDenied {
|
||||||
(!waf.SharedIPWhiteList.Contains(waf.IPTypeAll, firewallconfigs.FirewallScopeGlobal, 0, ip) &&
|
|
||||||
waf.SharedIPBlackList.Contains(waf.IPTypeAll, firewallconfigs.FirewallScopeGlobal, 0, ip)) {
|
|
||||||
tcpConn, ok := conn.(*net.TCPConn)
|
tcpConn, ok := conn.(*net.TCPConn)
|
||||||
if ok {
|
if ok {
|
||||||
_ = tcpConn.SetLinger(0)
|
_ = tcpConn.SetLinger(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
_ = conn.Close()
|
_ = conn.Close()
|
||||||
limiter.Release()
|
|
||||||
|
// 使用本地防火墙延长封禁
|
||||||
|
if beingDenied {
|
||||||
|
var fw = firewalls.Firewall()
|
||||||
|
if fw != nil && !fw.IsMock() {
|
||||||
|
_ = fw.DropSourceIP(ip, 120, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return this.Accept()
|
return this.Accept()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewClientConn(conn, this.isTLS, this.quickClose, limiter), nil
|
return NewClientConn(conn, this.isTLS, this.quickClose), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (this *ClientListener) Close() error {
|
func (this *ClientListener) Close() error {
|
||||||
|
|||||||
7
internal/nodes/conn_linger.go
Normal file
7
internal/nodes/conn_linger.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
|
||||||
|
|
||||||
|
package nodes
|
||||||
|
|
||||||
|
type LingerConn interface {
|
||||||
|
SetLinger(sec int) error
|
||||||
|
}
|
||||||
@@ -80,6 +80,13 @@ Loop:
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 发送到本地
|
||||||
|
if sharedHTTPAccessLogViewer.HasConns() {
|
||||||
|
for _, accessLog := range accessLogs {
|
||||||
|
sharedHTTPAccessLogViewer.Send(accessLog)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 发送到API
|
// 发送到API
|
||||||
if this.rpcClient == nil {
|
if this.rpcClient == nil {
|
||||||
client, err := rpc.SharedRPC()
|
client, err := rpc.SharedRPC()
|
||||||
|
|||||||
116
internal/nodes/http_access_log_viewer.go
Normal file
116
internal/nodes/http_access_log_viewer.go
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
|
||||||
|
|
||||||
|
package nodes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
||||||
|
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
|
||||||
|
"github.com/iwind/TeaGo/types"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
|
var sharedHTTPAccessLogViewer = NewHTTPAccessLogViewer()
|
||||||
|
|
||||||
|
// HTTPAccessLogViewer 本地访问日志浏览器
|
||||||
|
type HTTPAccessLogViewer struct {
|
||||||
|
sockFile string
|
||||||
|
|
||||||
|
listener net.Listener
|
||||||
|
connMap map[int64]net.Conn // connId => net.Conn
|
||||||
|
connId int64
|
||||||
|
locker sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHTTPAccessLogViewer 获取新对象
|
||||||
|
func NewHTTPAccessLogViewer() *HTTPAccessLogViewer {
|
||||||
|
return &HTTPAccessLogViewer{
|
||||||
|
sockFile: os.TempDir() + "/" + teaconst.AccessLogSockName,
|
||||||
|
connMap: map[int64]net.Conn{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start 启动
|
||||||
|
func (this *HTTPAccessLogViewer) Start() error {
|
||||||
|
this.locker.Lock()
|
||||||
|
defer this.locker.Unlock()
|
||||||
|
|
||||||
|
if this.listener == nil {
|
||||||
|
// remove if exists
|
||||||
|
_ = os.Remove(this.sockFile)
|
||||||
|
|
||||||
|
// start listening
|
||||||
|
listener, err := net.Listen("unix", this.sockFile)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
this.listener = listener
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
conn, err := this.listener.Accept()
|
||||||
|
if err != nil {
|
||||||
|
remotelogs.Error("ACCESS_LOG", "start local reading failed: "+err.Error())
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
this.locker.Lock()
|
||||||
|
var connId = this.nextConnId()
|
||||||
|
this.connMap[connId] = conn
|
||||||
|
go func() {
|
||||||
|
this.startReading(conn, connId)
|
||||||
|
}()
|
||||||
|
this.locker.Unlock()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasConns 检查是否有连接
|
||||||
|
func (this *HTTPAccessLogViewer) HasConns() bool {
|
||||||
|
this.locker.Lock()
|
||||||
|
defer this.locker.Unlock()
|
||||||
|
return len(this.connMap) > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send 发送日志
|
||||||
|
func (this *HTTPAccessLogViewer) Send(accessLog *pb.HTTPAccessLog) {
|
||||||
|
var conns = []net.Conn{}
|
||||||
|
this.locker.Lock()
|
||||||
|
for _, conn := range this.connMap {
|
||||||
|
conns = append(conns, conn)
|
||||||
|
}
|
||||||
|
this.locker.Unlock()
|
||||||
|
|
||||||
|
if len(conns) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, conn := range conns {
|
||||||
|
// ignore error
|
||||||
|
_, _ = conn.Write([]byte(accessLog.RemoteAddr + " [" + accessLog.TimeLocal + "] \"" + accessLog.RequestMethod + " " + accessLog.Scheme + "://" + accessLog.Host + accessLog.RequestURI + " " + accessLog.Proto + "\" " + types.String(accessLog.Status) + " - " + fmt.Sprintf("%.2fms", accessLog.RequestTime*1000) + "\n"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *HTTPAccessLogViewer) nextConnId() int64 {
|
||||||
|
return atomic.AddInt64(&this.connId, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *HTTPAccessLogViewer) startReading(conn net.Conn, connId int64) {
|
||||||
|
var buf = make([]byte, 1024)
|
||||||
|
for {
|
||||||
|
_, err := conn.Read(buf)
|
||||||
|
if err != nil {
|
||||||
|
this.locker.Lock()
|
||||||
|
delete(this.connMap, connId)
|
||||||
|
this.locker.Unlock()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
246
internal/nodes/http_cache_task_manager.go
Normal file
246
internal/nodes/http_cache_task_manager.go
Normal file
@@ -0,0 +1,246 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
|
||||||
|
|
||||||
|
package nodes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
|
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/caches"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/compressions"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/events"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/goman"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/rpc"
|
||||||
|
"github.com/iwind/TeaGo/Tea"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
events.On(events.EventStart, func() {
|
||||||
|
goman.New(func() {
|
||||||
|
SharedHTTPCacheTaskManager.Start()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
var SharedHTTPCacheTaskManager = NewHTTPCacheTaskManager()
|
||||||
|
|
||||||
|
// HTTPCacheTaskManager 缓存任务管理
|
||||||
|
type HTTPCacheTaskManager struct {
|
||||||
|
ticker *time.Ticker
|
||||||
|
httpClient *http.Client
|
||||||
|
protocolReg *regexp.Regexp
|
||||||
|
|
||||||
|
taskQueue chan *pb.PurgeServerCacheRequest
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHTTPCacheTaskManager() *HTTPCacheTaskManager {
|
||||||
|
var duration = 30 * time.Second
|
||||||
|
if Tea.IsTesting() {
|
||||||
|
duration = 10 * time.Second
|
||||||
|
}
|
||||||
|
return &HTTPCacheTaskManager{
|
||||||
|
ticker: time.NewTicker(duration),
|
||||||
|
httpClient: &http.Client{
|
||||||
|
Timeout: 10 * time.Minute, // TODO 可以设置请求超时时间
|
||||||
|
Transport: &http.Transport{
|
||||||
|
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||||
|
_, port, err := net.SplitHostPort(addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return net.Dial(network, "127.0.0.1:"+port)
|
||||||
|
},
|
||||||
|
MaxIdleConns: 128,
|
||||||
|
MaxIdleConnsPerHost: 32,
|
||||||
|
MaxConnsPerHost: 32,
|
||||||
|
IdleConnTimeout: 2 * time.Minute,
|
||||||
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
|
TLSHandshakeTimeout: 0,
|
||||||
|
TLSClientConfig: &tls.Config{
|
||||||
|
InsecureSkipVerify: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
protocolReg: regexp.MustCompile(`^(?i)(http|https)://`),
|
||||||
|
taskQueue: make(chan *pb.PurgeServerCacheRequest, 1024),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *HTTPCacheTaskManager) Start() {
|
||||||
|
// task queue
|
||||||
|
goman.New(func() {
|
||||||
|
rpcClient, _ := rpc.SharedRPC()
|
||||||
|
|
||||||
|
if rpcClient != nil {
|
||||||
|
for taskReq := range this.taskQueue {
|
||||||
|
_, err := rpcClient.ServerRPC().PurgeServerCache(rpcClient.Context(), taskReq)
|
||||||
|
if err != nil {
|
||||||
|
remotelogs.Error("HTTP_CACHE_TASK_MANAGER", "create purge task failed: "+err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// Loop
|
||||||
|
for range this.ticker.C {
|
||||||
|
err := this.Loop()
|
||||||
|
if err != nil {
|
||||||
|
remotelogs.Error("HTTP_CACHE_TASK_MANAGER", "execute task failed: "+err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *HTTPCacheTaskManager) Loop() error {
|
||||||
|
rpcClient, err := rpc.SharedRPC()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := rpcClient.HTTPCacheTaskKeyRPC().FindDoingHTTPCacheTaskKeys(rpcClient.Context(), &pb.FindDoingHTTPCacheTaskKeysRequest{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var keys = resp.HttpCacheTaskKeys
|
||||||
|
if len(keys) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var pbResults = []*pb.UpdateHTTPCacheTaskKeysStatusRequest_KeyResult{}
|
||||||
|
|
||||||
|
for _, key := range keys {
|
||||||
|
err = this.processKey(key)
|
||||||
|
|
||||||
|
var pbResult = &pb.UpdateHTTPCacheTaskKeysStatusRequest_KeyResult{
|
||||||
|
Id: key.Id,
|
||||||
|
NodeClusterId: key.NodeClusterId,
|
||||||
|
Error: "",
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
pbResult.Error = err.Error()
|
||||||
|
}
|
||||||
|
pbResults = append(pbResults, pbResult)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = rpcClient.HTTPCacheTaskKeyRPC().UpdateHTTPCacheTaskKeysStatus(rpcClient.Context(), &pb.UpdateHTTPCacheTaskKeysStatusRequest{KeyResults: pbResults})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *HTTPCacheTaskManager) PushTaskKeys(keys []string) {
|
||||||
|
select {
|
||||||
|
case this.taskQueue <- &pb.PurgeServerCacheRequest{
|
||||||
|
Keys: keys,
|
||||||
|
Prefixes: nil,
|
||||||
|
}:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *HTTPCacheTaskManager) processKey(key *pb.HTTPCacheTaskKey) error {
|
||||||
|
switch key.Type {
|
||||||
|
case "purge":
|
||||||
|
var storages = caches.SharedManager.FindAllStorages()
|
||||||
|
for _, storage := range storages {
|
||||||
|
switch key.KeyType {
|
||||||
|
case "key":
|
||||||
|
var cacheKeys = []string{key.Key}
|
||||||
|
if strings.HasPrefix(key.Key, "http://") {
|
||||||
|
cacheKeys = append(cacheKeys, strings.Replace(key.Key, "http://", "https://", 1))
|
||||||
|
} else if strings.HasPrefix(key.Key, "https://") {
|
||||||
|
cacheKeys = append(cacheKeys, strings.Replace(key.Key, "https://", "http://", 1))
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 提升效率
|
||||||
|
for _, cacheKey := range cacheKeys {
|
||||||
|
var subKeys = []string{
|
||||||
|
cacheKey,
|
||||||
|
cacheKey + caches.SuffixMethod + "HEAD",
|
||||||
|
cacheKey + caches.SuffixWebP,
|
||||||
|
cacheKey + caches.SuffixPartial,
|
||||||
|
}
|
||||||
|
// TODO 根据实际缓存的内容进行组合
|
||||||
|
for _, encoding := range compressions.AllEncodings() {
|
||||||
|
subKeys = append(subKeys, cacheKey+caches.SuffixCompression+encoding)
|
||||||
|
subKeys = append(subKeys, cacheKey+caches.SuffixWebP+caches.SuffixCompression+encoding)
|
||||||
|
}
|
||||||
|
|
||||||
|
err := storage.Purge(subKeys, "file")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "prefix":
|
||||||
|
var prefixes = []string{key.Key}
|
||||||
|
if strings.HasPrefix(key.Key, "http://") {
|
||||||
|
prefixes = append(prefixes, strings.Replace(key.Key, "http://", "https://", 1))
|
||||||
|
} else if strings.HasPrefix(key.Key, "https://") {
|
||||||
|
prefixes = append(prefixes, strings.Replace(key.Key, "https://", "http://", 1))
|
||||||
|
}
|
||||||
|
|
||||||
|
err := storage.Purge(prefixes, "dir")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "fetch":
|
||||||
|
err := this.fetchKey(key)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return errors.New("invalid operation type '" + key.Type + "'")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 增加失败重试
|
||||||
|
// TODO 使用并发操作
|
||||||
|
func (this *HTTPCacheTaskManager) fetchKey(key *pb.HTTPCacheTaskKey) error {
|
||||||
|
var fullKey = key.Key
|
||||||
|
if !this.protocolReg.MatchString(fullKey) {
|
||||||
|
fullKey = "https://" + fullKey
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodGet, fullKey, nil)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("invalid url: " + fullKey + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO 可以在管理界面自定义Header
|
||||||
|
req.Header.Set("X-Edge-Cache-Action", "fetch")
|
||||||
|
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36") // TODO 可以定义
|
||||||
|
req.Header.Set("Accept-Encoding", "gzip, deflate, br")
|
||||||
|
resp, err := this.httpClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("request failed: " + fullKey + ": " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
|
// 读取内容,以便于生成缓存
|
||||||
|
_, _ = io.Copy(io.Discard, resp.Body)
|
||||||
|
|
||||||
|
// 处理502
|
||||||
|
if resp.StatusCode == http.StatusBadGateway {
|
||||||
|
return errors.New("read origin site timeout")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
25
internal/nodes/http_cache_task_manager_test.go
Normal file
25
internal/nodes/http_cache_task_manager_test.go
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
|
||||||
|
|
||||||
|
package nodes_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/TeaOSLab/EdgeCommon/pkg/nodeconfigs"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/caches"
|
||||||
|
"github.com/TeaOSLab/EdgeNode/internal/nodes"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestHTTPCacheTaskManager_Loop(t *testing.T) {
|
||||||
|
// initialize cache policies
|
||||||
|
config, err := nodeconfigs.SharedNodeConfig()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
caches.SharedManager.UpdatePolicies(config.HTTPCachePolicies)
|
||||||
|
|
||||||
|
var manager = nodes.NewHTTPCacheTaskManager()
|
||||||
|
err = manager.Loop()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,16 +22,18 @@ var SharedHTTPClientPool = NewHTTPClientPool()
|
|||||||
|
|
||||||
// HTTPClientPool 客户端池
|
// HTTPClientPool 客户端池
|
||||||
type HTTPClientPool struct {
|
type HTTPClientPool struct {
|
||||||
clientExpiredDuration time.Duration
|
clientsMap map[string]*HTTPClient // backend key => client
|
||||||
clientsMap map[string]*HTTPClient // backend key => client
|
|
||||||
locker sync.Mutex
|
cleanTicker *time.Ticker
|
||||||
|
|
||||||
|
locker sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewHTTPClientPool 获取新对象
|
// NewHTTPClientPool 获取新对象
|
||||||
func NewHTTPClientPool() *HTTPClientPool {
|
func NewHTTPClientPool() *HTTPClientPool {
|
||||||
var pool = &HTTPClientPool{
|
var pool = &HTTPClientPool{
|
||||||
clientExpiredDuration: 3600 * time.Second,
|
cleanTicker: time.NewTicker(1 * time.Hour),
|
||||||
clientsMap: map[string]*HTTPClient{},
|
clientsMap: map[string]*HTTPClient{},
|
||||||
}
|
}
|
||||||
|
|
||||||
goman.New(func() {
|
goman.New(func() {
|
||||||
@@ -52,11 +54,22 @@ func (this *HTTPClientPool) Client(req *HTTPRequest,
|
|||||||
}
|
}
|
||||||
|
|
||||||
var key = origin.UniqueKey() + "@" + originAddr
|
var key = origin.UniqueKey() + "@" + originAddr
|
||||||
|
var isLnRequest = origin.Id == 0
|
||||||
|
|
||||||
|
this.locker.RLock()
|
||||||
|
client, found := this.clientsMap[key]
|
||||||
|
this.locker.RUnlock()
|
||||||
|
if found {
|
||||||
|
client.UpdateAccessTime()
|
||||||
|
return client.RawClient(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 这里不能使用RLock,避免因为并发生成多个同样的client实例
|
||||||
this.locker.Lock()
|
this.locker.Lock()
|
||||||
defer this.locker.Unlock()
|
defer this.locker.Unlock()
|
||||||
|
|
||||||
client, found := this.clientsMap[key]
|
// 再次查找
|
||||||
|
client, found = this.clientsMap[key]
|
||||||
if found {
|
if found {
|
||||||
client.UpdateAccessTime()
|
client.UpdateAccessTime()
|
||||||
return client.RawClient(), nil
|
return client.RawClient(), nil
|
||||||
@@ -89,6 +102,17 @@ func (this *HTTPClientPool) Client(req *HTTPRequest,
|
|||||||
idleConns = numberCPU * 8
|
idleConns = numberCPU * 8
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 可以判断为Ln节点请求
|
||||||
|
if isLnRequest {
|
||||||
|
maxConnections *= 8
|
||||||
|
idleConns *= 8
|
||||||
|
idleTimeout *= 4
|
||||||
|
} else if sharedNodeConfig != nil && sharedNodeConfig.Level > 1 {
|
||||||
|
// Ln节点可以适当增加连接数
|
||||||
|
maxConnections *= 2
|
||||||
|
idleConns *= 2
|
||||||
|
}
|
||||||
|
|
||||||
// TLS通讯
|
// TLS通讯
|
||||||
var tlsConfig = &tls.Config{
|
var tlsConfig = &tls.Config{
|
||||||
InsecureSkipVerify: true,
|
InsecureSkipVerify: true,
|
||||||
@@ -104,39 +128,42 @@ func (this *HTTPClientPool) Client(req *HTTPRequest,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var transport = &http.Transport{
|
var transport = &HTTPClientTransport{
|
||||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
Transport: &http.Transport{
|
||||||
// 支持TOA的连接
|
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||||
conn, err := this.handleTOA(req, ctx, network, originAddr, connectionTimeout)
|
// 支持TOA的连接
|
||||||
if conn != nil || err != nil {
|
conn, err := this.handleTOA(req, ctx, network, originAddr, connectionTimeout)
|
||||||
return conn, err
|
if conn != nil || err != nil {
|
||||||
}
|
return conn, err
|
||||||
|
}
|
||||||
|
|
||||||
// 普通的连接
|
// 普通的连接
|
||||||
conn, err = (&net.Dialer{
|
conn, err = (&net.Dialer{
|
||||||
Timeout: connectionTimeout,
|
Timeout: connectionTimeout,
|
||||||
KeepAlive: 1 * time.Minute,
|
KeepAlive: 1 * time.Minute,
|
||||||
}).DialContext(ctx, network, originAddr)
|
}).DialContext(ctx, network, originAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// 处理PROXY protocol
|
// 处理PROXY protocol
|
||||||
err = this.handlePROXYProtocol(conn, req, proxyProtocol)
|
err = this.handlePROXYProtocol(conn, req, proxyProtocol)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return conn, nil
|
return conn, nil
|
||||||
|
},
|
||||||
|
MaxIdleConns: 0,
|
||||||
|
MaxIdleConnsPerHost: idleConns,
|
||||||
|
MaxConnsPerHost: maxConnections,
|
||||||
|
IdleConnTimeout: idleTimeout,
|
||||||
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
|
TLSHandshakeTimeout: 5 * time.Second,
|
||||||
|
TLSClientConfig: tlsConfig,
|
||||||
|
ReadBufferSize: 8 * 1024,
|
||||||
|
Proxy: nil,
|
||||||
},
|
},
|
||||||
MaxIdleConns: 0,
|
|
||||||
MaxIdleConnsPerHost: idleConns,
|
|
||||||
MaxConnsPerHost: maxConnections,
|
|
||||||
IdleConnTimeout: idleTimeout,
|
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
|
||||||
TLSHandshakeTimeout: 3 * time.Second,
|
|
||||||
TLSClientConfig: tlsConfig,
|
|
||||||
Proxy: nil,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
rawClient = &http.Client{
|
rawClient = &http.Client{
|
||||||
@@ -168,13 +195,12 @@ func (this *HTTPClientPool) Client(req *HTTPRequest,
|
|||||||
|
|
||||||
// 清理不使用的Client
|
// 清理不使用的Client
|
||||||
func (this *HTTPClientPool) cleanClients() {
|
func (this *HTTPClientPool) cleanClients() {
|
||||||
var ticker = time.NewTicker(this.clientExpiredDuration)
|
for range this.cleanTicker.C {
|
||||||
for range ticker.C {
|
var nowTime = time.Now().Unix()
|
||||||
currentAt := time.Now().Unix()
|
|
||||||
|
|
||||||
this.locker.Lock()
|
this.locker.Lock()
|
||||||
for k, client := range this.clientsMap {
|
for k, client := range this.clientsMap {
|
||||||
if client.AccessTime() < currentAt+86400 { // 超过 N 秒没有调用就关闭
|
if client.AccessTime() < nowTime+86400 { // 超过 N 秒没有调用就关闭
|
||||||
delete(this.clientsMap, k)
|
delete(this.clientsMap, k)
|
||||||
client.Close()
|
client.Close()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ func TestHTTPClientPool_Client(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestHTTPClientPool_cleanClients(t *testing.T) {
|
func TestHTTPClientPool_cleanClients(t *testing.T) {
|
||||||
origin := &serverconfigs.OriginConfig{
|
var origin = &serverconfigs.OriginConfig{
|
||||||
Id: 1,
|
Id: 1,
|
||||||
Version: 2,
|
Version: 2,
|
||||||
Addr: &serverconfigs.NetworkAddressConfig{Host: "127.0.0.1", PortRange: "1234"},
|
Addr: &serverconfigs.NetworkAddressConfig{Host: "127.0.0.1", PortRange: "1234"},
|
||||||
@@ -48,8 +48,7 @@ func TestHTTPClientPool_cleanClients(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
pool := NewHTTPClientPool()
|
var pool = NewHTTPClientPool()
|
||||||
pool.clientExpiredDuration = 2 * time.Second
|
|
||||||
|
|
||||||
for i := 0; i < 10; i++ {
|
for i := 0; i < 10; i++ {
|
||||||
t.Log("get", i)
|
t.Log("get", i)
|
||||||
|
|||||||
26
internal/nodes/http_client_transport.go
Normal file
26
internal/nodes/http_client_transport.go
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
|
||||||
|
|
||||||
|
package nodes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
const emptyHTTPLocation = "/$EmptyHTTPLocation$"
|
||||||
|
|
||||||
|
type HTTPClientTransport struct {
|
||||||
|
*http.Transport
|
||||||
|
}
|
||||||
|
|
||||||
|
func (this *HTTPClientTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||||
|
resp, err := this.Transport.RoundTrip(req)
|
||||||
|
if err != nil {
|
||||||
|
return resp, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查在跳转相关状态中Location是否存在
|
||||||
|
if httpStatusIsRedirect(resp.StatusCode) && len(resp.Header.Get("Location")) == 0 {
|
||||||
|
resp.Header.Set("Location", emptyHTTPLocation)
|
||||||
|
}
|
||||||
|
return resp, nil
|
||||||
|
}
|
||||||
@@ -17,7 +17,6 @@ import (
|
|||||||
"github.com/iwind/TeaGo/maps"
|
"github.com/iwind/TeaGo/maps"
|
||||||
"github.com/iwind/TeaGo/types"
|
"github.com/iwind/TeaGo/types"
|
||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
@@ -89,7 +88,9 @@ type HTTPRequest struct {
|
|||||||
firewallRuleSetId int64
|
firewallRuleSetId int64
|
||||||
firewallRuleId int64
|
firewallRuleId int64
|
||||||
firewallActions []string
|
firewallActions []string
|
||||||
tags []string
|
wafHasRequestBody bool
|
||||||
|
|
||||||
|
tags []string
|
||||||
|
|
||||||
logAttrs map[string]string
|
logAttrs map[string]string
|
||||||
|
|
||||||
@@ -149,7 +150,7 @@ func (this *HTTPRequest) Do() {
|
|||||||
// Web配置
|
// Web配置
|
||||||
err := this.configureWeb(this.ReqServer.Web, true, 0)
|
err := this.configureWeb(this.ReqServer.Web, true, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
this.write50x(err, http.StatusInternalServerError, false)
|
this.write50x(err, http.StatusInternalServerError, "Failed to configure the server", "配置服务失败", false)
|
||||||
this.doEnd()
|
this.doEnd()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -164,15 +165,26 @@ func (this *HTTPRequest) Do() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 处理健康检查
|
||||||
|
var isHealthCheck = false
|
||||||
|
var healthCheckKey = this.RawReq.Header.Get(serverconfigs.HealthCheckHeaderName)
|
||||||
|
if len(healthCheckKey) > 0 {
|
||||||
|
if this.doHealthCheck(healthCheckKey, &isHealthCheck) {
|
||||||
|
this.doEnd()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if !this.isLnRequest {
|
if !this.isLnRequest {
|
||||||
// 特殊URL处理
|
// 特殊URL处理
|
||||||
if len(this.rawURI) > 1 && this.rawURI[1] == '.' {
|
if len(this.rawURI) > 1 && this.rawURI[1] == '.' {
|
||||||
// ACME
|
// ACME
|
||||||
// TODO 需要配置是否启用ACME检测
|
// TODO 需要配置是否启用ACME检测
|
||||||
if strings.HasPrefix(this.rawURI, "/.well-known/acme-challenge/") {
|
if strings.HasPrefix(this.rawURI, "/.well-known/acme-challenge/") {
|
||||||
this.doACME()
|
if this.doACME() {
|
||||||
this.doEnd()
|
this.doEnd()
|
||||||
return
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -190,6 +202,24 @@ func (this *HTTPRequest) Do() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UAM
|
||||||
|
if !isHealthCheck {
|
||||||
|
if this.web.UAM != nil {
|
||||||
|
if this.web.UAM.IsOn {
|
||||||
|
if this.doUAM() {
|
||||||
|
this.doEnd()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if this.ReqServer.UAM != nil && this.ReqServer.UAM.IsOn {
|
||||||
|
this.web.UAM = this.ReqServer.UAM
|
||||||
|
if this.doUAM() {
|
||||||
|
this.doEnd()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// WAF
|
// WAF
|
||||||
if this.web.FirewallRef != nil && this.web.FirewallRef.IsOn {
|
if this.web.FirewallRef != nil && this.web.FirewallRef.IsOn {
|
||||||
if this.doWAFRequest() {
|
if this.doWAFRequest() {
|
||||||
@@ -232,6 +262,12 @@ func (this *HTTPRequest) Do() {
|
|||||||
|
|
||||||
// 开始调用
|
// 开始调用
|
||||||
func (this *HTTPRequest) doBegin() {
|
func (this *HTTPRequest) doBegin() {
|
||||||
|
// 是否找不到域名匹配
|
||||||
|
if this.ReqServer.Id == 0 {
|
||||||
|
this.doMismatch()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if !this.isLnRequest {
|
if !this.isLnRequest {
|
||||||
// 处理request limit
|
// 处理request limit
|
||||||
if this.web.RequestLimit != nil &&
|
if this.web.RequestLimit != nil &&
|
||||||
@@ -247,29 +283,12 @@ func (this *HTTPRequest) doBegin() {
|
|||||||
this.web.AccessLogRef.IsOn &&
|
this.web.AccessLogRef.IsOn &&
|
||||||
this.web.AccessLogRef.ContainsField(serverconfigs.HTTPAccessLogFieldRequestBody) {
|
this.web.AccessLogRef.ContainsField(serverconfigs.HTTPAccessLogFieldRequestBody) {
|
||||||
var err error
|
var err error
|
||||||
this.requestBodyData, err = ioutil.ReadAll(io.LimitReader(this.RawReq.Body, AccessLogMaxRequestBodySize))
|
this.requestBodyData, err = io.ReadAll(io.LimitReader(this.RawReq.Body, AccessLogMaxRequestBodySize))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
this.write50x(err, http.StatusBadGateway, false)
|
this.write50x(err, http.StatusBadGateway, "Failed to read request body for access log", "为访问日志读取请求Body失败", false)
|
||||||
return
|
|
||||||
}
|
|
||||||
this.RawReq.Body = ioutil.NopCloser(io.MultiReader(bytes.NewBuffer(this.requestBodyData), this.RawReq.Body))
|
|
||||||
}
|
|
||||||
|
|
||||||
// 处理健康检查
|
|
||||||
var isHealthCheck = false
|
|
||||||
var healthCheckKey = this.RawReq.Header.Get(serverconfigs.HealthCheckHeaderName)
|
|
||||||
if len(healthCheckKey) > 0 {
|
|
||||||
if this.doHealthCheck(healthCheckKey, &isHealthCheck) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// UAM
|
|
||||||
if !isHealthCheck && this.ReqServer.UAM != nil && this.ReqServer.UAM.IsOn {
|
|
||||||
if this.doUAM() {
|
|
||||||
this.doEnd()
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
this.RawReq.Body = io.NopCloser(io.MultiReader(bytes.NewBuffer(this.requestBodyData), this.RawReq.Body))
|
||||||
}
|
}
|
||||||
|
|
||||||
// 跳转
|
// 跳转
|
||||||
@@ -339,7 +358,7 @@ func (this *HTTPRequest) doEnd() {
|
|||||||
|
|
||||||
// 流量统计
|
// 流量统计
|
||||||
// TODO 增加是否开启开关
|
// TODO 增加是否开启开关
|
||||||
if this.ReqServer != nil {
|
if this.ReqServer != nil && this.ReqServer.Id > 0 {
|
||||||
var countCached int64 = 0
|
var countCached int64 = 0
|
||||||
var cachedBytes int64 = 0
|
var cachedBytes int64 = 0
|
||||||
|
|
||||||
@@ -356,17 +375,17 @@ func (this *HTTPRequest) doEnd() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
stats.SharedTrafficStatManager.Add(this.ReqServer.Id, this.ReqHost, this.writer.SentBodyBytes()+this.writer.SentHeaderBytes(), cachedBytes, 1, countCached, countAttacks, attackBytes, this.ReqServer.ShouldCheckTrafficLimit(), this.ReqServer.PlanId())
|
stats.SharedTrafficStatManager.Add(this.ReqServer.Id, this.ReqHost, this.writer.SentBodyBytes()+this.writer.SentHeaderBytes(), cachedBytes, 1, countCached, countAttacks, attackBytes, this.ReqServer.ShouldCheckTrafficLimit(), this.ReqServer.PlanId())
|
||||||
}
|
|
||||||
|
|
||||||
// 指标
|
// 指标
|
||||||
if metrics.SharedManager.HasHTTPMetrics() {
|
if metrics.SharedManager.HasHTTPMetrics() {
|
||||||
this.doMetricsResponse()
|
this.doMetricsResponse()
|
||||||
}
|
}
|
||||||
|
|
||||||
// 统计
|
// 统计
|
||||||
if this.web.StatRef != nil && this.web.StatRef.IsOn {
|
if this.web.StatRef != nil && this.web.StatRef.IsOn {
|
||||||
// 放到最后执行
|
// 放到最后执行
|
||||||
this.doStat()
|
this.doStat()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -521,6 +540,11 @@ func (this *HTTPRequest) configureWeb(web *serverconfigs.HTTPWebConfig, isTop bo
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UAM
|
||||||
|
if web.UAM != nil && (web.UAM.IsPrior || isTop) {
|
||||||
|
this.web.UAM = web.UAM
|
||||||
|
}
|
||||||
|
|
||||||
// 重写规则
|
// 重写规则
|
||||||
if len(web.RewriteRefs) > 0 {
|
if len(web.RewriteRefs) > 0 {
|
||||||
for index, ref := range web.RewriteRefs {
|
for index, ref := range web.RewriteRefs {
|
||||||
@@ -1033,7 +1057,7 @@ func (this *HTTPRequest) requestRemoteAddr(supportVar bool) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// X-Forwarded-For
|
// X-Forwarded-For
|
||||||
forwardedFor := this.RawReq.Header.Get("X-Forwarded-For")
|
var forwardedFor = this.RawReq.Header.Get("X-Forwarded-For")
|
||||||
if len(forwardedFor) > 0 {
|
if len(forwardedFor) > 0 {
|
||||||
commaIndex := strings.Index(forwardedFor, ",")
|
commaIndex := strings.Index(forwardedFor, ",")
|
||||||
if commaIndex > 0 {
|
if commaIndex > 0 {
|
||||||
@@ -1089,7 +1113,7 @@ func (this *HTTPRequest) requestRemoteAddr(supportVar bool) string {
|
|||||||
// 获取请求的客户端地址列表
|
// 获取请求的客户端地址列表
|
||||||
func (this *HTTPRequest) requestRemoteAddrs() (result []string) {
|
func (this *HTTPRequest) requestRemoteAddrs() (result []string) {
|
||||||
// X-Forwarded-For
|
// X-Forwarded-For
|
||||||
forwardedFor := this.RawReq.Header.Get("X-Forwarded-For")
|
var forwardedFor = this.RawReq.Header.Get("X-Forwarded-For")
|
||||||
if len(forwardedFor) > 0 {
|
if len(forwardedFor) > 0 {
|
||||||
commaIndex := strings.Index(forwardedFor, ",")
|
commaIndex := strings.Index(forwardedFor, ",")
|
||||||
if commaIndex > 0 {
|
if commaIndex > 0 {
|
||||||
@@ -1114,13 +1138,16 @@ func (this *HTTPRequest) requestRemoteAddrs() (result []string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Remote-Addr
|
// Remote-Addr
|
||||||
remoteAddr := this.RawReq.RemoteAddr
|
{
|
||||||
host, _, err := net.SplitHostPort(remoteAddr)
|
var remoteAddr = this.RawReq.RemoteAddr
|
||||||
if err == nil {
|
host, _, err := net.SplitHostPort(remoteAddr)
|
||||||
result = append(result, host)
|
if err == nil {
|
||||||
} else {
|
result = append(result, host)
|
||||||
result = append(result, remoteAddr)
|
} else {
|
||||||
|
result = append(result, remoteAddr)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1362,12 +1389,12 @@ func (this *HTTPRequest) Cookie(name string) string {
|
|||||||
return c.Value
|
return c.Value
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeleteHeader 删除Header
|
// DeleteHeader 删除请求Header
|
||||||
func (this *HTTPRequest) DeleteHeader(name string) {
|
func (this *HTTPRequest) DeleteHeader(name string) {
|
||||||
this.RawReq.Header.Del(name)
|
this.RawReq.Header.Del(name)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetHeader 设置Header
|
// SetHeader 设置请求Header
|
||||||
func (this *HTTPRequest) SetHeader(name string, values []string) {
|
func (this *HTTPRequest) SetHeader(name string, values []string) {
|
||||||
this.RawReq.Header[name] = values
|
this.RawReq.Header[name] = values
|
||||||
}
|
}
|
||||||
@@ -1447,7 +1474,12 @@ func (this *HTTPRequest) setForwardHeaders(header http.Header) {
|
|||||||
header["X-Forwarded-For"] = []string{strings.Join(forwardedFor, ", ") + ", " + remoteAddr}
|
header["X-Forwarded-For"] = []string{strings.Join(forwardedFor, ", ") + ", " + remoteAddr}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
header["X-Forwarded-For"] = []string{remoteAddr}
|
var clientRemoteAddr = this.requestRemoteAddr(true)
|
||||||
|
if len(clientRemoteAddr) > 0 && clientRemoteAddr != remoteAddr {
|
||||||
|
header["X-Forwarded-For"] = []string{clientRemoteAddr + ", " + remoteAddr}
|
||||||
|
} else {
|
||||||
|
header["X-Forwarded-For"] = []string{remoteAddr}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1679,7 +1711,12 @@ func (this *HTTPRequest) canIgnore(err error) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 客户端主动取消
|
// 客户端主动取消
|
||||||
if err == errWritingToClient || err == context.Canceled || err == io.ErrShortWrite || strings.Contains(err.Error(), "write: connection timed out") || strings.Contains(err.Error(), "write: broken pipe") {
|
if err == errWritingToClient ||
|
||||||
|
err == context.Canceled ||
|
||||||
|
err == io.ErrShortWrite ||
|
||||||
|
strings.Contains(err.Error(), "write: connection") ||
|
||||||
|
strings.Contains(err.Error(), "write: broken pipe") ||
|
||||||
|
strings.Contains(err.Error(), "write tcp") {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,34 +4,36 @@ import (
|
|||||||
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
|
"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/rpc"
|
"github.com/TeaOSLab/EdgeNode/internal/rpc"
|
||||||
"net/http"
|
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (this *HTTPRequest) doACME() {
|
func (this *HTTPRequest) doACME() (shouldStop bool) {
|
||||||
// TODO 对请求进行校验,防止恶意攻击
|
// TODO 对请求进行校验,防止恶意攻击
|
||||||
|
|
||||||
token := filepath.Base(this.RawReq.URL.Path)
|
var token = filepath.Base(this.RawReq.URL.Path)
|
||||||
if token == "acme-challenge" || len(token) <= 32 {
|
if token == "acme-challenge" || len(token) <= 32 {
|
||||||
this.writer.WriteHeader(http.StatusNotFound)
|
return false
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
rpcClient, err := rpc.SharedRPC()
|
rpcClient, err := rpc.SharedRPC()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
remotelogs.Error("RPC", "[ACME]rpc failed: "+err.Error())
|
remotelogs.Error("RPC", "[ACME]rpc failed: "+err.Error())
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
keyResp, err := rpcClient.ACMEAuthenticationRPC().FindACMEAuthenticationKeyWithToken(rpcClient.Context(), &pb.FindACMEAuthenticationKeyWithTokenRequest{Token: token})
|
keyResp, err := rpcClient.ACMEAuthenticationRPC().FindACMEAuthenticationKeyWithToken(rpcClient.Context(), &pb.FindACMEAuthenticationKeyWithTokenRequest{Token: token})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
remotelogs.Error("RPC", "[ACME]read key for token failed: "+err.Error())
|
remotelogs.Error("RPC", "[ACME]read key for token failed: "+err.Error())
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
if len(keyResp.Key) == 0 {
|
if len(keyResp.Key) == 0 {
|
||||||
this.writer.WriteHeader(http.StatusNotFound)
|
return false
|
||||||
} else {
|
|
||||||
this.writer.Header().Set("Content-Type", "text/plain")
|
|
||||||
_, _ = this.writer.WriteString(keyResp.Key)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.tags = append(this.tags, "ACME")
|
||||||
|
|
||||||
|
this.writer.Header().Set("Content-Type", "text/plain")
|
||||||
|
_, _ = this.writer.WriteString(keyResp.Key)
|
||||||
|
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ package nodes
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
|
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
|
||||||
"io/ioutil"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -26,14 +26,14 @@ func (this *HTTPRequest) doAuth() (shouldStop bool) {
|
|||||||
subReq.Proto = this.RawReq.Proto
|
subReq.Proto = this.RawReq.Proto
|
||||||
subReq.ProtoMinor = this.RawReq.ProtoMinor
|
subReq.ProtoMinor = this.RawReq.ProtoMinor
|
||||||
subReq.ProtoMajor = this.RawReq.ProtoMajor
|
subReq.ProtoMajor = this.RawReq.ProtoMajor
|
||||||
subReq.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
|
subReq.Body = io.NopCloser(bytes.NewReader([]byte{}))
|
||||||
subReq.Header.Set("Referer", this.URL())
|
subReq.Header.Set("Referer", this.URL())
|
||||||
var writer = NewEmptyResponseWriter(this.writer)
|
var writer = NewEmptyResponseWriter(this.writer)
|
||||||
this.doSubRequest(writer, subReq)
|
this.doSubRequest(writer, subReq)
|
||||||
return writer.StatusCode(), nil
|
return writer.StatusCode(), nil
|
||||||
}, this.Format)
|
}, this.Format)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
this.write50x(err, http.StatusInternalServerError, false)
|
this.write50x(err, http.StatusInternalServerError, "Failed to execute the AuthPolicy", "认证策略执行失败", false)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if b {
|
if b {
|
||||||
|
|||||||
@@ -3,12 +3,9 @@ package nodes
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"errors"
|
"errors"
|
||||||
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
|
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/caches"
|
"github.com/TeaOSLab/EdgeNode/internal/caches"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/compressions"
|
"github.com/TeaOSLab/EdgeNode/internal/compressions"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/goman"
|
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
|
"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/rpc"
|
|
||||||
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
"github.com/TeaOSLab/EdgeNode/internal/utils"
|
||||||
rangeutils "github.com/TeaOSLab/EdgeNode/internal/utils/ranges"
|
rangeutils "github.com/TeaOSLab/EdgeNode/internal/utils/ranges"
|
||||||
"github.com/iwind/TeaGo/types"
|
"github.com/iwind/TeaGo/types"
|
||||||
@@ -33,11 +30,6 @@ func (this *HTTPRequest) doCacheRead(useStale bool) (shouldStop bool) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 判断是否在预热
|
|
||||||
if (strings.HasPrefix(this.RawReq.RemoteAddr, "127.") || strings.HasPrefix(this.RawReq.RemoteAddr, "[::1]")) && this.RawReq.Header.Get("X-Cache-Action") == "preheat" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// 添加 X-Cache Header
|
// 添加 X-Cache Header
|
||||||
var addStatusHeader = this.web.Cache.AddStatusHeader
|
var addStatusHeader = this.web.Cache.AddStatusHeader
|
||||||
if addStatusHeader {
|
if addStatusHeader {
|
||||||
@@ -89,6 +81,12 @@ func (this *HTTPRequest) doCacheRead(useStale bool) (shouldStop bool) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 是否正在Purge
|
||||||
|
var isPurging = this.web.Cache.PurgeIsOn && strings.ToUpper(this.RawReq.Method) == "PURGE" && this.RawReq.Header.Get("X-Edge-Purge-Key") == this.web.Cache.PurgeKey
|
||||||
|
if isPurging {
|
||||||
|
this.RawReq.Method = http.MethodGet
|
||||||
|
}
|
||||||
|
|
||||||
// 校验请求
|
// 校验请求
|
||||||
if !this.cacheRef.MatchRequest(this.RawReq) {
|
if !this.cacheRef.MatchRequest(this.RawReq) {
|
||||||
this.cacheRef = nil
|
this.cacheRef = nil
|
||||||
@@ -136,8 +134,13 @@ func (this *HTTPRequest) doCacheRead(useStale bool) (shouldStop bool) {
|
|||||||
}
|
}
|
||||||
this.writer.cacheStorage = storage
|
this.writer.cacheStorage = storage
|
||||||
|
|
||||||
|
// 如果正在预热,则不读取缓存,等待下一个步骤重新生成
|
||||||
|
if (strings.HasPrefix(this.RawReq.RemoteAddr, "127.") || strings.HasPrefix(this.RawReq.RemoteAddr, "[::1]")) && this.RawReq.Header.Get("X-Edge-Cache-Action") == "fetch" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// 判断是否在Purge
|
// 判断是否在Purge
|
||||||
if this.web.Cache.PurgeIsOn && strings.ToUpper(this.RawReq.Method) == "PURGE" && this.RawReq.Header.Get("X-Edge-Purge-Key") == this.web.Cache.PurgeKey {
|
if isPurging {
|
||||||
this.varMapping["cache.status"] = "PURGE"
|
this.varMapping["cache.status"] = "PURGE"
|
||||||
|
|
||||||
var subKeys = []string{
|
var subKeys = []string{
|
||||||
@@ -159,22 +162,7 @@ func (this *HTTPRequest) doCacheRead(useStale bool) (shouldStop bool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 通过API节点清除别节点上的的Key
|
// 通过API节点清除别节点上的的Key
|
||||||
// TODO 改为队列,不需要每个请求都使用goroutine
|
SharedHTTPCacheTaskManager.PushTaskKeys([]string{key})
|
||||||
goman.New(func() {
|
|
||||||
rpcClient, err := rpc.SharedRPC()
|
|
||||||
if err == nil {
|
|
||||||
for _, rpcServerService := range rpcClient.ServerRPCList() {
|
|
||||||
_, err = rpcServerService.PurgeServerCache(rpcClient.Context(), &pb.PurgeServerCacheRequest{
|
|
||||||
Domains: []string{this.ReqHost},
|
|
||||||
Keys: []string{key},
|
|
||||||
Prefixes: nil,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
remotelogs.Error("HTTP_REQUEST_CACHE", "purge failed: "+err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -248,6 +236,11 @@ func (this *HTTPRequest) doCacheRead(useStale bool) (shouldStop bool) {
|
|||||||
if reader == nil {
|
if reader == nil {
|
||||||
reader, err = storage.OpenReader(key, useStale, false)
|
reader, err = storage.OpenReader(key, useStale, false)
|
||||||
if err != nil && this.cacheRef.AllowPartialContent {
|
if err != nil && this.cacheRef.AllowPartialContent {
|
||||||
|
// 尝试读取分片的缓存内容
|
||||||
|
if len(rangeHeader) == 0 {
|
||||||
|
// 默认读取开头
|
||||||
|
rangeHeader = "bytes=0-"
|
||||||
|
}
|
||||||
pReader, ranges := this.tryPartialReader(storage, key, useStale, rangeHeader)
|
pReader, ranges := this.tryPartialReader(storage, key, useStale, rangeHeader)
|
||||||
if pReader != nil {
|
if pReader != nil {
|
||||||
isPartialCache = true
|
isPartialCache = true
|
||||||
@@ -382,6 +375,7 @@ func (this *HTTPRequest) doCacheRead(useStale bool) (shouldStop bool) {
|
|||||||
if !this.isLnRequest && !isPartialCache && len(eTag) > 0 && this.requestHeader("If-None-Match") == eTag {
|
if !this.isLnRequest && !isPartialCache && len(eTag) > 0 && this.requestHeader("If-None-Match") == eTag {
|
||||||
// 自定义Header
|
// 自定义Header
|
||||||
this.processResponseHeaders(http.StatusNotModified)
|
this.processResponseHeaders(http.StatusNotModified)
|
||||||
|
this.addExpiresHeader(reader.ExpiresAt())
|
||||||
this.writer.WriteHeader(http.StatusNotModified)
|
this.writer.WriteHeader(http.StatusNotModified)
|
||||||
this.isCached = true
|
this.isCached = true
|
||||||
this.cacheRef = nil
|
this.cacheRef = nil
|
||||||
@@ -393,6 +387,7 @@ func (this *HTTPRequest) doCacheRead(useStale bool) (shouldStop bool) {
|
|||||||
if !this.isLnRequest && !isPartialCache && len(modifiedTime) > 0 && this.requestHeader("If-Modified-Since") == modifiedTime {
|
if !this.isLnRequest && !isPartialCache && len(modifiedTime) > 0 && this.requestHeader("If-Modified-Since") == modifiedTime {
|
||||||
// 自定义Header
|
// 自定义Header
|
||||||
this.processResponseHeaders(http.StatusNotModified)
|
this.processResponseHeaders(http.StatusNotModified)
|
||||||
|
this.addExpiresHeader(reader.ExpiresAt())
|
||||||
this.writer.WriteHeader(http.StatusNotModified)
|
this.writer.WriteHeader(http.StatusNotModified)
|
||||||
this.isCached = true
|
this.isCached = true
|
||||||
this.cacheRef = nil
|
this.cacheRef = nil
|
||||||
@@ -582,10 +577,12 @@ func (this *HTTPRequest) addExpiresHeader(expiresAt int64) {
|
|||||||
if this.cacheRef.ExpiresTime.Overwrite || len(this.writer.Header().Get("Expires")) == 0 {
|
if this.cacheRef.ExpiresTime.Overwrite || len(this.writer.Header().Get("Expires")) == 0 {
|
||||||
if this.cacheRef.ExpiresTime.AutoCalculate {
|
if this.cacheRef.ExpiresTime.AutoCalculate {
|
||||||
this.writer.Header().Set("Expires", time.Unix(utils.GMTUnixTime(expiresAt), 0).Format("Mon, 2 Jan 2006 15:04:05")+" GMT")
|
this.writer.Header().Set("Expires", time.Unix(utils.GMTUnixTime(expiresAt), 0).Format("Mon, 2 Jan 2006 15:04:05")+" GMT")
|
||||||
|
this.writer.Header().Del("Cache-Control")
|
||||||
} else if this.cacheRef.ExpiresTime.Duration != nil {
|
} else if this.cacheRef.ExpiresTime.Duration != nil {
|
||||||
var duration = this.cacheRef.ExpiresTime.Duration.Duration()
|
var duration = this.cacheRef.ExpiresTime.Duration.Duration()
|
||||||
if duration > 0 {
|
if duration > 0 {
|
||||||
this.writer.Header().Set("Expires", utils.GMTTime(time.Now().Add(duration)).Format("Mon, 2 Jan 2006 15:04:05")+" GMT")
|
this.writer.Header().Set("Expires", utils.GMTTime(time.Now().Add(duration)).Format("Mon, 2 Jan 2006 15:04:05")+" GMT")
|
||||||
|
this.writer.Header().Del("Cache-Control")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user