Skip to content

Commit

Permalink
Merge pull request #4 from lwch/dev
Browse files Browse the repository at this point in the history
v0.2.0
  • Loading branch information
lwch authored Sep 27, 2021
2 parents c40846c + dbbd14f commit 85e2130
Show file tree
Hide file tree
Showing 20 changed files with 265 additions and 538 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ jobs:
os:
- ubuntu-18.04
- ubuntu-20.04
# - windows-2016 # tar command error
- windows-2016 # tar command error
- windows-2019
- windows-2022
- macos-10.15
- macos-11
go:
- '1.11'
- '1.12'
- '1.13'
- '1.14'
Expand Down
9 changes: 8 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,11 @@
# v0.1.2

1. 服务端增加心跳,客户端增加超时次数判断逻辑,用以支持客户端操作系统休眠后的恢复
2. 修正客户端断开链接后的崩溃问题
2. 修正客户端断开链接后的崩溃问题

# v0.2.0

1. 新增action参数用于注册系统服务,删除原有init.d启动脚本
2. 提取link_id为基础字段,修改协议数据包格式

**注:由于提取link_id作为基础字段,因此v0.2.0版本与旧版本的程序不能混用**
26 changes: 15 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,24 +87,28 @@ server端配置(10.0.1.1):
- 建议在server端设置较长的超时时间
- 建议在client端设置较短的超时时间

## linux部署
## 部署

1. 将init.d/np-cli和init.d/np-svr拷贝至/etc/init.d目录
2. 创建/opt/natpass和对应目录
1. [下载](https://github.com/lwch/natpass/releases)并解压到任意目录
2. 修改配置文件
3. 注册服务(windows系统需要管理员权限)

sudo mkdir -p /opt/natpass/bin /opt/natpass/conf
3. 将编译出的二进制文件拷贝至/opt/natpass/bin目录
4. 将配置文件拷贝至/opt/natpass/conf目录,并修改对应参数
5. 设置开机启动项
sudo ./np-svr -conf <配置文件路径> -action install [-user <用户名>]
sudo ./np-cli -conf <配置文件路径> -action install [-user <用户名>]
4. linux系统

sudo systemctl enable np-svr
sudo systemctl start np-svr
sudo systemctl enable np-cli
6. 启动对应服务
sudo systemctl start np-cli

sudo /etc/init.d/np-svr start
sudo /etc/init.d/np-cli start
5. windows系统

打开服务管理面板:service.msc
找到np-svr或np-cli服务
右键启动即可

## iperf3压测对比

Expand Down
9 changes: 1 addition & 8 deletions build_all.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
"github.com/lwch/runtime"
)

const version = "0.1.2"
const version = "0.2.0"
const buildDir = "tmp"
const releaseDir = "release"

