Skip to content

Commit

Permalink
Merge remote-tracking branch 'remotes/origin/dev'
Browse files Browse the repository at this point in the history
# Conflicts:
#	lib/mux/conn.go
#	lib/mux/queue.go
  • Loading branch information
ffdfgdfg committed Jan 31, 2020
2 parents 0a65975 + 099d3fc commit 5c37505
Show file tree
Hide file tree
Showing 40 changed files with 195 additions and 3,112 deletions.
21 changes: 11 additions & 10 deletions bridge/bridge.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package bridge

import (
"ehang.io/nps-mux"
"encoding/binary"
"errors"
"fmt"
Expand All @@ -15,7 +16,6 @@ import (
"ehang.io/nps/lib/conn"
"ehang.io/nps/lib/crypt"
"ehang.io/nps/lib/file"
"ehang.io/nps/lib/mux"
"ehang.io/nps/lib/version"
"ehang.io/nps/server/connection"
"ehang.io/nps/server/tool"
Expand All @@ -24,14 +24,14 @@ import (
)

type Client struct {
tunnel *mux.Mux
tunnel *nps_mux.Mux
signal *conn.Conn
file *mux.Mux
file *nps_mux.Mux
Version string
retryTime int // it will be add 1 when ping not ok until to 3 will close the client
}

func NewClient(t, f *mux.Mux, s *conn.Conn, vs string) *Client {
func NewClient(t, f *nps_mux.Mux, s *conn.Conn, vs string) *Client {
return &Client{
signal: s,
tunnel: t,
Expand All @@ -50,10 +50,10 @@ type Bridge struct {
CloseClient chan int
SecretChan chan *conn.Secret
ipVerify bool
runList map[int]interface{}
runList sync.Map //map[int]interface{}
}

func NewTunnel(tunnelPort int, tunnelType string, ipVerify bool, runList map[int]interface{}) *Bridge {
func NewTunnel(tunnelPort int, tunnelType string, ipVerify bool, runList sync.Map) *Bridge {
return &Bridge{
TunnelPort: tunnelPort,
tunnelType: tunnelType,
Expand Down Expand Up @@ -242,7 +242,7 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
go s.GetHealthFromClient(id, c)
logs.Info("clientId %d connection succeeded, address:%s ", id, c.Conn.RemoteAddr())
case common.WORK_CHAN:
muxConn := mux.NewMux(c.Conn, s.tunnelType)
muxConn := nps_mux.NewMux(c.Conn, s.tunnelType)
if v, ok := s.Client.LoadOrStore(id, NewClient(muxConn, nil, nil, vs)); ok {
v.(*Client).tunnel = muxConn
}
Expand All @@ -263,7 +263,7 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int, vs string) {
logs.Error("secret error, failed to match the key successfully")
}
case common.WORK_FILE:
muxConn := mux.NewMux(c.Conn, s.tunnelType)
muxConn := nps_mux.NewMux(c.Conn, s.tunnelType)
if v, ok := s.Client.LoadOrStore(id, NewClient(nil, muxConn, nil, vs)); ok {
v.(*Client).file = muxConn
}
Expand Down Expand Up @@ -321,7 +321,7 @@ func (s *Bridge) SendLinkInfo(clientId int, link *conn.Link, t *file.Tunnel) (ta
}
}
}
var tunnel *mux.Mux
var tunnel *nps_mux.Mux
if t != nil && t.Mode == "file" {
tunnel = v.(*Client).file
} else {
Expand Down Expand Up @@ -407,7 +407,8 @@ loop:
})
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
v := value.(*file.Tunnel)
if _, ok := s.runList[v.Id]; ok && v.Client.Id == id {
//if _, ok := s.runList[v.Id]; ok && v.Client.Id == id {
if _, ok := s.runList.Load(v.Id); ok && v.Client.Id == id {
str += v.Remark + common.CONN_DATA_SEQ
}
return true
Expand Down
2 changes: 1 addition & 1 deletion build.sh
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#/bash/sh
export VERSION=0.26.0
export VERSION=0.26.1

sudo apt-get install gcc-mingw-w64-i686
env GOOS=windows GOARCH=386 CGO_ENABLED=1 CC=i686-w64-mingw32-gcc go build -ldflags "-s -w -extldflags -static -extldflags -static" -buildmode=c-shared -o npc_sdk.dll cmd/npc/sdk.go
Expand Down
10 changes: 5 additions & 5 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package client
import (
"bufio"
"bytes"
"ehang.io/nps-mux"
"net"
"net/http"
"strconv"
Expand All @@ -15,7 +16,6 @@ import (
"ehang.io/nps/lib/config"
"ehang.io/nps/lib/conn"
"ehang.io/nps/lib/crypt"
"ehang.io/nps/lib/mux"
)

type TRPClient struct {
Expand All @@ -24,7 +24,7 @@ type TRPClient struct {
proxyUrl string
vKey string
p2pAddr map[string]string
tunnel *mux.Mux
tunnel *nps_mux.Mux
signal *conn.Conn
ticker *time.Ticker
cnf *config.Config
Expand Down Expand Up @@ -138,22 +138,22 @@ func (s *TRPClient) newUdpConn(localAddr, rAddr string, md5Password string) {
conn.SetUdpSession(udpTunnel)
logs.Trace("successful connection with client ,address %s", udpTunnel.RemoteAddr().String())
//read link info from remote
conn.Accept(mux.NewMux(udpTunnel, s.bridgeConnType), func(c net.Conn) {
conn.Accept(nps_mux.NewMux(udpTunnel, s.bridgeConnType), func(c net.Conn) {
go s.handleChan(c)
})
break
}
}
}

//mux tunnel
//pmux tunnel
func (s *TRPClient) newChan() {
tunnel, err := NewConn(s.bridgeConnType, s.vKey, s.svrAddr, common.WORK_CHAN, s.proxyUrl)
if err != nil {
logs.Error("connect to ", s.svrAddr, "error:", err)
return
}
s.tunnel = mux.NewMux(tunnel.Conn, s.bridgeConnType)
s.tunnel = nps_mux.NewMux(tunnel.Conn, s.bridgeConnType)
for {
src, err := s.tunnel.Accept()
if err != nil {
Expand Down
8 changes: 4 additions & 4 deletions client/local.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package client

import (
"ehang.io/nps-mux"
"errors"
"net"
"net/http"
Expand All @@ -13,7 +14,6 @@ import (
"ehang.io/nps/lib/conn"
"ehang.io/nps/lib/crypt"
"ehang.io/nps/lib/file"
"ehang.io/nps/lib/mux"
"ehang.io/nps/server/proxy"
"github.com/astaxie/beego/logs"
"github.com/xtaci/kcp-go"
Expand All @@ -22,7 +22,7 @@ import (
var (
LocalServer []*net.TCPListener
udpConn net.Conn
muxSession *mux.Mux
muxSession *nps_mux.Mux
fileServer []*http.Server
p2pNetBridge *p2pBridge
lock sync.RWMutex
Expand Down Expand Up @@ -73,7 +73,7 @@ func startLocalFileServer(config *config.CommonConfig, t *file.Tunnel, vkey stri
}
logs.Info("start local file system, local path %s, strip prefix %s ,remote port %s ", t.LocalPath, t.StripPre, t.Ports)
fileServer = append(fileServer, srv)
listener := mux.NewMux(remoteConn.Conn, common.CONN_TCP)
listener := nps_mux.NewMux(remoteConn.Conn, common.CONN_TCP)
logs.Error(srv.Serve(listener))
}

Expand Down Expand Up @@ -214,6 +214,6 @@ func newUdpConn(localAddr string, config *config.CommonConfig, l *config.LocalSe
logs.Trace("successful create a connection with server", remoteAddress)
conn.SetUdpSession(udpTunnel)
udpConn = udpTunnel
muxSession = mux.NewMux(udpConn, "kcp")
muxSession = nps_mux.NewMux(udpConn, "kcp")
p2pNetBridge = &p2pBridge{}
}
28 changes: 26 additions & 2 deletions cmd/npc/npc.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,31 @@ var (
debug = flag.Bool("debug", true, "npc debug")
)

const systemdScript = `[Unit]
Description={{.Description}}
ConditionFileIsExecutable={{.Path|cmdEscape}}
{{range $i, $dep := .Dependencies}}
{{$dep}} {{end}}
[Service]
LimitNOFILE=65536
StartLimitInterval=5
StartLimitBurst=10
ExecStart={{.Path|cmdEscape}}{{range .Arguments}} {{.|cmd}}{{end}}
{{if .ChRoot}}RootDirectory={{.ChRoot|cmd}}{{end}}
{{if .WorkingDirectory}}WorkingDirectory={{.WorkingDirectory|cmdEscape}}{{end}}
{{if .UserName}}User={{.UserName}}{{end}}
{{if .ReloadSignal}}ExecReload=/bin/kill -{{.ReloadSignal}} "$MAINPID"{{end}}
{{if .PIDFile}}PIDFile={{.PIDFile|cmd}}{{end}}
{{if and .LogOutput .HasOutputFileSupport -}}
StandardOutput=file:/var/log/{{.Name}}.out
StandardError=file:/var/log/{{.Name}}.err
{{- end}}
Restart=always
RestartSec=120
[Install]
WantedBy=multi-user.target
`

func main() {
flag.Parse()
logs.Reset()
Expand All @@ -54,8 +79,6 @@ func main() {

// init service
options := make(service.KeyValue)
options["Restart"] = "on-success"
options["SuccessExitStatus"] = "1 2 8 SIGKILL"
svcConfig := &service.Config{
Name: "Npc",
DisplayName: "nps内网穿透客户端",
Expand All @@ -66,6 +89,7 @@ func main() {
svcConfig.Dependencies = []string{
"Requires=network.target",
"After=network-online.target syslog.target"}
svcConfig.Option["SystemdScript"] = systemdScript
}
for _, v := range os.Args[1:] {
switch v {
Expand Down
42 changes: 34 additions & 8 deletions cmd/nps/nps.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,31 @@ var (
level string
)

const systemdScript = `[Unit]
Description={{.Description}}
ConditionFileIsExecutable={{.Path|cmdEscape}}
{{range $i, $dep := .Dependencies}}
{{$dep}} {{end}}
[Service]
LimitNOFILE=65536
StartLimitInterval=5
StartLimitBurst=10
ExecStart={{.Path|cmdEscape}}{{range .Arguments}} {{.|cmd}}{{end}}
{{if .ChRoot}}RootDirectory={{.ChRoot|cmd}}{{end}}
{{if .WorkingDirectory}}WorkingDirectory={{.WorkingDirectory|cmdEscape}}{{end}}
{{if .UserName}}User={{.UserName}}{{end}}
{{if .ReloadSignal}}ExecReload=/bin/kill -{{.ReloadSignal}} "$MAINPID"{{end}}
{{if .PIDFile}}PIDFile={{.PIDFile|cmd}}{{end}}
{{if and .LogOutput .HasOutputFileSupport -}}
StandardOutput=file:/var/log/{{.Name}}.out
StandardError=file:/var/log/{{.Name}}.err
{{- end}}
Restart=always
RestartSec=120
[Install]
WantedBy=multi-user.target
`

func main() {
flag.Parse()
// init log
Expand All @@ -49,8 +74,6 @@ func main() {
}
// init service
options := make(service.KeyValue)
options["Restart"] = "on-success"
options["SuccessExitStatus"] = "1 2 8 SIGKILL"
svcConfig := &service.Config{
Name: "Nps",
DisplayName: "nps内网穿透代理服务器",
Expand All @@ -59,14 +82,15 @@ func main() {
}
svcConfig.Arguments = append(svcConfig.Arguments, "service")
if len(os.Args) > 1 && os.Args[1] == "service" {
logs.SetLogger(logs.AdapterFile, `{"level":`+level+`,"filename":"`+logPath+`","daily":false,"maxlines":100000,"color":true}`)
_ = logs.SetLogger(logs.AdapterFile, `{"level":`+level+`,"filename":"`+logPath+`","daily":false,"maxlines":100000,"color":true}`)
} else {
logs.SetLogger(logs.AdapterConsole, `{"level":`+level+`,"color":true}`)
_ = logs.SetLogger(logs.AdapterConsole, `{"level":`+level+`,"color":true}`)
}
if !common.IsWindows() {
svcConfig.Dependencies = []string{
"Requires=network.target",
"After=network-online.target syslog.target"}
svcConfig.Option["SystemdScript"] = systemdScript
}
prg := &nps{}
prg.exit = make(chan struct{})
Expand All @@ -82,8 +106,8 @@ func main() {
return
case "install":
// uninstall before
service.Control(s, "stop")
service.Control(s, "uninstall")
_ = service.Control(s, "stop")
_ = service.Control(s, "uninstall")

binPath := install.InstallNps()
svcConfig.Executable = binPath
Expand Down Expand Up @@ -111,18 +135,20 @@ func main() {
return
}
}
s.Run()
_ = s.Run()
}

type nps struct {
exit chan struct{}
}

func (p *nps) Start(s service.Service) error {
p.run()
_, _ = s.Status()
_ = p.run()
return nil
}
func (p *nps) Stop(s service.Service) error {
_, _ = s.Status()
close(p.exit)
if service.Interactive() {
os.Exit(0)
Expand Down
6 changes: 4 additions & 2 deletions conf/nps.conf
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ web_key_file=conf/server.key
#web_base_url=/nps

#Web API unauthenticated IP address(the len of auth_crypt_key must be 16)
auth_key=test
#Remove comments if needed
#auth_key=test
auth_crypt_key =1234567812345678

#allow_ports=9001-9009,10001,11000-12000
Expand All @@ -73,4 +74,5 @@ system_info_display=false
http_cache=false
http_cache_length=100


#get origin ip
http_add_origin_header=false
2 changes: 1 addition & 1 deletion docs/_coverpage.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
![logo](logo.svg)

# NPS <small>0.26.0</small>
# NPS <small>0.26.1</small>

> 一款轻量级、高性能、功能强大的内网穿透代理服务器
Expand Down
2 changes: 2 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
# web api

需要开启请先去掉`nps.conf``auth_key`的注释并配置一个合适的密钥
## webAPI验证说明
- 采用auth_key的验证方式
- 在提交的每个请求后面附带两个参数,`auth_key``timestamp`
Expand Down
4 changes: 1 addition & 3 deletions docs/description.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# 说明
## 获取用户真实ip
如需使用需要在`nps.conf`中设置`http_add_origin_header=true`

在域名代理模式中,可以通过request请求 header 中的 X-Forwarded-For 和 X-Real-IP 来获取用户真实 IP。

Expand All @@ -8,9 +9,6 @@
## 热更新支持
对于绝大多数配置,在web管理中的修改将实时使用,无需重启客户端或者服务端

## web端保护
在一分钟内,如果密码错误次数超过10次,该ip在一分钟内将不能再次登陆。

## 客户端地址显示
在web管理中将显示客户端的连接地址

Expand Down
2 changes: 1 addition & 1 deletion docs/feature.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ target_ip=10.1.50.2
```
## KCP协议支持

KCP 是一个快速可靠协议,能以比 TCP浪费10%-20%的带宽的代价,换取平均延迟降低 30%-40%,在弱网环境下对性能能有一定的提升。可在nps.conf中修改`bridge_type`为kcp
在网络质量非常好的情况下,例如专线,内网,可以开启略微降低延迟。如需使用可在nps.conf中修改`bridge_type`为kcp
,设置后本代理将开启udp端口(`bridge_port`

注意:当服务端为kcp时,客户端连接时也需要使用相同配置,无配置文件模式加上参数type=kcp,配置文件模式在配置文件中设置tp=kcp
Expand Down

0 comments on commit 5c37505

Please sign in to comment.