From 7761d6d7cd3c1a24a015aa51d4f1d1b9e473dfd5 Mon Sep 17 00:00:00 2001 From: Vincent <46603415@qq.com> Date: Tue, 30 Nov 2021 09:36:41 +0800 Subject: [PATCH] Initial commit --- .gitignore | 14 ++++- README.md | 44 +++++++++++++- blacklist.json | 3 + build-linux64.sh | 8 +++ build-macos.sh | 8 +++ build-win64.sh | 8 +++ config.json | 8 +++ global/global.go | 47 +++++++++++++++ go.mod | 10 +++ go.sum | 80 ++++++++++++++++++++++++ logic/kernel.go | 42 +++++++++++++ logic/loadconf.go | 101 +++++++++++++++++++++++++++++++ logic/notice.go | 22 +++++++ logic/start.go | 147 +++++++++++++++++++++++++++++++++++++++++++++ logs/logs.go | 54 +++++++++++++++++ main.go | 13 ++++ start.sh | 2 + version/version.go | 27 +++++++++ whitelist.json | 3 + 19 files changed, 636 insertions(+), 5 deletions(-) create mode 100644 blacklist.json create mode 100644 build-linux64.sh create mode 100644 build-macos.sh create mode 100644 build-win64.sh create mode 100644 config.json create mode 100644 global/global.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 logic/kernel.go create mode 100644 logic/loadconf.go create mode 100644 logic/notice.go create mode 100644 logic/start.go create mode 100644 logs/logs.go create mode 100644 main.go create mode 100644 start.sh create mode 100644 version/version.go create mode 100644 whitelist.json diff --git a/.gitignore b/.gitignore index 66fd13c..d766078 100644 --- a/.gitignore +++ b/.gitignore @@ -4,12 +4,20 @@ *.dll *.so *.dylib - +# goland +*.iml +*.ipr +*.iws +.idea/ # Test binary, built with `go test -c` *.test - +# logs +*.log +syslog/ # Output of the go coverage tool, specifically when used with LiteIDE *.out - +# project +TransGateLinux +TransGate # Dependency directories (remove the comment below to include it) # vendor/ diff --git a/README.md b/README.md index 685f2b2..c92a0fd 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,42 @@ -# transgate -tcp transgate TCP转发服务器 +# TransGate +### 作者信息 +Author: Vincent +E-Mail: 46603415@qq.com +QQ: 46603415 +### 配置参数 +#### 基本配置 +`config.json` +```json +{ + "IP":"0.0.0.0", + "Port":"7200", + "DesSrvIP":"192.168.10.249", + "DesSrvPort":"3389", + "MaxUser":4, + "RunModel":"bl" +} +``` +```conf + "IP":"0.0.0.0", //转发服务器ip地址 + "Port":"7200", //转发服务器端口 + "DesSrvIP":"192.168.10.249", //目标服务器IP地址 + "DesSrvPort":"3389", //目标服务器端口 + "MaxUser":4 //最大连接数 + "RunModel":"bl" //运行白名单模式写参数wl,运行黑名单模式写参数bl. +``` +#### 白名单 +`whitelist.json` +json数组,分隔符为,修改后必须重启网关生效 +```json +{ + "AcceptIPList":"127.0.0.1,192.168.10.255" +} +``` +#### 黑名单 +`blacklist.json` +json数组,分隔符为,修改后必须重启网关生效 +```json +{ + "BanIPList":"192.168.10.255,192.168.10.254,127.0.0.1" +} +``` \ No newline at end of file diff --git a/blacklist.json b/blacklist.json new file mode 100644 index 0000000..a794405 --- /dev/null +++ b/blacklist.json @@ -0,0 +1,3 @@ +{ + "BanIPList":"192.168.10.255,192.168.10.254,127.0.0.1" +} \ No newline at end of file diff --git a/build-linux64.sh b/build-linux64.sh new file mode 100644 index 0000000..c5c26bc --- /dev/null +++ b/build-linux64.sh @@ -0,0 +1,8 @@ +#!/bin/zsh +BUILD_TIME=$(date '+%Y/%m/%d %H:%M:%S') +BUILD_GO_VERSION=$(go version | awk '{print $3"@"$4}') +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \ +-ldflags \ +"-X 'TransGate/version.BuildTime=${BUILD_TIME}' \ +-X TransGate/version.BuildGoVersion=${BUILD_GO_VERSION}" \ +-o TransGateLinux main.go \ No newline at end of file diff --git a/build-macos.sh b/build-macos.sh new file mode 100644 index 0000000..a8d160a --- /dev/null +++ b/build-macos.sh @@ -0,0 +1,8 @@ +#!/bin/zsh +BUILD_TIME=$(date '+%Y/%m/%d %H:%M:%S') +BUILD_GO_VERSION=$(go version | awk '{print $3"@"$4}') +CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build \ +-ldflags \ +"-X 'TransGate/version.BuildTime=${BUILD_TIME}' \ +-X TransGate/version.BuildGoVersion=${BUILD_GO_VERSION}" \ + -o TransGate main.go \ No newline at end of file diff --git a/build-win64.sh b/build-win64.sh new file mode 100644 index 0000000..68669e4 --- /dev/null +++ b/build-win64.sh @@ -0,0 +1,8 @@ +#!/bin/zsh +BUILD_TIME=$(date '+%Y/%m/%d %H:%M:%S') +BUILD_GO_VERSION=$(go version | awk '{print $3"@"$4}') +CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build \ +-ldflags \ +"-X 'TransGate/version.BuildTime=${BUILD_TIME}' \ +-X TransGate/version.BuildGoVersion=${BUILD_GO_VERSION}" \ +-o TransGateWin64.exe main.go \ No newline at end of file diff --git a/config.json b/config.json new file mode 100644 index 0000000..9d607d0 --- /dev/null +++ b/config.json @@ -0,0 +1,8 @@ +{ + "IP":"0.0.0.0", + "Port":"7200", + "DesSrvIP":"rr-bp1ne645nbd0x7j8r4o.mysql.rds.aliyuncs.com", + "DesSrvPort":"3306", + "MaxUser":10, + "RunModel":"wl" +} diff --git a/global/global.go b/global/global.go new file mode 100644 index 0000000..a18a32b --- /dev/null +++ b/global/global.go @@ -0,0 +1,47 @@ +/** + * @Author: Vincent + * @Author: 46603415@qq.com + * @Date: 2020/9/17 10:36 上午 + * @Desc: + */ + +package global + +import ( + "TransGate/logs" + "runtime" +) + +// TransGateConf 全局变量来存储配置信息 +type TransGateConf struct { + IP string + Port string + MaxUser int64 //允许连接的用户最大值 + DesSrvIP string //目标服务器OP + DesSrvPort string //目标服务器端口 + RunModel string //定义了运行模式,wl代表白名单,bl代表黑名单,白名单模式加载wl.json(只允许白名单访问),黑名单加载bl(除了黑名单以外的ip都可以访问) +} + +type BanConf struct { + BanIPList string +} +type WLConf struct { + AcceptIPList string +} + +type JsonStruct struct { +} + +var IP string +var Port string +var MaxUser int64 +var DesSrvIP string +var DesSrvPort string +var BanIPList string //设计用于禁止链接的ip列表 +var BanIPArr []string +var AcceptIPList string +var AcceptIPArr []string +var Logger = logs.InitLogger("./syslog/TransGateSys.log", "debug") +var ConnectCount int64 +var RunModel string //服务器运行模式 +var CPUCoreMax = runtime.NumCPU() //全局变量记录cpu核心数 diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..c733b36 --- /dev/null +++ b/go.mod @@ -0,0 +1,10 @@ +module TransGate + +go 1.14 + +require ( + github.com/gogf/gf v1.13.4 + github.com/natefinch/lumberjack v2.0.0+incompatible + go.uber.org/zap v1.16.0 + gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..b1a81e6 --- /dev/null +++ b/go.sum @@ -0,0 +1,80 @@ +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/clbanning/mxj v1.8.5-0.20200714211355-ff02cfb8ea28/go.mod h1:BVjHeAH+rl9rs6f+QIpeRl0tfu10SXn1pUSa5PVGJng= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/gogf/gf v1.13.4 h1:+IWX/L/SNYjwp9C0tXABZ8vJfYaFKyx0cTAb2DE2a1Y= +github.com/gogf/gf v1.13.4/go.mod h1:dGX0/BElXDBYbdJGascqfrWScj8IMeOietDjVD6/5Fc= +github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gqcn/structs v1.1.1/go.mod h1:/aBhTBSsKQ2Ec9pbnYdGphtdWXHFn4KrCL0fXM/Adok= +github.com/grokify/html-strip-tags-go v0.0.0-20190921062105-daaa06bf1aaf/go.mod h1:2Su6romC5/1VXOQMaWL2yb618ARB8iVo6/DR99A6d78= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +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/natefinch/lumberjack v2.0.0+incompatible h1:4QJd3OLAMgj7ph+yZTuX13Ld4UpgHp07nNdFX7mqFfM= +github.com/natefinch/lumberjack v2.0.0+incompatible/go.mod h1:Wi9p2TTF5DG5oU+6YfsmYQpsTIOm0B1VNzQg9Mw6nPk= +github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +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.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +go.uber.org/atomic v1.6.0 h1:Ezj3JGmsOnG1MoRWQkPBsKLe9DwWD9QeXzTRzzldNVk= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/multierr v1.5.0 h1:KCa4XfM8CWFCpxXRGok+Q0SS/0XBhMDbHHGABQLvD2A= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee h1:0mgffUl7nfd+FpvXMVz4IDEaUSmT1ysygQC7qYo7sG4= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.16.0 h1:uFRZXykJGK9lLY4HtgSw44DnIcAM+kRBP7x5m+NpAOM= +go.uber.org/zap v1.16.0/go.mod h1:MA8QOfq0BHJwdXa996Y4dYkAqRKB8/1K1QMMZVaNZjQ= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200602114024-627f9648deb9/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +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/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5 h1:hKsoRgsbwY1NafxrwTs+k64bikrLBkAgPir1TNCj3Zs= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8= +gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= diff --git a/logic/kernel.go b/logic/kernel.go new file mode 100644 index 0000000..02f29bc --- /dev/null +++ b/logic/kernel.go @@ -0,0 +1,42 @@ +/** + * @Author: Vincent + * @Author: 46603415@qq.com + * @Date: 2020/9/17 11:31 上午 + * @Desc: 数据交换拷贝 + */ + +package logic + +import ( + "TransGate/global" + "io" + "net" + "sync/atomic" +) + +func DataExHandle(proxy net.Conn, target net.Conn) { + defer func(proxy net.Conn) { + err := proxy.Close() + if err != nil { + + } + }(proxy) + defer func(target net.Conn) { + err := target.Close() + if err != nil { + + } + }(target) + ExitChan := make(chan bool, 1) + go func(proxy net.Conn, target net.Conn, ExChan chan bool) { + _, _ = io.Copy(proxy, target) + ExitChan <- true + }(proxy, target, ExitChan) + go func(proxy net.Conn, target net.Conn, ExChan chan bool) { + _, _ = io.Copy(target, proxy) + ExitChan <- true + }(proxy, target, ExitChan) + + <-ExitChan + atomic.AddInt64(&global.ConnectCount, -1) +} diff --git a/logic/loadconf.go b/logic/loadconf.go new file mode 100644 index 0000000..b795bdf --- /dev/null +++ b/logic/loadconf.go @@ -0,0 +1,101 @@ +/** + * @Author: Vincent + * @Author: 46603415@qq.com + * @Date: 2020/9/17 10:47 上午 + * @Desc: 加载配置 + */ + +package logic + +import ( + "TransGate/global" + "encoding/json" + "io/ioutil" + "os" + "strings" +) + +func Exists(path string) bool { + _, err := os.Stat(path) //os.Stat获取文件信息 + if err != nil { + if os.IsNotExist(err) { + return false + } + return true + } + return true +} + +func LoadAllConfig() { + chkGateConf := Exists("./config.json") + chkBanConf := Exists("./blacklist.json") + chkWLConf := Exists("./whitelist.json") + if chkGateConf && chkBanConf && chkWLConf { + LoadTransGateConf() + LoadBanConf() + LoadWLConf() + } else { + //NoticeInfo("load conf error!") + global.Logger.Error("load conf error!") + os.Exit(1) + } + +} + +// LoadTransGateConf 加载网关Json配置 +func LoadTransGateConf() { + JsonParse := NewJsonStruct() + conf := global.TransGateConf{} + JsonParse.Load("./config.json", &conf) + global.IP = conf.IP + global.Port = conf.Port + global.MaxUser = conf.MaxUser + global.DesSrvIP = conf.DesSrvIP + global.DesSrvPort = conf.DesSrvPort + global.RunModel = conf.RunModel +} + +// LoadBanConf 加载黑名单配置 +func LoadBanConf() { + JsonParse := NewJsonStruct() + conf := BanConf{} + JsonParse.Load("./blacklist.json", &conf) + global.BanIPList = conf.BanIPList + global.BanIPArr = strings.Split(global.BanIPList, ",") //以,为分隔符,分割字符串导入到字符串数组,用于存储拒绝连接列表 +} + +// LoadWLConf 加载黑名单配置 +func LoadWLConf() { + JsonParse := NewJsonStruct() + conf := WLConf{} + JsonParse.Load("./whitelist.json", &conf) + global.AcceptIPList = conf.AcceptIPList + global.AcceptIPArr = strings.Split(global.AcceptIPList, ",") //以,为分隔符,分割字符串导入到字符串数组,用于存储拒绝连接列表 +} + +type BanConf struct { + BanIPList string +} +type WLConf struct { + AcceptIPList string +} + +func NewJsonStruct() *JsonStruct { + return &JsonStruct{} +} + +type JsonStruct struct { +} + +func (jst *JsonStruct) Load(filename string, v interface{}) { + //ReadFile函数会读取文件的全部内容,并将结果以[]byte类型返回 + data, err := ioutil.ReadFile(filename) + if err != nil { + return + } + //读取的数据为json格式,需要进行解码 + err = json.Unmarshal(data, v) + if err != nil { + return + } +} diff --git a/logic/notice.go b/logic/notice.go new file mode 100644 index 0000000..0258ce7 --- /dev/null +++ b/logic/notice.go @@ -0,0 +1,22 @@ +/** + * @Author: Vincent + * @Author: 46603415@qq.com + * @Date: 2020/9/17 11:01 上午 + * @Desc: 10分钟打印一下当前连接数 + */ + +package logic + +import ( + "TransGate/global" + "fmt" + "time" +) + +func NoticeCount() { + for { + time.Sleep(10 * time.Minute) + msg := fmt.Sprintf("Online Connections: %v", global.ConnectCount) + global.Logger.Info(msg) + } +} diff --git a/logic/start.go b/logic/start.go new file mode 100644 index 0000000..4aebba9 --- /dev/null +++ b/logic/start.go @@ -0,0 +1,147 @@ +/** + * @Author: Vincent + * @Author: 46603415@qq.com + * @Date: 2020/9/17 10:47 上午 + * @Desc: + */ + +package logic + +import ( + "TransGate/global" + "TransGate/version" + "fmt" + "net" + "os" + "runtime" + "strings" + "sync/atomic" +) + +func StartTransGate() { + version.PrintVer() + LoadAllConfig() + go NoticeCount() //Vincent 20190513 计时函数必须要新开一个协程去做处理,否则会阻塞Socket的 + SourceSrvInfo := global.IP + ":" + global.Port + server, err := net.Listen("tcp", SourceSrvInfo) + + if err != nil { + msg := fmt.Sprintf("Unable To Bind IP & Port Error: %s", err.Error()) + global.Logger.Error(msg) + os.Exit(1) //如果无法监听链接直接退出程序 + } + + msg := fmt.Sprint("TransGate Started ...") + runEnvInfo := fmt.Sprintf("BindIP: %s | BindPort: %s | MaxUser: %v | DesSrvIP: %s | DesSrvPort: %s | RunModel: %s | CPUCoreMax: %v", global.IP, global.Port, global.MaxUser, global.DesSrvIP, global.DesSrvPort, global.RunModel, global.CPUCoreMax) + global.Logger.Info(msg) + global.Logger.Info(runEnvInfo) + + defer func(server net.Listener) { + err := server.Close() + if err != nil { + + } + }(server) + for { + switch global.RunModel { + //黑名单方式运行 + case "bl": + proxyConn, err := server.Accept() + isExist := false + for _, v := range global.BanIPArr { + banip := proxyConn.RemoteAddr().String() + banip = banip[0:strings.LastIndex(banip, ":")] + if v == banip { + isExist = true + } + } + if isExist { + global.Logger.Error(fmt.Sprintf("IP Address In BanList, Kick Off IP Address: %s", proxyConn.RemoteAddr())) + _ = proxyConn.Close() + continue + } else { + //无法接受一个请求 + if err != nil { + msg := fmt.Sprintf("Unable to accept a request, error: %s", err.Error()) + //NoticeInfo(msg) + global.Logger.Error(msg) + continue + } + global.Logger.Info(fmt.Sprintf("Accept New Connection: %s", proxyConn.RemoteAddr().String())) + //转发地址 + targetAddr := fmt.Sprintf("%s:%s", global.DesSrvIP, global.DesSrvPort) + //net.Dial 是主动拨号链接到别的地址,而不是像listener一样本地建立一个socket监听 + targetConn, err := net.Dial("tcp", targetAddr) + //拨号链接到转发服务器出错 + if err != nil { + global.Logger.Error(fmt.Sprintf("net.Dial Unable To Connect To Target: %s, error: %s", targetAddr, err.Error())) + _ = proxyConn.Close() + continue + } + //判断以下是否达到了配置设定的服务器最大链接数 + if global.ConnectCount >= global.MaxUser { + global.Logger.Error(fmt.Sprintf("Over Max Connections, Kick Off Connection %s MaxValue --> %v", proxyConn.RemoteAddr().String(), global.MaxUser)) + _ = proxyConn.Close() + continue + } + atomic.AddInt64(&global.ConnectCount, 1) //原子钟加1给在现数 + runtime.GOMAXPROCS(global.CPUCoreMax) //CPU多核利用 + go DataExHandle(proxyConn, targetConn) + } + //白名单方式运行 + case "wl": + proxyConn, err := server.Accept() + isExist := false + for _, v := range global.AcceptIPArr { + acceptIp := proxyConn.RemoteAddr().String() + acceptIp = acceptIp[0:strings.LastIndex(acceptIp, ":")] + if v == acceptIp { + isExist = true + } + } + if isExist { + //无法接受一个请求 + if err != nil { + global.Logger.Error(fmt.Sprintf("Unable to accept a request, error: %s", err.Error())) + continue + } + global.Logger.Info(fmt.Sprintf("Accept New Connection: %s", proxyConn.RemoteAddr().String())) + //转发地址 + targetAddr := fmt.Sprintf("%s:%s", global.DesSrvIP, global.DesSrvPort) + //net.Dial 是主动拨号链接到别的地址,而不是像listener一样本地建立一个socket监听 + targetConn, err := net.Dial("tcp", targetAddr) + //拨号链接到转发服务器出错 + if err != nil { + global.Logger.Error(fmt.Sprintf("net.Dial Unable To Connect To Target: %s, error: %s", targetAddr, err.Error())) + err := proxyConn.Close() + if err != nil { + return + } + continue + } + //判断以下是否达到了配置设定的服务器最大链接数 + if global.ConnectCount >= global.MaxUser { + global.Logger.Error(fmt.Sprintf("Over Max Connections, Kick Off Connection %s MaxValue --> %v", proxyConn.RemoteAddr().String(), global.MaxUser)) + err := proxyConn.Close() + if err != nil { + return + } + continue + } + atomic.AddInt64(&global.ConnectCount, 1) //原子钟加1给在现数 + runtime.GOMAXPROCS(global.CPUCoreMax) //CPU多核利用 + go DataExHandle(proxyConn, targetConn) + } else { + global.Logger.Error(fmt.Sprintf("IP Address Does Not In WhiteList, Kick Off IP Address: %s", proxyConn.RemoteAddr())) + err := proxyConn.Close() + if err != nil { + return + } + continue + } + default: + global.Logger.Error(fmt.Sprintf("Wrong Parameter With RunModel: %s", global.RunModel)) + os.Exit(1) + } + } +} diff --git a/logs/logs.go b/logs/logs.go new file mode 100644 index 0000000..cbcd3e1 --- /dev/null +++ b/logs/logs.go @@ -0,0 +1,54 @@ +/** + * @Author: Vincent + * @Author: 46603415@qq.com + * @Date: 2020/9/17 10:36 上午 + * @Desc: 日志模块 + */ + +package logs + +import ( + "github.com/natefinch/lumberjack" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" +) + +func InitLogger(logPath string, loglevel string) *zap.Logger { + + hook := lumberjack.Logger{ + Filename: logPath, // 日志文件路径 + MaxSize: 128, // megabytes + MaxBackups: 30, // 最多保留300个备份 + MaxAge: 7, // days + Compress: true, // 是否压缩 disabled by default + } + + w := zapcore.AddSync(&hook) + + // 设置日志级别,debug可以打印出info,debug,warn;info级别可以打印warn,info;warn只能打印warn + // debug->info->warn->error + var level zapcore.Level + switch loglevel { + case "debug": + level = zap.DebugLevel + case "info": + level = zap.InfoLevel + case "error": + level = zap.ErrorLevel + default: + level = zap.InfoLevel + } + encoderConfig := zap.NewProductionEncoderConfig() + // 时间格式 + encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder + core := zapcore.NewCore( + zapcore.NewConsoleEncoder(encoderConfig), + w, + level, + ) + + logger := zap.New(core) + logger.Info("Default Logger init success!") + + return logger +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..039b3fb --- /dev/null +++ b/main.go @@ -0,0 +1,13 @@ +/** + * @Author: Vincent + * @Author: 46603415@qq.com + * @Date: 2020/9/17 10:35 上午 + * @Desc: + */ +package main + +import "TransGate/logic" + +func main() { + logic.StartTransGate() +} diff --git a/start.sh b/start.sh new file mode 100644 index 0000000..395b631 --- /dev/null +++ b/start.sh @@ -0,0 +1,2 @@ +#!/bin/bash +./TransGateLinux & diff --git a/version/version.go b/version/version.go new file mode 100644 index 0000000..2b7db69 --- /dev/null +++ b/version/version.go @@ -0,0 +1,27 @@ +/** + * @Author: Vincent + * @Author: 46603415@qq.com + * @Date: 2020/9/17 11:42 上午 + * @Desc: 打印版本信息 + */ + +package version + +import ( + "TransGate/global" + "fmt" + "github.com/gogf/gf" +) + +var ( + BuildTime = "unknown" + BuildGoVersion = "unknown" + Author = "Vincent" + Email = "46603415@qq.com" +) + +func PrintVer() { + msgVer := fmt.Sprintf("Author: %s| E-Mail: %s | Build Data: %s | Golang Version: %s | GF Version: %s", Author, Email, BuildTime, BuildGoVersion, gf.VERSION) + global.Logger.Info(msgVer) + //fmt.Print(msgVer) +} diff --git a/whitelist.json b/whitelist.json new file mode 100644 index 0000000..348e846 --- /dev/null +++ b/whitelist.json @@ -0,0 +1,3 @@ +{ + "AcceptIPList":"127.0.0.1,192.168.10.255,122.224.109.210" +} \ No newline at end of file