Expand Down Expand Up @@ -76,13 +76,6 @@ func build(t target) {
runtime.Assert(err)
err = copyFile("CHANGELOG.md", path.Join(buildDir, "CHANGELOG.md"))
runtime.Assert(err)
if t.os != "windows" && t.os != "android" && t.os != "ios" {
runtime.Assert(os.MkdirAll(path.Join(buildDir, "init.d"), 0755))
err = copyFile(path.Join("init.d", "np-cli"), path.Join(buildDir, "init.d", "np-cli"))
runtime.Assert(err)
err = copyFile(path.Join("init.d", "np-svr"), path.Join(buildDir, "init.d", "np-svr"))
runtime.Assert(err)
}

ldflags := "-X 'main._GIT_HASH=" + gitHash() + "' " +
"-X 'main._GIT_REVERSION=" + gitReversion() + "' " +
Expand Down
127 changes: 83 additions & 44 deletions code/client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@ import (
"natpass/code/network"
"net"
"os"
"path/filepath"
rt "runtime"
"strconv"
"time"

"net/http"
_ "net/http/pprof"

"github.com/lwch/daemon"
"github.com/kardianos/service"
"github.com/lwch/logging"
"github.com/lwch/runtime"
)

var (
Expand All @@ -34,46 +36,31 @@ func showVersion() {
os.Exit(0)
}

func main() {
bak := flag.Bool("d", false, "backend running")
pid := flag.String("pid", "", "pid file dir")
user := flag.String("u", "", "daemon user")
conf := flag.String("conf", "", "configure file path")
version := flag.Bool("v", false, "show version info")
flag.Parse()

if *version {
showVersion()
os.Exit(0)
}

if len(*conf) == 0 {
fmt.Println("missing -conf param")
os.Exit(1)
}
type app struct {
cfg *global.Configure
}

if *bak {
daemon.Start(0, *pid, *user, "-conf", *conf)
return
}
func (a *app) Start(s service.Service) error {
go a.run()
return nil
}

go func() {
http.ListenAndServe(":9000", nil)
}()
func (a *app) run() {
// go func() {
// http.ListenAndServe(":9000", nil)
// }()

cfg := global.LoadConf(*conf)

logging.SetSizeRotate(cfg.LogDir, "np-cli", int(cfg.LogSize.Bytes()), cfg.LogRotate, true)
logging.SetSizeRotate(a.cfg.LogDir, "np-cli", int(a.cfg.LogSize.Bytes()), a.cfg.LogRotate, true)
defer logging.Flush()

pl := pool.New(cfg)
pl := pool.New(a.cfg)

for _, t := range cfg.Tunnels {
for _, t := range a.cfg.Tunnels {
tn := tunnel.New(t)
go tn.Handle(pl)
}

for i := 0; i < cfg.Links-pl.Size(); i++ {
for i := 0; i < a.cfg.Links-pl.Size(); i++ {
go func() {
for {
conn := pl.Get()
Expand All @@ -89,22 +76,20 @@ func main() {
var linkID string
switch msg.GetXType() {
case network.Msg_connect_req:
connect(pl, conn, msg.GetFrom(), msg.GetTo(),
connect(pl, conn, msg.GetLinkId(), msg.GetFrom(), msg.GetTo(),
msg.GetFromIdx(), msg.GetToIdx(), msg.GetCreq())
case network.Msg_connect_rep:
linkID = msg.GetCrep().GetId()
case network.Msg_disconnect:
linkID = msg.GetXDisconnect().GetId()
case network.Msg_forward:
linkID = msg.GetXData().GetLid()
case network.Msg_connect_rep,
network.Msg_disconnect,
network.Msg_forward:
linkID = msg.GetLinkId()
}
if len(linkID) > 0 {
logging.Error("link of %s on connection %d not found, type=%s",
linkID, conn.Idx, msg.GetXType().String())
continue
}
}
logging.Info("connection %s-%d exited", cfg.ID, conn.Idx)
logging.Info("connection %s-%d exited", a.cfg.ID, conn.Idx)
time.Sleep(time.Second)
}
}()
Expand All @@ -113,14 +98,68 @@ func main() {
select {}
}

func connect(pool *pool.Pool, conn *pool.Conn, from, to string, fromIdx, toIdx uint32, req *network.ConnectRequest) {
func (a *app) Stop(s service.Service) error {
return nil
}

func main() {
user := flag.String("user", "", "service user")
conf := flag.String("conf", "", "configure file path")
version := flag.Bool("version", false, "show version info")
act := flag.String("action", "", "install or uninstall")
flag.Parse()

if *version {
showVersion()
os.Exit(0)
}

if len(*conf) == 0 {
fmt.Println("missing -conf param")
os.Exit(1)
}

dir, err := filepath.Abs(*conf)
runtime.Assert(err)

var depends []string
if rt.GOOS != "windows" {
depends = append(depends, "After=network.target")
}

appCfg := &service.Config{
Name: "np-cli",
DisplayName: "np-cli",
Description: "nat forward service",
UserName: *user,
Arguments: []string{"-conf", dir},
Dependencies: depends,
}

cfg := global.LoadConf(*conf)

app := &app{cfg: cfg}
sv, err := service.New(app, appCfg)
runtime.Assert(err)

switch *act {
case "install":
runtime.Assert(sv.Install())
case "uninstall":
runtime.Assert(sv.Uninstall())
default:
runtime.Assert(sv.Run())
}
}

func connect(pool *pool.Pool, conn *pool.Conn, id, from, to string, fromIdx, toIdx uint32, req *network.ConnectRequest) {
dial := "tcp"
if req.GetXType() == network.ConnectRequest_udp {
dial = "udp"
}
link, err := net.Dial(dial, fmt.Sprintf("%s:%d", req.GetAddr(), req.GetPort()))
if err != nil {
conn.SendConnectError(from, fromIdx, req.GetId(), err.Error())
conn.SendConnectError(from, fromIdx, id, err.Error())
return
}
host, pt, _ := net.SplitHostPort(link.LocalAddr().String())
Expand All @@ -134,9 +173,9 @@ func connect(pool *pool.Pool, conn *pool.Conn, from, to string, fromIdx, toIdx u
RemoteAddr: req.GetAddr(),
RemotePort: uint16(req.GetPort()),
})
lk := tunnel.NewLink(tn, req.GetId(), from, link, conn)
lk := tunnel.NewLink(tn, id, from, link, conn)
lk.SetTargetIdx(fromIdx)
conn.SendConnectOK(from, fromIdx, req.GetId())
conn.SendConnectOK(from, fromIdx, id)
lk.Forward()
lk.OnWork <- struct{}{}
}
13 changes: 2 additions & 11 deletions code/client/pool/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,19 +106,10 @@ func (conn *Conn) loopRead(cancel context.CancelFunc) {
return
}
timeout = 0
var linkID string
switch msg.GetXType() {
case network.Msg_connect_req:
linkID = msg.GetCreq().GetId()
case network.Msg_connect_rep:
linkID = msg.GetCrep().GetId()
case network.Msg_disconnect:
linkID = msg.GetXDisconnect().GetId()
case network.Msg_forward:
linkID = msg.GetXData().GetLid()
case network.Msg_keepalive:
if msg.GetXType() == network.Msg_keepalive {
continue
}
linkID := msg.GetLinkId()
conn.RLock()
ch := conn.read[linkID]
conn.RUnlock()
Expand Down
14 changes: 5 additions & 9 deletions code/client/pool/send.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ func (conn *Conn) SendConnectReq(id string, cfg global.Tunnel) {
var msg network.Msg
msg.To = cfg.Target
msg.XType = network.Msg_connect_req
msg.LinkId = id
msg.Payload = &network.Msg_Creq{
Creq: &network.ConnectRequest{
Id: id,
Name: cfg.Name,
XType: tp,
Addr: cfg.RemoteAddr,
Expand All @@ -36,9 +36,9 @@ func (conn *Conn) SendConnectError(to string, toIdx uint32, id, info string) {
msg.To = to
msg.ToIdx = toIdx
msg.XType = network.Msg_connect_rep
msg.LinkId = id
msg.Payload = &network.Msg_Crep{
Crep: &network.ConnectResponse{
Id: id,
Ok: false,
Msg: info,
},
Expand All @@ -55,9 +55,9 @@ func (conn *Conn) SendConnectOK(to string, toIdx uint32, id string) {
msg.To = to
msg.ToIdx = toIdx
msg.XType = network.Msg_connect_rep
msg.LinkId = id
msg.Payload = &network.Msg_Crep{
Crep: &network.ConnectResponse{
Id: id,
Ok: true,
},
}
Expand All @@ -73,11 +73,7 @@ func (conn *Conn) SendDisconnect(to string, toIdx uint32, id string) {
msg.To = to
msg.ToIdx = toIdx
msg.XType = network.Msg_disconnect
msg.Payload = &network.Msg_XDisconnect{
XDisconnect: &network.Disconnect{
Id: id,
},
}
msg.LinkId = id
select {
case conn.write <- &msg:
case <-time.After(conn.parent.cfg.WriteTimeout):
Expand All @@ -95,9 +91,9 @@ func (conn *Conn) SendData(to string, toIdx uint32, id string, data []byte) {
msg.To = to
msg.ToIdx = toIdx
msg.XType = network.Msg_forward
msg.LinkId = id
msg.Payload = &network.Msg_XData{
XData: &network.Data{
Lid: id,
Data: dup(data),
},
}
Expand Down
Loading

0 comments on commit 85e2130

Please sign in to comment.