Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0e2b6283c | ||
|
|
a66b465046 | ||
|
|
7ec3e82b0f | ||
|
|
7e93497f1a | ||
|
|
e24b2921ac | ||
|
|
572dcd2aab | ||
|
|
97330bfbdc | ||
|
|
f78e81b452 | ||
|
|
d45bc3c066 | ||
|
|
f81fb7760e | ||
|
|
149b2e467c | ||
|
|
a29a7d4923 | ||
|
|
0d257a95dd | ||
|
|
ad22ada1f1 | ||
|
|
948d931883 | ||
|
|
8afa6b2929 | ||
|
|
7a49e48b89 | ||
|
|
0819afc9da | ||
|
|
eecf1c6c69 | ||
|
|
9428457487 | ||
|
|
f3e90f146d | ||
|
|
7bf54b608d | ||
|
|
496d9f52f9 | ||
|
|
d97b18f51f | ||
|
|
037e7b28f1 | ||
|
|
b3660c3b8d | ||
|
|
cbc3bd2afe | ||
|
|
5fc51f40a7 | ||
|
|
1c1aa5ec5b | ||
|
|
f526c56784 | ||
|
|
fbbd4bace2 | ||
|
|
534d428c6d | ||
|
|
0492268190 | ||
|
|
01fca7d568 | ||
|
|
0711b9befb | ||
|
|
2c13a02bdc | ||
|
|
204c53ddd3 | ||
|
|
6788f24821 | ||
|
|
e65ab33749 | ||
|
|
7f94b3871a | ||
|
|
aa5b869da9 | ||
|
|
f7898e019e | ||
|
|
ca04f19275 | ||
|
|
db43405237 | ||
|
|
750ecb824a | ||
|
|
2c608ddb7f | ||
|
|
934402e97d | ||
|
|
6fe69bc6b1 | ||
|
|
dab51c32a2 | ||
|
|
48c7309973 | ||
|
|
f2329f72f6 | ||
|
|
9f03c2f6eb | ||
|
|
7a8cb3d5b6 | ||
|
|
3b18d66835 | ||
|
|
9f6b33a62b | ||
|
|
44d314515b |
@@ -0,0 +1 @@
|
||||
.idea
|
||||
+430
-200
@@ -1,87 +1,107 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/kcp"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"fmt"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/mux"
|
||||
"github.com/cnlh/nps/lib/version"
|
||||
"github.com/cnlh/nps/server/connection"
|
||||
"github.com/cnlh/nps/server/tool"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
tunnel *conn.Conn
|
||||
signal *conn.Conn
|
||||
linkMap map[int]*conn.Link
|
||||
linkStatusMap map[int]bool
|
||||
stop chan bool
|
||||
tunnel *mux.Mux
|
||||
signal *conn.Conn
|
||||
file *mux.Mux
|
||||
retryTime int // it will be add 1 when ping not ok until to 3 will close the client
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func NewClient(t *conn.Conn, s *conn.Conn) *Client {
|
||||
func NewClient(t, f *mux.Mux, s *conn.Conn) *Client {
|
||||
return &Client{
|
||||
linkMap: make(map[int]*conn.Link),
|
||||
stop: make(chan bool),
|
||||
linkStatusMap: make(map[int]bool),
|
||||
signal: s,
|
||||
tunnel: t,
|
||||
signal: s,
|
||||
tunnel: t,
|
||||
file: f,
|
||||
}
|
||||
}
|
||||
|
||||
type Bridge struct {
|
||||
TunnelPort int //通信隧道端口
|
||||
tcpListener *net.TCPListener //server端监听
|
||||
kcpListener *kcp.Listener //server端监听
|
||||
Client map[int]*Client
|
||||
RunList map[int]interface{} //运行中的任务
|
||||
tunnelType string //bridge type kcp or tcp
|
||||
lock sync.Mutex
|
||||
tunnelLock sync.Mutex
|
||||
clientLock sync.RWMutex
|
||||
TunnelPort int //通信隧道端口
|
||||
Client map[int]*Client
|
||||
tunnelType string //bridge type kcp or tcp
|
||||
OpenTask chan *file.Tunnel
|
||||
CloseTask chan *file.Tunnel
|
||||
CloseClient chan int
|
||||
SecretChan chan *conn.Secret
|
||||
clientLock sync.RWMutex
|
||||
Register map[string]time.Time
|
||||
registerLock sync.RWMutex
|
||||
ipVerify bool
|
||||
runList map[int]interface{}
|
||||
}
|
||||
|
||||
func NewTunnel(tunnelPort int, runList map[int]interface{}, tunnelType string) *Bridge {
|
||||
func NewTunnel(tunnelPort int, tunnelType string, ipVerify bool, runList map[int]interface{}) *Bridge {
|
||||
t := new(Bridge)
|
||||
t.TunnelPort = tunnelPort
|
||||
t.Client = make(map[int]*Client)
|
||||
t.RunList = runList
|
||||
t.tunnelType = tunnelType
|
||||
t.OpenTask = make(chan *file.Tunnel)
|
||||
t.CloseTask = make(chan *file.Tunnel)
|
||||
t.CloseClient = make(chan int)
|
||||
t.Register = make(map[string]time.Time)
|
||||
t.ipVerify = ipVerify
|
||||
t.runList = runList
|
||||
t.SecretChan = make(chan *conn.Secret)
|
||||
return t
|
||||
}
|
||||
|
||||
func (s *Bridge) StartTunnel() error {
|
||||
var err error
|
||||
go s.ping()
|
||||
if s.tunnelType == "kcp" {
|
||||
s.kcpListener, err = kcp.ListenWithOptions(":"+strconv.Itoa(s.TunnelPort), nil, 150, 3)
|
||||
listener, err := kcp.ListenWithOptions(beego.AppConfig.String("bridge_ip")+":"+beego.AppConfig.String("bridge_port"), nil, 150, 3)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
return err
|
||||
}
|
||||
logs.Info("server start, the bridge type is %s, the bridge port is %d", s.tunnelType, s.TunnelPort)
|
||||
go func() {
|
||||
for {
|
||||
c, err := s.kcpListener.AcceptKCP()
|
||||
c, err := listener.AcceptKCP()
|
||||
conn.SetUdpSession(c)
|
||||
if err != nil {
|
||||
lg.Println(err)
|
||||
logs.Warn(err)
|
||||
continue
|
||||
}
|
||||
go s.cliProcess(conn.NewConn(c))
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
s.tcpListener, err = net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), s.TunnelPort, ""})
|
||||
listener, err := connection.GetBridgeListener(s.tunnelType)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
return err
|
||||
}
|
||||
go func() {
|
||||
for {
|
||||
c, err := s.tcpListener.Accept()
|
||||
c, err := listener.Accept()
|
||||
if err != nil {
|
||||
lg.Println(err)
|
||||
logs.Warn(err)
|
||||
continue
|
||||
}
|
||||
go s.cliProcess(conn.NewConn(c))
|
||||
@@ -91,48 +111,130 @@ func (s *Bridge) StartTunnel() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
//get health information form client
|
||||
func (s *Bridge) GetHealthFromClient(id int, c *conn.Conn) {
|
||||
for {
|
||||
if info, status, err := c.GetHealthInfo(); err != nil {
|
||||
logs.Error(err)
|
||||
break
|
||||
} else if !status { //the status is true , return target to the targetArr
|
||||
for _, v := range file.GetCsvDb().Tasks {
|
||||
if v.Client.Id == id && v.Mode == "tcp" && strings.Contains(v.Target, info) {
|
||||
v.Lock()
|
||||
if v.TargetArr == nil || (len(v.TargetArr) == 0 && len(v.HealthRemoveArr) == 0) {
|
||||
v.TargetArr = common.TrimArr(strings.Split(v.Target, "\n"))
|
||||
}
|
||||
v.TargetArr = common.RemoveArrVal(v.TargetArr, info)
|
||||
if v.HealthRemoveArr == nil {
|
||||
v.HealthRemoveArr = make([]string, 0)
|
||||
}
|
||||
v.HealthRemoveArr = append(v.HealthRemoveArr, info)
|
||||
v.Unlock()
|
||||
}
|
||||
}
|
||||
for _, v := range file.GetCsvDb().Hosts {
|
||||
if v.Client.Id == id && strings.Contains(v.Target, info) {
|
||||
v.Lock()
|
||||
if v.TargetArr == nil || (len(v.TargetArr) == 0 && len(v.HealthRemoveArr) == 0) {
|
||||
v.TargetArr = common.TrimArr(strings.Split(v.Target, "\n"))
|
||||
}
|
||||
v.TargetArr = common.RemoveArrVal(v.TargetArr, info)
|
||||
if v.HealthRemoveArr == nil {
|
||||
v.HealthRemoveArr = make([]string, 0)
|
||||
}
|
||||
v.HealthRemoveArr = append(v.HealthRemoveArr, info)
|
||||
v.Unlock()
|
||||
}
|
||||
}
|
||||
} else { //the status is false,remove target from the targetArr
|
||||
for _, v := range file.GetCsvDb().Tasks {
|
||||
if v.Client.Id == id && v.Mode == "tcp" && common.IsArrContains(v.HealthRemoveArr, info) && !common.IsArrContains(v.TargetArr, info) {
|
||||
v.Lock()
|
||||
v.TargetArr = append(v.TargetArr, info)
|
||||
v.HealthRemoveArr = common.RemoveArrVal(v.HealthRemoveArr, info)
|
||||
v.Unlock()
|
||||
}
|
||||
}
|
||||
for _, v := range file.GetCsvDb().Hosts {
|
||||
if v.Client.Id == id && common.IsArrContains(v.HealthRemoveArr, info) && !common.IsArrContains(v.TargetArr, info) {
|
||||
v.Lock()
|
||||
v.TargetArr = append(v.TargetArr, info)
|
||||
v.HealthRemoveArr = common.RemoveArrVal(v.HealthRemoveArr, info)
|
||||
v.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//验证失败,返回错误验证flag,并且关闭连接
|
||||
func (s *Bridge) verifyError(c *conn.Conn) {
|
||||
c.Write([]byte(common.VERIFY_EER))
|
||||
c.Conn.Close()
|
||||
}
|
||||
|
||||
func (s *Bridge) verifySuccess(c *conn.Conn) {
|
||||
c.Write([]byte(common.VERIFY_SUCCESS))
|
||||
}
|
||||
|
||||
func (s *Bridge) cliProcess(c *conn.Conn) {
|
||||
c.SetReadDeadline(5, s.tunnelType)
|
||||
var buf []byte
|
||||
var err error
|
||||
if buf, err = c.ReadLen(32); err != nil {
|
||||
//read test flag
|
||||
if _, err := c.GetShortContent(3); err != nil {
|
||||
logs.Info("The client %s connect error", c.Conn.RemoteAddr())
|
||||
return
|
||||
}
|
||||
//version check
|
||||
if b, err := c.GetShortContent(32); err != nil || string(b) != crypt.Md5(version.GetVersion()) {
|
||||
logs.Info("The client %s version does not match", c.Conn.RemoteAddr())
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
//验证
|
||||
id, err := file.GetCsvDb().GetIdByVerifyKey(string(buf), c.Conn.RemoteAddr().String())
|
||||
if err != nil {
|
||||
lg.Println("当前客户端连接校验错误,关闭此客户端:", c.Conn.RemoteAddr())
|
||||
s.verifyError(c)
|
||||
//write server version to client
|
||||
c.Write([]byte(crypt.Md5(version.GetVersion())))
|
||||
c.SetReadDeadline(5, s.tunnelType)
|
||||
var buf []byte
|
||||
var err error
|
||||
//get vKey from client
|
||||
if buf, err = c.GetShortContent(32); err != nil {
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
//做一个判断 添加到对应的channel里面以供使用
|
||||
//verify
|
||||
id, err := file.GetCsvDb().GetIdByVerifyKey(string(buf), c.Conn.RemoteAddr().String())
|
||||
if err != nil {
|
||||
logs.Info("Current client connection validation error, close this client:", c.Conn.RemoteAddr())
|
||||
s.verifyError(c)
|
||||
return
|
||||
} else {
|
||||
s.verifySuccess(c)
|
||||
}
|
||||
if flag, err := c.ReadFlag(); err == nil {
|
||||
s.typeDeal(flag, c, id)
|
||||
} else {
|
||||
logs.Warn(err, flag)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Bridge) closeClient(id int) {
|
||||
func (s *Bridge) DelClient(id int, isOther bool) {
|
||||
s.clientLock.Lock()
|
||||
defer s.clientLock.Unlock()
|
||||
if v, ok := s.Client[id]; ok {
|
||||
v.signal.WriteClose()
|
||||
if c, err := file.GetCsvDb().GetClient(id); err == nil && c.NoStore {
|
||||
s.CloseClient <- c.Id
|
||||
}
|
||||
if v.signal != nil {
|
||||
v.signal.Close()
|
||||
}
|
||||
delete(s.Client, id)
|
||||
}
|
||||
}
|
||||
|
||||
//tcp连接类型区分
|
||||
//use different
|
||||
func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int) {
|
||||
switch typeVal {
|
||||
case common.WORK_MAIN:
|
||||
//客户端已经存在,下线
|
||||
//the vKey connect by another ,close the client of before
|
||||
s.clientLock.Lock()
|
||||
if v, ok := s.Client[id]; ok {
|
||||
s.clientLock.Unlock()
|
||||
@@ -143,181 +245,309 @@ func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int) {
|
||||
v.signal = c
|
||||
v.Unlock()
|
||||
} else {
|
||||
s.Client[id] = NewClient(nil, c)
|
||||
s.Client[id] = NewClient(nil, nil, c)
|
||||
s.clientLock.Unlock()
|
||||
}
|
||||
lg.Printf("客户端%d连接成功,地址为:%s", id, c.Conn.RemoteAddr())
|
||||
go s.GetStatus(id)
|
||||
go s.GetHealthFromClient(id, c)
|
||||
logs.Info("clientId %d connection succeeded, address:%s ", id, c.Conn.RemoteAddr())
|
||||
case common.WORK_CHAN:
|
||||
s.clientLock.Lock()
|
||||
if v, ok := s.Client[id]; ok {
|
||||
s.clientLock.Unlock()
|
||||
v.Lock()
|
||||
v.tunnel = c
|
||||
v.tunnel = mux.NewMux(c.Conn, s.tunnelType)
|
||||
v.Unlock()
|
||||
} else {
|
||||
s.Client[id] = NewClient(c, nil)
|
||||
s.Client[id] = NewClient(mux.NewMux(c.Conn, s.tunnelType), nil, nil)
|
||||
s.clientLock.Unlock()
|
||||
}
|
||||
go s.clientCopy(id)
|
||||
case common.WORK_CONFIG:
|
||||
var isPub bool
|
||||
client, err := file.GetCsvDb().GetClient(id);
|
||||
if err == nil {
|
||||
if client.VerifyKey == beego.AppConfig.String("public_vkey") {
|
||||
isPub = true
|
||||
} else {
|
||||
isPub = false
|
||||
}
|
||||
}
|
||||
binary.Write(c, binary.LittleEndian, isPub)
|
||||
go s.getConfig(c, isPub, client)
|
||||
case common.WORK_REGISTER:
|
||||
go s.register(c)
|
||||
case common.WORK_SECRET:
|
||||
if b, err := c.GetShortContent(32); err == nil {
|
||||
s.SecretChan <- conn.NewSecret(string(b), c)
|
||||
}
|
||||
case common.WORK_FILE:
|
||||
s.clientLock.Lock()
|
||||
if v, ok := s.Client[id]; ok {
|
||||
s.clientLock.Unlock()
|
||||
v.Lock()
|
||||
v.file = mux.NewMux(c.Conn, s.tunnelType)
|
||||
v.Unlock()
|
||||
} else {
|
||||
s.Client[id] = NewClient(nil, mux.NewMux(c.Conn, s.tunnelType), nil)
|
||||
s.clientLock.Unlock()
|
||||
}
|
||||
case common.WORK_P2P:
|
||||
//read md5 secret
|
||||
if b, err := c.GetShortContent(32); err != nil {
|
||||
return
|
||||
} else if t := file.GetCsvDb().GetTaskByMd5Password(string(b)); t == nil {
|
||||
return
|
||||
} else {
|
||||
s.clientLock.Lock()
|
||||
if v, ok := s.Client[t.Client.Id]; !ok {
|
||||
s.clientLock.Unlock()
|
||||
return
|
||||
} else {
|
||||
s.clientLock.Unlock()
|
||||
//向密钥对应的客户端发送与服务端udp建立连接信息,地址,密钥
|
||||
v.signal.Write([]byte(common.NEW_UDP_CONN))
|
||||
svrAddr := beego.AppConfig.String("p2p_ip") + ":" + beego.AppConfig.String("p2p_port")
|
||||
if err != nil {
|
||||
logs.Warn("get local udp addr error")
|
||||
return
|
||||
}
|
||||
v.signal.WriteLenContent([]byte(svrAddr))
|
||||
v.signal.WriteLenContent(b)
|
||||
//向该请求者发送建立连接请求,服务器地址
|
||||
c.WriteLenContent([]byte(svrAddr))
|
||||
}
|
||||
}
|
||||
}
|
||||
c.SetAlive(s.tunnelType)
|
||||
return
|
||||
}
|
||||
|
||||
//等待
|
||||
func (s *Bridge) waitStatus(clientId, id int) (bool) {
|
||||
ticker := time.NewTicker(time.Millisecond * 100)
|
||||
stop := time.After(time.Second * 10)
|
||||
//register ip
|
||||
func (s *Bridge) register(c *conn.Conn) {
|
||||
var hour int32
|
||||
if err := binary.Read(c, binary.LittleEndian, &hour); err == nil {
|
||||
s.registerLock.Lock()
|
||||
s.Register[common.GetIpByAddr(c.Conn.RemoteAddr().String())] = time.Now().Add(time.Hour * time.Duration(hour))
|
||||
s.registerLock.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Bridge) SendLinkInfo(clientId int, link *conn.Link, linkAddr string, t *file.Tunnel) (target net.Conn, err error) {
|
||||
s.clientLock.Lock()
|
||||
if v, ok := s.Client[clientId]; ok {
|
||||
s.clientLock.Unlock()
|
||||
|
||||
//If ip is restricted to do ip verification
|
||||
if s.ipVerify {
|
||||
s.registerLock.Lock()
|
||||
ip := common.GetIpByAddr(linkAddr)
|
||||
if v, ok := s.Register[ip]; !ok {
|
||||
s.registerLock.Unlock()
|
||||
return nil, errors.New(fmt.Sprintf("The ip %s is not in the validation list", ip))
|
||||
} else {
|
||||
s.registerLock.Unlock()
|
||||
if !v.After(time.Now()) {
|
||||
return nil, errors.New(fmt.Sprintf("The validity of the ip %s has expired", ip))
|
||||
}
|
||||
}
|
||||
}
|
||||
var tunnel *mux.Mux
|
||||
if t != nil && t.Mode == "file" {
|
||||
tunnel = v.file
|
||||
} else {
|
||||
tunnel = v.tunnel
|
||||
}
|
||||
if tunnel == nil {
|
||||
err = errors.New("the client connect error")
|
||||
return
|
||||
}
|
||||
|
||||
if target, err = tunnel.NewConn(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if t != nil && t.Mode == "file" {
|
||||
return
|
||||
}
|
||||
|
||||
if _, err = conn.NewConn(target).SendLinkInfo(link); err != nil {
|
||||
logs.Info("new connect error ,the target %s refuse to connect", link.Host)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
s.clientLock.Unlock()
|
||||
err = errors.New(fmt.Sprintf("the client %d is not connect", clientId))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Bridge) ping() {
|
||||
ticker := time.NewTicker(time.Second * 5)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
s.clientLock.Lock()
|
||||
if v, ok := s.Client[clientId]; ok {
|
||||
s.clientLock.Unlock()
|
||||
v.Lock()
|
||||
if vv, ok := v.linkStatusMap[id]; ok {
|
||||
ticker.Stop()
|
||||
v.Unlock()
|
||||
return vv
|
||||
}
|
||||
v.Unlock()
|
||||
} else {
|
||||
s.clientLock.Unlock()
|
||||
}
|
||||
case <-stop:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Bridge) SendLinkInfo(clientId int, link *conn.Link) (tunnel *conn.Conn, err error) {
|
||||
s.clientLock.Lock()
|
||||
if v, ok := s.Client[clientId]; ok {
|
||||
s.clientLock.Unlock()
|
||||
v.signal.SendLinkInfo(link)
|
||||
if err != nil {
|
||||
lg.Println("send error:", err, link.Id)
|
||||
s.DelClient(clientId)
|
||||
return
|
||||
}
|
||||
if v.tunnel == nil {
|
||||
err = errors.New("tunnel获取错误")
|
||||
return
|
||||
} else {
|
||||
tunnel = v.tunnel
|
||||
}
|
||||
v.Lock()
|
||||
v.linkMap[link.Id] = link
|
||||
v.Unlock()
|
||||
if !s.waitStatus(clientId, link.Id) {
|
||||
err = errors.New("连接失败")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
s.clientLock.Unlock()
|
||||
err = errors.New("客户端未连接")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//得到一个tcp隧道
|
||||
func (s *Bridge) GetTunnel(id int, en, de int, crypt, mux bool) (conn *conn.Conn, err error) {
|
||||
s.clientLock.Lock()
|
||||
defer s.clientLock.Unlock()
|
||||
if v, ok := s.Client[id]; !ok {
|
||||
err = errors.New("客户端未连接")
|
||||
} else {
|
||||
conn = v.tunnel
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//得到一个通信通道
|
||||
func (s *Bridge) GetSignal(id int) (conn *conn.Conn, err error) {
|
||||
s.clientLock.Lock()
|
||||
defer s.clientLock.Unlock()
|
||||
if v, ok := s.Client[id]; !ok {
|
||||
err = errors.New("客户端未连接")
|
||||
} else {
|
||||
conn = v.signal
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//删除通信通道
|
||||
func (s *Bridge) DelClient(id int) {
|
||||
s.closeClient(id)
|
||||
}
|
||||
|
||||
func (s *Bridge) verify(id int) bool {
|
||||
for k := range s.RunList {
|
||||
if k == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (s *Bridge) GetStatus(clientId int) {
|
||||
s.clientLock.Lock()
|
||||
client := s.Client[clientId]
|
||||
s.clientLock.Unlock()
|
||||
|
||||
if client == nil {
|
||||
return
|
||||
}
|
||||
for {
|
||||
if id, status, err := client.signal.GetConnStatus(); err != nil {
|
||||
s.closeClient(clientId)
|
||||
return
|
||||
} else {
|
||||
client.Lock()
|
||||
client.linkStatusMap[id] = status
|
||||
client.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Bridge) clientCopy(clientId int) {
|
||||
|
||||
s.clientLock.Lock()
|
||||
client := s.Client[clientId]
|
||||
s.clientLock.Unlock()
|
||||
|
||||
for {
|
||||
if id, err := client.tunnel.GetLen(); err != nil {
|
||||
s.closeClient(clientId)
|
||||
lg.Println("读取msg id 错误", err, id)
|
||||
break
|
||||
} else {
|
||||
client.Lock()
|
||||
if link, ok := client.linkMap[id]; ok {
|
||||
client.Unlock()
|
||||
if content, err := client.tunnel.GetMsgContent(link); err != nil {
|
||||
pool.PutBufPoolCopy(content)
|
||||
s.closeClient(clientId)
|
||||
lg.Println("read msg content error", err, "close client")
|
||||
break
|
||||
} else {
|
||||
if len(content) == len(common.IO_EOF) && string(content) == common.IO_EOF {
|
||||
if link.Conn != nil {
|
||||
link.Conn.Close()
|
||||
}
|
||||
} else {
|
||||
if link.UdpListener != nil && link.UdpRemoteAddr != nil {
|
||||
link.UdpListener.WriteToUDP(content, link.UdpRemoteAddr)
|
||||
} else {
|
||||
link.Conn.Write(content)
|
||||
}
|
||||
link.Flow.Add(0, len(content))
|
||||
arr := make([]int, 0)
|
||||
for k, v := range s.Client {
|
||||
if v.tunnel == nil || v.signal == nil {
|
||||
v.retryTime += 1
|
||||
if v.retryTime >= 3 {
|
||||
arr = append(arr, k)
|
||||
}
|
||||
pool.PutBufPoolCopy(content)
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
client.Unlock()
|
||||
continue
|
||||
if v.tunnel.IsClose {
|
||||
arr = append(arr, k)
|
||||
}
|
||||
}
|
||||
s.clientLock.Unlock()
|
||||
for _, v := range arr {
|
||||
logs.Info("the client %d closed", v)
|
||||
s.DelClient(v, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//get config and add task from client config
|
||||
func (s *Bridge) getConfig(c *conn.Conn, isPub bool, client *file.Client) {
|
||||
var fail bool
|
||||
loop:
|
||||
for {
|
||||
flag, err := c.ReadFlag()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
switch flag {
|
||||
case common.WORK_STATUS:
|
||||
if b, err := c.GetShortContent(32); err != nil {
|
||||
break loop
|
||||
} else {
|
||||
var str string
|
||||
id, err := file.GetCsvDb().GetClientIdByVkey(string(b))
|
||||
if err != nil {
|
||||
break loop
|
||||
}
|
||||
file.GetCsvDb().Lock()
|
||||
for _, v := range file.GetCsvDb().Hosts {
|
||||
if v.Client.Id == id {
|
||||
str += v.Remark + common.CONN_DATA_SEQ
|
||||
}
|
||||
}
|
||||
for _, v := range file.GetCsvDb().Tasks {
|
||||
if _, ok := s.runList[v.Id]; ok && v.Client.Id == id {
|
||||
str += v.Remark + common.CONN_DATA_SEQ
|
||||
}
|
||||
}
|
||||
file.GetCsvDb().Unlock()
|
||||
binary.Write(c, binary.LittleEndian, int32(len([]byte(str))))
|
||||
binary.Write(c, binary.LittleEndian, []byte(str))
|
||||
}
|
||||
case common.NEW_CONF:
|
||||
var err error
|
||||
if client, err = c.GetConfigInfo(); err != nil {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
} else {
|
||||
if err = file.GetCsvDb().NewClient(client); err != nil {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
}
|
||||
c.WriteAddOk()
|
||||
c.Write([]byte(client.VerifyKey))
|
||||
s.clientLock.Lock()
|
||||
s.Client[client.Id] = NewClient(nil, nil, nil)
|
||||
s.clientLock.Unlock()
|
||||
}
|
||||
case common.NEW_HOST:
|
||||
h, err := c.GetHostInfo()
|
||||
if err != nil {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
}
|
||||
h.Client = client
|
||||
if h.Location == "" {
|
||||
h.Location = "/"
|
||||
}
|
||||
if !client.HasHost(h) {
|
||||
if file.GetCsvDb().IsHostExist(h) {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
} else {
|
||||
file.GetCsvDb().NewHost(h)
|
||||
c.WriteAddOk()
|
||||
}
|
||||
} else {
|
||||
c.WriteAddOk()
|
||||
}
|
||||
case common.NEW_TASK:
|
||||
if t, err := c.GetTaskInfo(); err != nil {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
} else {
|
||||
ports := common.GetPorts(t.Ports)
|
||||
targets := common.GetPorts(t.Target)
|
||||
if len(ports) > 1 && (t.Mode == "tcp" || t.Mode == "udp") && (len(ports) != len(targets)) {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
} else if t.Mode == "secret" {
|
||||
ports = append(ports, 0)
|
||||
}
|
||||
if len(ports) == 0 {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
}
|
||||
for i := 0; i < len(ports); i++ {
|
||||
tl := new(file.Tunnel)
|
||||
tl.Mode = t.Mode
|
||||
tl.Port = ports[i]
|
||||
if len(ports) == 1 {
|
||||
tl.Target = t.Target
|
||||
tl.Remark = t.Remark
|
||||
} else {
|
||||
tl.Remark = t.Remark + "_" + strconv.Itoa(tl.Port)
|
||||
if t.TargetAddr != "" {
|
||||
tl.Target = t.TargetAddr + ":" + strconv.Itoa(targets[i])
|
||||
} else {
|
||||
tl.Target = strconv.Itoa(targets[i])
|
||||
}
|
||||
}
|
||||
tl.Id = file.GetCsvDb().GetTaskId()
|
||||
tl.Status = true
|
||||
tl.Flow = new(file.Flow)
|
||||
tl.NoStore = true
|
||||
tl.Client = client
|
||||
tl.Password = t.Password
|
||||
tl.LocalPath = t.LocalPath
|
||||
tl.StripPre = t.StripPre
|
||||
if !client.HasTunnel(tl) {
|
||||
if err := file.GetCsvDb().NewTask(tl); err != nil {
|
||||
logs.Notice("Add task error ", err.Error())
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
}
|
||||
if b := tool.TestServerPort(tl.Port, tl.Mode); !b && t.Mode != "secret" && t.Mode != "p2p" {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
} else {
|
||||
s.OpenTask <- tl
|
||||
}
|
||||
}
|
||||
c.WriteAddOk()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if fail && client != nil {
|
||||
s.DelClient(client.Id, false)
|
||||
}
|
||||
c.Close()
|
||||
}
|
||||
|
||||
+175
-134
@@ -2,192 +2,233 @@ package client
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/config"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/kcp"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"github.com/cnlh/nps/lib/mux"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
|
||||
"net"
|
||||
"sync"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
type TRPClient struct {
|
||||
svrAddr string
|
||||
linkMap map[int]*conn.Link
|
||||
stop chan bool
|
||||
tunnel *conn.Conn
|
||||
bridgeConnType string
|
||||
sync.Mutex
|
||||
vKey string
|
||||
proxyUrl string
|
||||
vKey string
|
||||
tunnel *mux.Mux
|
||||
signal *conn.Conn
|
||||
ticker *time.Ticker
|
||||
cnf *config.Config
|
||||
}
|
||||
|
||||
//new client
|
||||
func NewRPClient(svraddr string, vKey string, bridgeConnType string) *TRPClient {
|
||||
func NewRPClient(svraddr string, vKey string, bridgeConnType string, proxyUrl string, cnf *config.Config) *TRPClient {
|
||||
return &TRPClient{
|
||||
svrAddr: svraddr,
|
||||
linkMap: make(map[int]*conn.Link),
|
||||
stop: make(chan bool),
|
||||
Mutex: sync.Mutex{},
|
||||
vKey: vKey,
|
||||
bridgeConnType: bridgeConnType,
|
||||
proxyUrl: proxyUrl,
|
||||
cnf: cnf,
|
||||
}
|
||||
}
|
||||
|
||||
//start
|
||||
func (s *TRPClient) Start() error {
|
||||
s.NewConn()
|
||||
return nil
|
||||
}
|
||||
|
||||
//新建
|
||||
func (s *TRPClient) NewConn() {
|
||||
var err error
|
||||
var c net.Conn
|
||||
func (s *TRPClient) Start() {
|
||||
retry:
|
||||
if s.bridgeConnType == "tcp" {
|
||||
c, err = net.Dial("tcp", s.svrAddr)
|
||||
} else {
|
||||
var sess *kcp.UDPSession
|
||||
sess, err = kcp.DialWithOptions(s.svrAddr, nil, 150, 3)
|
||||
conn.SetUdpSession(sess)
|
||||
c = sess
|
||||
}
|
||||
c, err := NewConn(s.bridgeConnType, s.vKey, s.svrAddr, common.WORK_MAIN, s.proxyUrl)
|
||||
if err != nil {
|
||||
lg.Println("连接服务端失败,五秒后将重连")
|
||||
logs.Error("The connection server failed and will be reconnected in five seconds")
|
||||
time.Sleep(time.Second * 5)
|
||||
goto retry
|
||||
return
|
||||
}
|
||||
s.processor(conn.NewConn(c))
|
||||
|
||||
logs.Info("Successful connection with server %s", s.svrAddr)
|
||||
go s.ping()
|
||||
s.processor(c)
|
||||
}
|
||||
|
||||
func (s *TRPClient) Close() {
|
||||
s.tunnel.Close()
|
||||
s.signal.Close()
|
||||
s.ticker.Stop()
|
||||
}
|
||||
|
||||
//处理
|
||||
func (s *TRPClient) processor(c *conn.Conn) {
|
||||
c.SetAlive(s.bridgeConnType)
|
||||
if _, err := c.Write([]byte(common.Getverifyval(s.vKey))); err != nil {
|
||||
return
|
||||
}
|
||||
c.WriteMain()
|
||||
s.signal = c
|
||||
go s.dealChan()
|
||||
if s.cnf != nil && len(s.cnf.Healths) > 0 {
|
||||
go heathCheck(s.cnf.Healths, s.signal)
|
||||
}
|
||||
for {
|
||||
flags, err := c.ReadFlag()
|
||||
if err != nil {
|
||||
lg.Println("服务端断开,正在重新连接")
|
||||
logs.Error("Accept server data error %s, end this service", err.Error())
|
||||
break
|
||||
}
|
||||
switch flags {
|
||||
case common.VERIFY_EER:
|
||||
lg.Fatalf("vKey:%s不正确,服务端拒绝连接,请检查", s.vKey)
|
||||
case common.NEW_CONN:
|
||||
if link, err := c.GetLinkInfo(); err != nil {
|
||||
break
|
||||
} else {
|
||||
s.Lock()
|
||||
s.linkMap[link.Id] = link
|
||||
s.Unlock()
|
||||
go s.linkProcess(link, c)
|
||||
}
|
||||
logs.Error("VKey:%s is incorrect, the server refuses to connect, please check", s.vKey)
|
||||
os.Exit(0)
|
||||
case common.RES_CLOSE:
|
||||
lg.Fatalln("该vkey被另一客户连接")
|
||||
logs.Error("The authentication key is connected by another client or the server closes the client.")
|
||||
os.Exit(0)
|
||||
case common.RES_MSG:
|
||||
lg.Println("服务端返回错误,重新连接")
|
||||
logs.Error("Server-side return error")
|
||||
break
|
||||
case common.NEW_UDP_CONN:
|
||||
//读取服务端地址、密钥 继续做处理
|
||||
if lAddr, err := c.GetShortLenContent(); err != nil {
|
||||
logs.Warn(err)
|
||||
return
|
||||
} else if pwd, err := c.GetShortLenContent(); err == nil {
|
||||
go s.newUdpConn(string(lAddr), string(pwd))
|
||||
}
|
||||
default:
|
||||
lg.Println("无法解析该错误,重新连接")
|
||||
logs.Warn("The error could not be resolved")
|
||||
break
|
||||
}
|
||||
}
|
||||
s.stop <- true
|
||||
s.linkMap = make(map[int]*conn.Link)
|
||||
go s.NewConn()
|
||||
c.Close()
|
||||
s.Close()
|
||||
}
|
||||
func (s *TRPClient) linkProcess(link *conn.Link, c *conn.Conn) {
|
||||
//与目标建立连接
|
||||
server, err := net.DialTimeout(link.ConnType, link.Host, time.Second*3)
|
||||
|
||||
func (s *TRPClient) newUdpConn(rAddr string, md5Password string) {
|
||||
tmpConn, err := common.GetLocalUdpAddr()
|
||||
if err != nil {
|
||||
c.WriteFail(link.Id)
|
||||
lg.Println("connect to ", link.Host, "error:", err)
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
c.WriteSuccess(link.Id)
|
||||
|
||||
link.Conn = conn.NewConn(server)
|
||||
buf := pool.BufPoolCopy.Get().([]byte)
|
||||
localAddr, _ := net.ResolveUDPAddr("udp", tmpConn.LocalAddr().String())
|
||||
localConn, err := net.ListenUDP("udp", localAddr)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
localKcpConn, err := kcp.NewConn(rAddr, nil, 150, 3, localConn)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
conn.SetUdpSession(localKcpConn)
|
||||
localToolConn := conn.NewConn(localKcpConn)
|
||||
//写入密钥、provider身份
|
||||
if _, err := localToolConn.Write([]byte(md5Password)); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
if _, err := localToolConn.Write([]byte(common.WORK_P2P_PROVIDER)); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
//接收服务端传的visitor地址
|
||||
var b []byte
|
||||
if b, err = localToolConn.GetShortLenContent(); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
//向visitor地址发送测试消息
|
||||
visitorAddr, err := net.ResolveUDPAddr("udp", string(b))
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
//向目标IP发送探测包
|
||||
if _, err := localConn.WriteTo([]byte("test"), visitorAddr); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
//给服务端发反馈
|
||||
if _, err := localToolConn.Write([]byte(common.VERIFY_SUCCESS)); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
//关闭与服务端的连接
|
||||
localConn.Close()
|
||||
//关闭与服务端udp conn,建立新的监听
|
||||
if localConn, err = net.ListenUDP("udp", localAddr); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
l, err := kcp.ServeConn(nil, 150, 3, localConn)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
//接收新的监听,得到conn,
|
||||
for {
|
||||
if n, err := server.Read(buf); err != nil {
|
||||
s.tunnel.SendMsg([]byte(common.IO_EOF), link)
|
||||
break
|
||||
} else {
|
||||
if _, err := s.tunnel.SendMsg(buf[:n], link); err != nil {
|
||||
c.Close()
|
||||
break
|
||||
}
|
||||
udpTunnel, err := l.AcceptKCP()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
l.Close()
|
||||
return
|
||||
}
|
||||
}
|
||||
pool.PutBufPoolCopy(buf)
|
||||
s.Lock()
|
||||
delete(s.linkMap, link.Id)
|
||||
s.Unlock()
|
||||
}
|
||||
|
||||
//隧道模式处理
|
||||
func (s *TRPClient) dealChan() {
|
||||
var err error
|
||||
var c net.Conn
|
||||
var sess *kcp.UDPSession
|
||||
if s.bridgeConnType == "tcp" {
|
||||
c, err = net.Dial("tcp", s.svrAddr)
|
||||
} else {
|
||||
sess, err = kcp.DialWithOptions(s.svrAddr, nil, 10, 3)
|
||||
conn.SetUdpSession(sess)
|
||||
c = sess
|
||||
}
|
||||
if err != nil {
|
||||
lg.Println("connect to ", s.svrAddr, "error:", err)
|
||||
return
|
||||
}
|
||||
//验证
|
||||
if _, err := c.Write([]byte(common.Getverifyval(s.vKey))); err != nil {
|
||||
lg.Println("connect to ", s.svrAddr, "error:", err)
|
||||
return
|
||||
}
|
||||
//默认长连接保持
|
||||
s.tunnel = conn.NewConn(c)
|
||||
s.tunnel.SetAlive(s.bridgeConnType)
|
||||
//写标志
|
||||
s.tunnel.WriteChan()
|
||||
|
||||
go func() {
|
||||
for {
|
||||
if id, err := s.tunnel.GetLen(); err != nil {
|
||||
lg.Println("get msg id error")
|
||||
break
|
||||
} else {
|
||||
s.Lock()
|
||||
if v, ok := s.linkMap[id]; ok {
|
||||
s.Unlock()
|
||||
if content, err := s.tunnel.GetMsgContent(v); err != nil {
|
||||
lg.Println("get msg content error:", err, id)
|
||||
pool.PutBufPoolCopy(content)
|
||||
break
|
||||
} else {
|
||||
if len(content) == len(common.IO_EOF) && string(content) == common.IO_EOF {
|
||||
v.Conn.Close()
|
||||
} else if v.Conn != nil {
|
||||
v.Conn.Write(content)
|
||||
}
|
||||
pool.PutBufPoolCopy(content)
|
||||
}
|
||||
} else {
|
||||
s.Unlock()
|
||||
if udpTunnel.RemoteAddr().String() == string(b) {
|
||||
conn.SetUdpSession(udpTunnel)
|
||||
//读取link,设置msgCh 设置msgConn消息回传响应机制
|
||||
l := mux.NewMux(udpTunnel, s.bridgeConnType)
|
||||
for {
|
||||
connMux, err := l.Accept()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
go s.srcProcess(connMux)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//mux tunnel
|
||||
func (s *TRPClient) dealChan() {
|
||||
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)
|
||||
for {
|
||||
src, err := s.tunnel.Accept()
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
s.Close()
|
||||
break
|
||||
}
|
||||
go s.srcProcess(src)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TRPClient) srcProcess(src net.Conn) {
|
||||
lk, err := conn.NewConn(src).GetLinkInfo()
|
||||
if err != nil {
|
||||
src.Close()
|
||||
logs.Error("get connection info from server error ", err)
|
||||
return
|
||||
}
|
||||
//host for target processing
|
||||
lk.Host = common.FormatAddress(lk.Host)
|
||||
//connect to target
|
||||
if targetConn, err := net.Dial(lk.ConnType, lk.Host); err != nil {
|
||||
logs.Warn("connect to %s error %s", lk.Host, err.Error())
|
||||
src.Close()
|
||||
} else {
|
||||
logs.Trace("new %s connection with the goal of %s, remote address:%s", lk.ConnType, lk.Host, lk.RemoteAddr)
|
||||
conn.CopyWaitGroup(src, targetConn, lk.Crypt, lk.Compress, nil, nil, false)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TRPClient) ping() {
|
||||
s.ticker = time.NewTicker(time.Second * 5)
|
||||
loop:
|
||||
for {
|
||||
select {
|
||||
case <-s.ticker.C:
|
||||
if s.tunnel.IsClose {
|
||||
s.Close()
|
||||
s.ticker.Stop()
|
||||
break loop
|
||||
}
|
||||
}
|
||||
}()
|
||||
select {
|
||||
case <-s.stop:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
conn2 "github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"net"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestConfig(t *testing.T) {
|
||||
conn, err := net.Dial("tcp", "127.0.0.1:8284")
|
||||
if err != nil {
|
||||
t.Fail()
|
||||
}
|
||||
c := conn2.NewConn(conn)
|
||||
c.SetAlive("tcp")
|
||||
if _, err := c.Write([]byte(common.Getverifyval("123"))); err != nil {
|
||||
t.Fail()
|
||||
}
|
||||
c.WriteConfig()
|
||||
config := &file.Config{
|
||||
U: "1",
|
||||
P: "2",
|
||||
Compress: "snappy",
|
||||
Crypt: true,
|
||||
CompressEncode: 0,
|
||||
CompressDecode: 0,
|
||||
}
|
||||
host := &file.Host{
|
||||
Host: "a.o.com",
|
||||
Target: "127.0.0.1:8080",
|
||||
HeaderChange: "",
|
||||
HostChange: "",
|
||||
Flow: nil,
|
||||
Client: nil,
|
||||
Remark: "111",
|
||||
NowIndex: 0,
|
||||
TargetArr: nil,
|
||||
NoStore: false,
|
||||
RWMutex: sync.RWMutex{},
|
||||
}
|
||||
tunnel := &file.Tunnel{
|
||||
Port: 9001,
|
||||
Mode: "tcp",
|
||||
Target: "127.0.0.1:8082",
|
||||
Remark: "333",
|
||||
}
|
||||
var b []byte
|
||||
if b, err = c.ReadLen(16); err != nil {
|
||||
t.Fail()
|
||||
}
|
||||
if _, err := c.SendConfigInfo(config); err != nil {
|
||||
t.Fail()
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
t.Fail()
|
||||
}
|
||||
if _, err := c.SendHostInfo(host); err != nil {
|
||||
t.Fail()
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
t.Fail()
|
||||
}
|
||||
if _, err := c.SendTaskInfo(tunnel); err != nil {
|
||||
t.Fail()
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
t.Fail()
|
||||
}
|
||||
c.Close()
|
||||
NewRPClient("127.0.0.1:8284", string(b), "tcp").Start()
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/config"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/version"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
|
||||
"github.com/cnlh/nps/vender/golang.org/x/net/proxy"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func GetTaskStatus(path string) {
|
||||
cnf, err := config.NewConfig(path)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
c, err := NewConn(cnf.CommonConfig.Tp, cnf.CommonConfig.VKey, cnf.CommonConfig.Server, common.WORK_CONFIG, cnf.CommonConfig.ProxyUrl)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
|
||||
if _, err := c.Write([]byte(common.WORK_STATUS)); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
|
||||
//read now vKey and write to server
|
||||
if f, err := common.ReadAllFromFile(filepath.Join(common.GetTmpPath(), "npc_vkey.txt")); err != nil {
|
||||
log.Fatalln(err)
|
||||
} else if _, err := c.Write([]byte(crypt.Md5(string(f)))); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
var isPub bool
|
||||
binary.Read(c, binary.LittleEndian, &isPub)
|
||||
if l, err := c.GetLen(); err != nil {
|
||||
log.Fatalln(err)
|
||||
} else if b, err := c.GetShortContent(l); err != nil {
|
||||
log.Fatalln(err)
|
||||
} else {
|
||||
arr := strings.Split(string(b), common.CONN_DATA_SEQ)
|
||||
for _, v := range cnf.Hosts {
|
||||
if common.InStrArr(arr, v.Remark) {
|
||||
log.Println(v.Remark, "ok")
|
||||
} else {
|
||||
log.Println(v.Remark, "not running")
|
||||
}
|
||||
}
|
||||
for _, v := range cnf.Tasks {
|
||||
ports := common.GetPorts(v.Ports)
|
||||
if v.Mode == "secret" {
|
||||
ports = append(ports, 0)
|
||||
}
|
||||
for _, vv := range ports {
|
||||
var remark string
|
||||
if len(ports) > 1 {
|
||||
remark = v.Remark + "_" + strconv.Itoa(vv)
|
||||
} else {
|
||||
remark = v.Remark
|
||||
}
|
||||
if common.InStrArr(arr, remark) {
|
||||
log.Println(remark, "ok")
|
||||
} else {
|
||||
log.Println(remark, "not running")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
var errAdd = errors.New("The server returned an error, which port or host may have been occupied or not allowed to open.")
|
||||
|
||||
func StartFromFile(path string) {
|
||||
first := true
|
||||
cnf, err := config.NewConfig(path)
|
||||
if err != nil || cnf.CommonConfig == nil {
|
||||
logs.Error("Config file %s loading error", path)
|
||||
os.Exit(0)
|
||||
}
|
||||
logs.Info("Loading configuration file %s successfully", path)
|
||||
|
||||
re:
|
||||
if first || cnf.CommonConfig.AutoReconnection {
|
||||
if !first {
|
||||
logs.Info("Reconnecting...")
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
} else {
|
||||
return
|
||||
}
|
||||
first = false
|
||||
c, err := NewConn(cnf.CommonConfig.Tp, cnf.CommonConfig.VKey, cnf.CommonConfig.Server, common.WORK_CONFIG, cnf.CommonConfig.ProxyUrl)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
goto re
|
||||
}
|
||||
var isPub bool
|
||||
binary.Read(c, binary.LittleEndian, &isPub)
|
||||
|
||||
// get tmp password
|
||||
var b []byte
|
||||
vkey := cnf.CommonConfig.VKey
|
||||
if isPub {
|
||||
// send global configuration to server and get status of config setting
|
||||
if _, err := c.SendConfigInfo(cnf.CommonConfig); err != nil {
|
||||
logs.Error(err)
|
||||
goto re
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
logs.Error(errAdd)
|
||||
goto re
|
||||
}
|
||||
|
||||
if b, err = c.GetShortContent(16); err != nil {
|
||||
logs.Error(err)
|
||||
goto re
|
||||
}
|
||||
vkey = string(b)
|
||||
}
|
||||
ioutil.WriteFile(filepath.Join(common.GetTmpPath(), "npc_vkey.txt"), []byte(vkey), 0600)
|
||||
|
||||
//send hosts to server
|
||||
for _, v := range cnf.Hosts {
|
||||
if _, err := c.SendHostInfo(v); err != nil {
|
||||
logs.Error(err)
|
||||
goto re
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
logs.Error(errAdd, v.Host)
|
||||
goto re
|
||||
}
|
||||
}
|
||||
|
||||
//send task to server
|
||||
for _, v := range cnf.Tasks {
|
||||
if _, err := c.SendTaskInfo(v); err != nil {
|
||||
logs.Error(err)
|
||||
goto re
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
logs.Error(errAdd, v.Ports)
|
||||
goto re
|
||||
}
|
||||
if v.Mode == "file" {
|
||||
//start local file server
|
||||
go startLocalFileServer(cnf.CommonConfig, v, vkey)
|
||||
}
|
||||
}
|
||||
|
||||
//create local server secret or p2p
|
||||
for _, v := range cnf.LocalServer {
|
||||
go StartLocalServer(v, cnf.CommonConfig)
|
||||
}
|
||||
|
||||
c.Close()
|
||||
NewRPClient(cnf.CommonConfig.Server, vkey, cnf.CommonConfig.Tp, cnf.CommonConfig.ProxyUrl, cnf).Start()
|
||||
CloseLocalServer()
|
||||
goto re
|
||||
}
|
||||
|
||||
// Create a new connection with the server and verify it
|
||||
func NewConn(tp string, vkey string, server string, connType string, proxyUrl string) (*conn.Conn, error) {
|
||||
var err error
|
||||
var connection net.Conn
|
||||
var sess *kcp.UDPSession
|
||||
if tp == "tcp" {
|
||||
if proxyUrl != "" {
|
||||
u, er := url.Parse(proxyUrl)
|
||||
if er != nil {
|
||||
return nil, er
|
||||
}
|
||||
n, er := proxy.FromURL(u, nil)
|
||||
if er != nil {
|
||||
return nil, er
|
||||
}
|
||||
connection, err = n.Dial("tcp", server)
|
||||
} else {
|
||||
connection, err = net.Dial("tcp", server)
|
||||
}
|
||||
} else {
|
||||
sess, err = kcp.DialWithOptions(server, nil, 10, 3)
|
||||
conn.SetUdpSession(sess)
|
||||
connection = sess
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := conn.NewConn(connection)
|
||||
if _, err := c.Write([]byte(common.CONN_TEST)); err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
if _, err := c.Write([]byte(crypt.Md5(version.GetVersion()))); err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
if b, err := c.GetShortContent(32); err != nil || crypt.Md5(version.GetVersion()) != string(b) {
|
||||
logs.Error("The client does not match the server version. The current version of the client is", version.GetVersion())
|
||||
os.Exit(0)
|
||||
}
|
||||
if _, err := c.Write([]byte(common.Getverifyval(vkey))); err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
if s, err := c.ReadFlag(); err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
} else if s == common.VERIFY_EER {
|
||||
logs.Error("Validation key %s incorrect", vkey)
|
||||
os.Exit(0)
|
||||
}
|
||||
if _, err := c.Write([]byte(connType)); err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
c.SetAlive(tp)
|
||||
|
||||
return c, nil
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/sheap"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"github.com/pkg/errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var isStart bool
|
||||
var serverConn *conn.Conn
|
||||
|
||||
func heathCheck(healths []*file.Health, c *conn.Conn) bool {
|
||||
serverConn = c
|
||||
if isStart {
|
||||
for _, v := range healths {
|
||||
v.HealthMap = make(map[string]int)
|
||||
}
|
||||
return true
|
||||
}
|
||||
isStart = true
|
||||
h := &sheap.IntHeap{}
|
||||
for _, v := range healths {
|
||||
if v.HealthMaxFail > 0 && v.HealthCheckTimeout > 0 && v.HealthCheckInterval > 0 {
|
||||
v.HealthNextTime = time.Now().Add(time.Duration(v.HealthCheckInterval) * time.Second)
|
||||
heap.Push(h, v.HealthNextTime.Unix())
|
||||
v.HealthMap = make(map[string]int)
|
||||
}
|
||||
}
|
||||
go session(healths, h)
|
||||
return true
|
||||
}
|
||||
|
||||
func session(healths []*file.Health, h *sheap.IntHeap) {
|
||||
for {
|
||||
if h.Len() == 0 {
|
||||
logs.Error("health check error")
|
||||
break
|
||||
}
|
||||
rs := heap.Pop(h).(int64) - time.Now().Unix()
|
||||
if rs <= 0 {
|
||||
continue
|
||||
}
|
||||
timer := time.NewTimer(time.Duration(rs) * time.Second)
|
||||
select {
|
||||
case <-timer.C:
|
||||
for _, v := range healths {
|
||||
if v.HealthNextTime.Before(time.Now()) {
|
||||
v.HealthNextTime = time.Now().Add(time.Duration(v.HealthCheckInterval) * time.Second)
|
||||
//check
|
||||
go check(v)
|
||||
//reset time
|
||||
heap.Push(h, v.HealthNextTime.Unix())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//只针对一个端口 面向多个目标的情况
|
||||
func check(t *file.Health) {
|
||||
arr := strings.Split(t.HealthCheckTarget, ",")
|
||||
var err error
|
||||
var rs *http.Response
|
||||
for _, v := range arr {
|
||||
if t.HealthCheckType == "tcp" {
|
||||
_, err = net.DialTimeout("tcp", v, time.Duration(t.HealthCheckTimeout)*time.Second);
|
||||
} else {
|
||||
client := &http.Client{}
|
||||
client.Timeout = time.Duration(t.HealthCheckTimeout) * time.Second
|
||||
rs, err = client.Get("http://" + v + t.HttpHealthUrl)
|
||||
if err == nil && rs.StatusCode != 200 {
|
||||
err = errors.New("status code is not match")
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
t.HealthMap[v] += 1
|
||||
} else if t.HealthMap[v] >= t.HealthMaxFail {
|
||||
//send recovery add
|
||||
serverConn.SendHealthInfo(v, "1")
|
||||
t.HealthMap[v] = 0
|
||||
}
|
||||
|
||||
if t.HealthMap[v] == t.HealthMaxFail {
|
||||
//send fail remove
|
||||
serverConn.SendHealthInfo(v, "0")
|
||||
}
|
||||
}
|
||||
}
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/config"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/mux"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var LocalServer []*net.TCPListener
|
||||
var udpConn net.Conn
|
||||
var muxSession *mux.Mux
|
||||
var fileServer []*http.Server
|
||||
|
||||
func CloseLocalServer() {
|
||||
for _, v := range LocalServer {
|
||||
v.Close()
|
||||
}
|
||||
for _, v := range fileServer {
|
||||
v.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func startLocalFileServer(config *config.CommonConfig, t *file.Tunnel, vkey string) {
|
||||
remoteConn, err := NewConn(config.Tp, vkey, config.Server, common.WORK_FILE, config.ProxyUrl)
|
||||
if err != nil {
|
||||
logs.Error("Local connection server failed ", err.Error())
|
||||
return
|
||||
}
|
||||
srv := &http.Server{
|
||||
Handler: http.StripPrefix(t.StripPre, http.FileServer(http.Dir(t.LocalPath))),
|
||||
}
|
||||
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)
|
||||
logs.Warn(srv.Serve(listener))
|
||||
}
|
||||
|
||||
func StartLocalServer(l *config.LocalServer, config *config.CommonConfig) error {
|
||||
listener, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), l.Port, ""})
|
||||
if err != nil {
|
||||
logs.Error("local listener startup failed port %d, error %s", l.Port, err.Error())
|
||||
return err
|
||||
}
|
||||
LocalServer = append(LocalServer, listener)
|
||||
logs.Info("successful start-up of local monitoring, port", l.Port)
|
||||
for {
|
||||
c, err := listener.AcceptTCP()
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "use of closed network connection") {
|
||||
break
|
||||
}
|
||||
logs.Info(err)
|
||||
continue
|
||||
}
|
||||
if l.Type == "secret" {
|
||||
go processSecret(c, config, l)
|
||||
} else {
|
||||
go processP2P(c, config, l)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func processSecret(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
|
||||
remoteConn, err := NewConn(config.Tp, config.VKey, config.Server, common.WORK_SECRET, config.ProxyUrl)
|
||||
if err != nil {
|
||||
logs.Error("Local connection server failed ", err.Error())
|
||||
return
|
||||
}
|
||||
if _, err := remoteConn.Write([]byte(crypt.Md5(l.Password))); err != nil {
|
||||
logs.Error("Local connection server failed ", err.Error())
|
||||
return
|
||||
}
|
||||
conn.CopyWaitGroup(remoteConn.Conn, localTcpConn, false, false, nil, nil, false)
|
||||
}
|
||||
|
||||
func processP2P(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
|
||||
if udpConn == nil {
|
||||
newUdpConn(config, l)
|
||||
if udpConn == nil {
|
||||
return
|
||||
}
|
||||
muxSession = mux.NewMux(udpConn, "kcp")
|
||||
}
|
||||
nowConn, err := muxSession.NewConn()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
link := conn.NewLink(common.CONN_TCP, l.Target, config.Cnf.Crypt, config.Cnf.Compress, localTcpConn.LocalAddr().String())
|
||||
if _, err := conn.NewConn(nowConn).SendLinkInfo(link); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
conn.CopyWaitGroup(nowConn, localTcpConn, config.Cnf.Crypt, config.Cnf.Compress, nil, nil, false)
|
||||
}
|
||||
|
||||
func newUdpConn(config *config.CommonConfig, l *config.LocalServer) {
|
||||
remoteConn, err := NewConn(config.Tp, config.VKey, config.Server, common.WORK_P2P, config.ProxyUrl)
|
||||
if err != nil {
|
||||
logs.Error("Local connection server failed ", err.Error())
|
||||
return
|
||||
}
|
||||
if _, err := remoteConn.Write([]byte(crypt.Md5(l.Password))); err != nil {
|
||||
logs.Error("Local connection server failed ", err.Error())
|
||||
return
|
||||
}
|
||||
var rAddr []byte
|
||||
//读取服务端地址、密钥 继续做处理
|
||||
if rAddr, err = remoteConn.GetShortLenContent(); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
//与服务端udp建立连接
|
||||
tmpConn, err := common.GetLocalUdpAddr()
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
return
|
||||
}
|
||||
//与服务端建立udp连接
|
||||
localAddr, _ := net.ResolveUDPAddr("udp", tmpConn.LocalAddr().String())
|
||||
localConn, err := net.ListenUDP("udp", localAddr)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
localKcpConn, err := kcp.NewConn(string(rAddr), nil, 150, 3, localConn)
|
||||
conn.SetUdpSession(localKcpConn)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
//写入密钥、provider身份
|
||||
if _, err := localKcpConn.Write([]byte(crypt.Md5(l.Password))); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
if _, err := localKcpConn.Write([]byte(common.WORK_P2P_VISITOR)); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
//接收服务端传的visitor地址
|
||||
if b, err := conn.NewConn(localKcpConn).GetShortLenContent(); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
} else {
|
||||
//关闭与服务端连接
|
||||
localConn.Close()
|
||||
//建立新的连接
|
||||
localConn, err = net.ListenUDP("udp", localAddr)
|
||||
udpTunnel, err := kcp.NewConn(string(b), nil, 150, 3, localConn)
|
||||
if err != nil || udpTunnel == nil {
|
||||
logs.Warn(err)
|
||||
return
|
||||
}
|
||||
conn.SetUdpSession(udpTunnel)
|
||||
udpConn = udpTunnel
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
func RegisterLocalIp(server string, vKey string, tp string, proxyUrl string, hour int) {
|
||||
c, err := NewConn(tp, vKey, server, common.WORK_REGISTER, proxyUrl)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if err := binary.Write(c, binary.LittleEndian, int32(hour)); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
log.Printf("Successful ip registration for local public network, the validity period is %d hours.", hour)
|
||||
os.Exit(0)
|
||||
}
|
||||
+47
-16
@@ -3,33 +3,64 @@ package main
|
||||
import (
|
||||
"flag"
|
||||
"github.com/cnlh/nps/client"
|
||||
"github.com/cnlh/nps/lib/daemon"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/daemon"
|
||||
"github.com/cnlh/nps/lib/version"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const VERSION = "v0.0.13"
|
||||
|
||||
var (
|
||||
serverAddr = flag.String("server", "", "服务器地址ip:端口")
|
||||
verifyKey = flag.String("vkey", "", "验证密钥")
|
||||
logType = flag.String("log", "stdout", "日志输出方式(stdout|file)")
|
||||
connType = flag.String("type", "tcp", "与服务端建立连接方式(kcp|tcp)")
|
||||
serverAddr = flag.String("server", "", "Server addr (ip:port)")
|
||||
configPath = flag.String("config", "", "Configuration file path")
|
||||
verifyKey = flag.String("vkey", "", "Authentication key")
|
||||
logType = flag.String("log", "stdout", "Log output mode(stdout|file)")
|
||||
connType = flag.String("type", "tcp", "Connection type with the server(kcp|tcp)")
|
||||
proxyUrl = flag.String("proxy", "", "proxy socks5 url(eg:socks5://111:222@127.0.0.1:9007)")
|
||||
logLevel = flag.String("log_level", "7", "log level 0~7")
|
||||
registerTime = flag.Int("time", 2, "register time long /h")
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
daemon.InitDaemon("npc", common.GetRunPath(), common.GetPidPath())
|
||||
if len(os.Args) > 2 {
|
||||
switch os.Args[1] {
|
||||
case "status":
|
||||
path := strings.Replace(os.Args[2], "-config=", "", -1)
|
||||
client.GetTaskStatus(path)
|
||||
case "register":
|
||||
flag.CommandLine.Parse(os.Args[2:])
|
||||
client.RegisterLocalIp(*serverAddr, *verifyKey, *connType, *proxyUrl, *registerTime)
|
||||
}
|
||||
}
|
||||
daemon.InitDaemon("npc", common.GetRunPath(), common.GetTmpPath())
|
||||
logs.EnableFuncCallDepth(true)
|
||||
logs.SetLogFuncCallDepth(3)
|
||||
if *logType == "stdout" {
|
||||
lg.InitLogFile("npc", true, common.GetLogPath())
|
||||
logs.SetLogger(logs.AdapterConsole, `{"level":`+*logLevel+`,"color":true}`)
|
||||
} else {
|
||||
lg.InitLogFile("npc", false, common.GetLogPath())
|
||||
logs.SetLogger(logs.AdapterFile, `{"level":`+*logLevel+`,"filename":"npc_log.log"}`)
|
||||
}
|
||||
stop := make(chan int)
|
||||
for _, v := range strings.Split(*verifyKey, ",") {
|
||||
lg.Println("客户端启动,连接:", *serverAddr, " 验证令牌:", v)
|
||||
go client.NewRPClient(*serverAddr, v, *connType).Start()
|
||||
env := common.GetEnvMap()
|
||||
if *serverAddr == "" {
|
||||
*serverAddr, _ = env["NPC_SERVER_ADDR"]
|
||||
}
|
||||
if *verifyKey == "" {
|
||||
*verifyKey, _ = env["NPC_SERVER_VKEY"]
|
||||
}
|
||||
logs.Info("the version of client is %s", version.VERSION)
|
||||
if *verifyKey != "" && *serverAddr != "" && *configPath == "" {
|
||||
for {
|
||||
client.NewRPClient(*serverAddr, *verifyKey, *connType, *proxyUrl, nil).Start()
|
||||
logs.Info("It will be reconnected in five seconds")
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
} else {
|
||||
if *configPath == "" {
|
||||
*configPath = "npc.conf"
|
||||
}
|
||||
client.StartFromFile(*configPath)
|
||||
}
|
||||
<-stop
|
||||
}
|
||||
|
||||
+26
-58
@@ -2,95 +2,63 @@ package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"github.com/cnlh/nps/lib/beego"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/daemon"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/install"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/lib/version"
|
||||
"github.com/cnlh/nps/server"
|
||||
"github.com/cnlh/nps/server/connection"
|
||||
"github.com/cnlh/nps/server/test"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
_ "github.com/cnlh/nps/web/routers"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const VERSION = "v0.0.13"
|
||||
|
||||
var (
|
||||
TcpPort = flag.Int("tcpport", 0, "客户端与服务端通信端口")
|
||||
httpPort = flag.Int("httpport", 8024, "对外监听的端口")
|
||||
rpMode = flag.String("mode", "webServer", "启动模式")
|
||||
tunnelTarget = flag.String("target", "127.0.0.1:80", "远程目标")
|
||||
VerifyKey = flag.String("vkey", "", "验证密钥")
|
||||
u = flag.String("u", "", "验证用户名(socks5和web)")
|
||||
p = flag.String("p", "", "验证密码(socks5和web)")
|
||||
compress = flag.String("compress", "", "数据压缩方式(snappy)")
|
||||
crypt = flag.String("crypt", "false", "是否加密(true|false)")
|
||||
logType = flag.String("log", "stdout", "日志输出方式(stdout|file)")
|
||||
level string
|
||||
logType = flag.String("log", "stdout", "Log output mode(stdout|file)")
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
beego.LoadAppConfig("ini", filepath.Join(common.GetRunPath(), "conf", "nps.conf"))
|
||||
if len(os.Args) > 1 {
|
||||
switch os.Args[1] {
|
||||
case "test":
|
||||
server.TestServerConfig()
|
||||
test.TestServerConfig()
|
||||
log.Println("test ok, no error")
|
||||
return
|
||||
case "start", "restart", "stop", "status":
|
||||
daemon.InitDaemon("nps", common.GetRunPath(), common.GetPidPath())
|
||||
daemon.InitDaemon("nps", common.GetRunPath(), common.GetTmpPath())
|
||||
case "install":
|
||||
install.InstallNps()
|
||||
return
|
||||
}
|
||||
}
|
||||
if level = beego.AppConfig.String("log_level"); level == "" {
|
||||
level = "7"
|
||||
}
|
||||
logs.Reset()
|
||||
logs.EnableFuncCallDepth(true)
|
||||
logs.SetLogFuncCallDepth(3)
|
||||
if *logType == "stdout" {
|
||||
lg.InitLogFile("nps", true, common.GetLogPath())
|
||||
logs.SetLogger(logs.AdapterConsole, `{"level":`+level+`,"color":true}`)
|
||||
} else {
|
||||
lg.InitLogFile("nps", false, common.GetLogPath())
|
||||
logs.SetLogger(logs.AdapterFile, `{"level":`+level+`,"filename":"nps_log.log"}`)
|
||||
}
|
||||
task := &file.Tunnel{
|
||||
TcpPort: *httpPort,
|
||||
Mode: *rpMode,
|
||||
Target: *tunnelTarget,
|
||||
Config: &file.Config{
|
||||
U: *u,
|
||||
P: *p,
|
||||
Compress: *compress,
|
||||
Crypt: common.GetBoolByStr(*crypt),
|
||||
},
|
||||
Flow: &file.Flow{},
|
||||
UseClientCnf: false,
|
||||
Mode: "webServer",
|
||||
}
|
||||
if *VerifyKey != "" {
|
||||
c := &file.Client{
|
||||
Id: 0,
|
||||
VerifyKey: *VerifyKey,
|
||||
Addr: "",
|
||||
Remark: "",
|
||||
Status: true,
|
||||
IsConnect: false,
|
||||
Cnf: &file.Config{},
|
||||
Flow: &file.Flow{},
|
||||
}
|
||||
c.Cnf.CompressDecode, c.Cnf.CompressEncode = common.GetCompressType(c.Cnf.Compress)
|
||||
file.GetCsvDb().Clients[0] = c
|
||||
task.Client = c
|
||||
bridgePort, err := beego.AppConfig.Int("bridge_port")
|
||||
if err != nil {
|
||||
logs.Error("Getting bridge_port error", err)
|
||||
os.Exit(0)
|
||||
}
|
||||
if *TcpPort == 0 {
|
||||
p, err := beego.AppConfig.Int("bridgePort")
|
||||
if err == nil && *rpMode == "webServer" {
|
||||
*TcpPort = p
|
||||
} else {
|
||||
*TcpPort = 8284
|
||||
}
|
||||
}
|
||||
lg.Printf("服务端启动,监听%s服务端口:%d", beego.AppConfig.String("bridgeType"), *TcpPort)
|
||||
task.Config.CompressDecode, task.Config.CompressEncode = common.GetCompressType(task.Config.Compress)
|
||||
if *rpMode != "webServer" {
|
||||
file.GetCsvDb().Tasks[0] = task
|
||||
}
|
||||
beego.LoadAppConfig("ini", filepath.Join(common.GetRunPath(), "conf", "app.conf"))
|
||||
server.StartNewServer(*TcpPort, task, beego.AppConfig.String("bridgeType"))
|
||||
logs.Info("the version of server is %s ,allow client version to be %s", version.VERSION, version.GetVersion())
|
||||
connection.InitConnectionService()
|
||||
server.StartNewServer(bridgePort, task, beego.AppConfig.String("bridge_type"))
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
appname = nps
|
||||
|
||||
#Web Management Port
|
||||
httpport = 8080
|
||||
|
||||
#Boot mode(dev|pro)
|
||||
runmode = dev
|
||||
|
||||
#Web Management Password
|
||||
password=123
|
||||
|
||||
##Communication Port between Client and Server
|
||||
##If the data transfer mode is tcp, it is TCP port
|
||||
##If the data transfer mode is kcp, it is UDP port
|
||||
bridgePort=8284
|
||||
|
||||
#Web API unauthenticated IP address
|
||||
authip=127.0.0.1
|
||||
|
||||
##HTTP proxy port, no startup if empty
|
||||
httpProxyPort=80
|
||||
|
||||
##HTTPS proxy port, no startup if empty
|
||||
httpsProxyPort=
|
||||
|
||||
##certFile absolute path
|
||||
pemPath=/etc/nginx/certificate.crt
|
||||
|
||||
##KeyFile absolute path
|
||||
keyPath=/etc/nginx/private.key
|
||||
|
||||
##Data transmission mode(kcp or tcp)
|
||||
bridgeType=tcp
|
||||
+2
-1
@@ -1 +1,2 @@
|
||||
1,ydiigrm4ghu7mym1,测试,true,,,0,,0,0
|
||||
2,corjmrbhr33otit1,,true,,,0,false,0,0,0
|
||||
5,2dyy78gj7b9zw09l,,true,,,1,false,0,0,0
|
||||
|
||||
|
+3
-2
@@ -1,2 +1,3 @@
|
||||
a.o.com,127.0.0.1:8080,1,,,测试
|
||||
b.o.com,127.0.0.1:8082,1,,,
|
||||
c.o.com,10.1.50.196:4000,5,,,,/,2,7543392,22379,all
|
||||
a.o.com,127.0.0.1:8080,2,,,,/,3,0,0,all
|
||||
b.o.com,127.0.0.1:8082,5,,,,/,4,0,0,all
|
||||
|
||||
|
@@ -0,0 +1,65 @@
|
||||
[common]
|
||||
server=127.0.0.1:8024
|
||||
tp=tcp
|
||||
vkey=2dyy78gj7b9zw09l
|
||||
auto_reconnection=true
|
||||
[web]
|
||||
host=b.o.com
|
||||
target=10.1.50.203:80
|
||||
|
||||
[health_check_test1]
|
||||
health_check_timeout=1
|
||||
health_check_max_failed=3
|
||||
health_check_interval=1
|
||||
health_http_url=/
|
||||
health_check_type=http
|
||||
health_check_target=127.0.0.1:8083,127.0.0.1:8082
|
||||
|
||||
[health_check_test2]
|
||||
health_check_timeout=1
|
||||
health_check_max_failed=3
|
||||
health_check_interval=1
|
||||
health_check_type=tcp
|
||||
health_check_target=127.0.0.1:8083,127.0.0.1:8082
|
||||
|
||||
|
||||
[tcp]
|
||||
mode=tcp
|
||||
target=127.0.0.1:8083,127.0.0.1:8082
|
||||
port=9006
|
||||
targetAddr=123.206.77.88
|
||||
|
||||
[socks5]
|
||||
mode=socks5
|
||||
port=9005
|
||||
|
||||
[http]
|
||||
mode=httpProxy
|
||||
port=9004
|
||||
|
||||
|
||||
[file]
|
||||
mode=file
|
||||
port=9100
|
||||
local_path=./
|
||||
strip_pre=/web/
|
||||
|
||||
[s_ssh]
|
||||
mode=secret
|
||||
password=1234
|
||||
target=123.206.77.88:22
|
||||
|
||||
[udp]
|
||||
mode=udp
|
||||
port=53
|
||||
target=114.114.114.114:53
|
||||
|
||||
[p2p_ssh]
|
||||
port=2001
|
||||
password=p2pssh
|
||||
target=123.206.77.88:22
|
||||
|
||||
|
||||
[secret_ssh]
|
||||
port=2002
|
||||
password=1234
|
||||
Executable
+49
@@ -0,0 +1,49 @@
|
||||
appname = nps
|
||||
#Boot mode(dev|pro)
|
||||
runmode = dev
|
||||
|
||||
|
||||
|
||||
#HTTP(S) proxy port, no startup if empty
|
||||
http_proxy_port=80
|
||||
#https_proxy_port=443
|
||||
https_just_proxy=true
|
||||
#certFile absolute path
|
||||
pem_path=conf/server.pem
|
||||
#KeyFile absolute path
|
||||
key_path=conf/server.key
|
||||
|
||||
##bridge
|
||||
bridge_type=tcp
|
||||
bridge_port=8024
|
||||
bridge_ip=0.0.0.0
|
||||
|
||||
# Public password, which clients can use to connect to the server
|
||||
# After the connection, the server will be able to open relevant ports and parse related domain names according to its own configuration file.
|
||||
public_vkey=123
|
||||
|
||||
#Traffic data persistence interval(minute)
|
||||
#Ignorance means no persistence
|
||||
#flow_store_interval=1
|
||||
|
||||
# log level LevelEmergency->0 LevelAlert->1 LevelCritical->2 LevelError->3 LevelWarning->4 LevelNotice->5 LevelInformational->6 LevelDebug->7
|
||||
log_level=7
|
||||
|
||||
#Whether to restrict IP access, true or false or ignore
|
||||
#ip_limit=true
|
||||
|
||||
#p2p
|
||||
#p2p_ip=127.0.0.1
|
||||
#p2p_port=6000
|
||||
|
||||
#web
|
||||
web_host=a.o.com
|
||||
web_username=admin
|
||||
web_password=123
|
||||
web_port = 8080
|
||||
web_ip=0.0.0.0
|
||||
#Web API unauthenticated IP address
|
||||
auth_key=test
|
||||
auth_crypt_key =1234567812345678
|
||||
|
||||
#allow_ports=9001-9009,10001,11000-12000
|
||||
@@ -0,0 +1,27 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEpAIBAAKCAQEA2MVLOHvgU8FCp6LgQrPfaWcGygrsRk7TL9hbT8MxbCRUSLV7
|
||||
Lbt3q5Knz8eTN4NWmwE6L5glOcH2x3Hnn+hPjbvgq35XBBIccAm0cYYKqoKkikeK
|
||||
FZM0Gp/WhSrhJ4laTyQqyleIFKpwD9kHDiC/sxjGDhSFmHKhhAnsQIRm2tppFXX0
|
||||
aAMqJEm88jzk1BN2QtKjEAn1u8v1+QW1KP3WuzdXH4L7hhMll66/KIm6Hfs2FRHQ
|
||||
pRUWqZeJY4q79NW5p5f+siGwOsGpxb/p11pM+0xnCH3UIFbm3zCTzP4sLvkfFGAe
|
||||
yAHsAwmaP8dJxh40ej3NN8uNiNvt8nw2Vb/1LwIDAQABAoIBAD40x/RKoEKIyE8B
|
||||
D6g0pB1EQo+CePFoN3SYewO1uR4WgtVmtxWVoa7r5BpdZGLe3uCWhpMX7z7W6bGs
|
||||
f1LFQOckjkHIfMIfTGfecRjO5Yqu+Pbxtq+gUah+S/plJr3IzdC+SUVNvzBnBMeX
|
||||
eU3Vmg2UQ2nQ+9GWu8D/c/vDwxx0X8oQ2G8QaxX0tUurlSMNA3M7xySwEvhx54fO
|
||||
UrDF3Q4yF48eA4butxVLFWf3cnlY+nR8uYd2vKfmp689/8C6kkfoM9igB78e93sm
|
||||
uDM2eRLm4kU5WLl301T42n6AF7w8J0MhLLVOIeLs4l5gZPa3uKvYFmuHQao7e/5R
|
||||
U/jHKrECgYEA8alPXuxFSVOvdhIsSN//Frj9CdExVdYmaLkt/2LO4FMnOaWh1xh7
|
||||
5iCY1bJT8D9dhfbqRg3qW2oguZD8gu04R8fTRegQ89qmAIwsEYqVf9salR41lZU4
|
||||
Rc+5yc7O11WIe9Lzu+ONFBFkAh3UFMR4zVZ/JhKIG/P5Srm7SUdKW2cCgYEA5aHo
|
||||
x2LR+yKhjkrBzHG3Qrfy1PtlYHjOpYYAKHQcBFuiG08W3CK/vkYl+mhv0uyhT7mn
|
||||
q6NDqrpZPRnDlOoEqgRS1X/QWKN6Pgd4HNLIawvp0vK9jYXDPcAXFzVthXCIwFcn
|
||||
3a3m4cHiuLdRNOHkydiHQyTOF6eEneN07TDvwvkCgYEApzOd1u9igPmFzQuF2GYi
|
||||
+HXFnaU/nUQuDwcQ7EJRIKRn31raPxiRoQesty5LJU6yRp4wOYgnPliPi9Tk4TGA
|
||||
XynC4/tMv2vorzhMxVY9Wdke602bhYNZC/RNd3O/aP2lEQdD3Bv04I2nxE8fDb9i
|
||||
VbAjCRSJV83WDf2zt1+78sECgYEAzezjRiKdcZu9y0/I+WEk2cUCE/MaF2he0FsZ
|
||||
uy1cjp/qAJltQ5452xUnK6cKWNlxU4CHF0mC/hC8xCldliZCZoEYE3PaUBLSJdwm
|
||||
35o6tpxpZI3gZJCG5NJlIp/8BkVDrVC7ZHV17hAkFEf4n/bPaB8wNYtE8jt8luaK
|
||||
TcarzGkCgYBn2alN0RLN2PHDurraFZB6GuCvh/arEjSCY3SDFQPF10CVjTDV7sx3
|
||||
eqJkwJ81syTmfJwZIceWbOFGgsuSx37UrQAVlHZSvzeqEg9dA5HqSoOACyidJI7j
|
||||
RG2+HB+KpsIZjGgLrEM4i7VOpYUDRdaouIXngFq/t9HNT+MDck5/Lw==
|
||||
-----END RSA PRIVATE KEY-----
|
||||
@@ -0,0 +1,22 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDtTCCAp2gAwIBAgIJAPXRSiP0Fs7sMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV
|
||||
BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX
|
||||
aWRnaXRzIFB0eSBMdGQwHhcNMTcxMTA3MDg1MzQ2WhcNMjcxMTA1MDg1MzQ2WjBF
|
||||
MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50
|
||||
ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
|
||||
CgKCAQEA2MVLOHvgU8FCp6LgQrPfaWcGygrsRk7TL9hbT8MxbCRUSLV7Lbt3q5Kn
|
||||
z8eTN4NWmwE6L5glOcH2x3Hnn+hPjbvgq35XBBIccAm0cYYKqoKkikeKFZM0Gp/W
|
||||
hSrhJ4laTyQqyleIFKpwD9kHDiC/sxjGDhSFmHKhhAnsQIRm2tppFXX0aAMqJEm8
|
||||
8jzk1BN2QtKjEAn1u8v1+QW1KP3WuzdXH4L7hhMll66/KIm6Hfs2FRHQpRUWqZeJ
|
||||
Y4q79NW5p5f+siGwOsGpxb/p11pM+0xnCH3UIFbm3zCTzP4sLvkfFGAeyAHsAwma
|
||||
P8dJxh40ej3NN8uNiNvt8nw2Vb/1LwIDAQABo4GnMIGkMB0GA1UdDgQWBBQdPc0R
|
||||
a8alY6Ab7voidkTGaH4PxzB1BgNVHSMEbjBsgBQdPc0Ra8alY6Ab7voidkTGaH4P
|
||||
x6FJpEcwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNV
|
||||
BAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJAPXRSiP0Fs7sMAwGA1UdEwQF
|
||||
MAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAH1IZNkjuvt2nZPzXsuiVNyCE1vm346z
|
||||
naE0Uzt3aseAN9m/iiB8mLz+ryvWc2aFMX5lTdsHdm2rqmqBCBXeRwTLf4OeHIju
|
||||
ZQW6makWt6PxANEo6gbdPbQXbS420ssUhnR2irIH1SdI31iikVFPdiS0baRRE/gS
|
||||
+440M1jOOOnKm0Qin92ejsshmji/0qaD2+6D5TNw4HmIZaFTBw+kfjxCL6trfeBn
|
||||
4fT0RJ121V3G3+AtG5sWQ93B3pCg+jtD+fGKkNSLhphq84bD1Zv7l73QGOoylkEn
|
||||
Sc0ajTLOXFBb83yRdlgV3Da95jH9rDZ4jSod48m+KemoZTDQw0vSwAU=
|
||||
-----END CERTIFICATE-----
|
||||
+5
-4
@@ -1,4 +1,5 @@
|
||||
53,udpServer,114.114.114.114:53,,,,1,0,0,0,2,1,true,udp
|
||||
9005,httpProxyServer,,,,,1,0,0,0,4,1,true,
|
||||
9002,socks5Server,,,,,1,0,0,0,3,1,true,socks5
|
||||
9001,tunnelServer,127.0.0.1:8082,,,,1,0,0,0,1,1,true,测试tcp
|
||||
8025,socks5,,1,1,2,,0,0,
|
||||
8026,httpProxy,,1,2,2,,0,0,
|
||||
9002,tcp,127.0.0.1:8082,1,3,2,,0,0,
|
||||
9003,socks5,,1,5,5,,0,0,
|
||||
9009,tcp,127.0.0.1:8082,1,21,5,,8244480,2382592,
|
||||
|
||||
|
Binary file not shown.
|
Before Width: | Height: | Size: 334 KiB After Width: | Height: | Size: 290 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 281 KiB After Width: | Height: | Size: 232 KiB |
+15
-9
@@ -1,27 +1,33 @@
|
||||
package common
|
||||
|
||||
const (
|
||||
COMPRESS_NONE_ENCODE = iota
|
||||
COMPRESS_NONE_DECODE
|
||||
COMPRESS_SNAPY_ENCODE
|
||||
COMPRESS_SNAPY_DECODE
|
||||
CONN_DATA_SEQ = "*#*" //Separator
|
||||
VERIFY_EER = "vkey"
|
||||
VERIFY_SUCCESS = "sucs"
|
||||
WORK_MAIN = "main"
|
||||
WORK_CHAN = "chan"
|
||||
RES_SIGN = "sign"
|
||||
WORK_CONFIG = "conf"
|
||||
WORK_REGISTER = "rgst"
|
||||
WORK_SECRET = "sert"
|
||||
WORK_FILE = "file"
|
||||
WORK_P2P = "p2pm"
|
||||
WORK_P2P_VISITOR = "p2pv"
|
||||
WORK_P2P_PROVIDER = "p2pp"
|
||||
WORK_STATUS = "stus"
|
||||
RES_MSG = "msg0"
|
||||
RES_CLOSE = "clse"
|
||||
NEW_CONN = "conn" //新连接标志
|
||||
NEW_TASK = "task" //新连接标志
|
||||
CONN_SUCCESS = "sucs"
|
||||
NEW_UDP_CONN = "udpc" //p2p udp conn
|
||||
NEW_TASK = "task"
|
||||
NEW_CONF = "conf"
|
||||
NEW_HOST = "host"
|
||||
CONN_TCP = "tcp"
|
||||
CONN_UDP = "udp"
|
||||
CONN_TEST = "TST"
|
||||
UnauthorizedBytes = `HTTP/1.1 401 Unauthorized
|
||||
Content-Type: text/plain; charset=utf-8
|
||||
WWW-Authenticate: Basic realm="easyProxy"
|
||||
|
||||
401 Unauthorized`
|
||||
IO_EOF = "PROXYEOF"
|
||||
ConnectionFailBytes = `HTTP/1.1 404 Not Found
|
||||
|
||||
`
|
||||
|
||||
+4
-4
@@ -12,7 +12,7 @@ import (
|
||||
func GetRunPath() string {
|
||||
var path string
|
||||
if path = GetInstallPath(); !FileExists(path) {
|
||||
return "./"
|
||||
return GetAppPath()
|
||||
}
|
||||
return path
|
||||
}
|
||||
@@ -48,7 +48,7 @@ func IsWindows() bool {
|
||||
func GetLogPath() string {
|
||||
var path string
|
||||
if IsWindows() {
|
||||
path = "./"
|
||||
path = GetAppPath()
|
||||
} else {
|
||||
path = "/tmp"
|
||||
}
|
||||
@@ -56,10 +56,10 @@ func GetLogPath() string {
|
||||
}
|
||||
|
||||
//interface pid file path
|
||||
func GetPidPath() string {
|
||||
func GetTmpPath() string {
|
||||
var path string
|
||||
if IsWindows() {
|
||||
path = "./"
|
||||
path = GetAppPath()
|
||||
} else {
|
||||
path = "/tmp"
|
||||
}
|
||||
|
||||
+189
-19
@@ -5,7 +5,9 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"html/template"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
@@ -15,19 +17,6 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
//Judging Compression Mode
|
||||
func GetCompressType(compress string) (int, int) {
|
||||
switch compress {
|
||||
case "":
|
||||
return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
|
||||
case "snappy":
|
||||
return COMPRESS_SNAPY_DECODE, COMPRESS_SNAPY_ENCODE
|
||||
default:
|
||||
lg.Fatalln("数据压缩格式错误")
|
||||
}
|
||||
return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
|
||||
}
|
||||
|
||||
//Get the corresponding IP address through domain name
|
||||
func GetHostByName(hostname string) string {
|
||||
if !DomainCheck(hostname) {
|
||||
@@ -94,7 +83,7 @@ func GetStrByBool(b bool) string {
|
||||
|
||||
//int
|
||||
func GetIntNoErrByStr(str string) int {
|
||||
i, _ := strconv.Atoi(str)
|
||||
i, _ := strconv.Atoi(strings.TrimSpace(str))
|
||||
return i
|
||||
}
|
||||
|
||||
@@ -144,7 +133,11 @@ func FileExists(name string) bool {
|
||||
//Judge whether the TCP port can open normally
|
||||
func TestTcpPort(port int) bool {
|
||||
l, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), port, ""})
|
||||
defer l.Close()
|
||||
defer func() {
|
||||
if l != nil {
|
||||
l.Close()
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
@@ -154,7 +147,11 @@ func TestTcpPort(port int) bool {
|
||||
//Judge whether the UDP port can open normally
|
||||
func TestUdpPort(port int) bool {
|
||||
l, err := net.ListenUDP("udp", &net.UDPAddr{net.ParseIP("0.0.0.0"), port, ""})
|
||||
defer l.Close()
|
||||
defer func() {
|
||||
if l != nil {
|
||||
l.Close()
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
@@ -168,9 +165,182 @@ func BinaryWrite(raw *bytes.Buffer, v ...string) {
|
||||
buffer := new(bytes.Buffer)
|
||||
var l int32
|
||||
for _, v := range v {
|
||||
l += int32(len([]byte(v))) + int32(len([]byte("#")))
|
||||
l += int32(len([]byte(v))) + int32(len([]byte(CONN_DATA_SEQ)))
|
||||
binary.Write(buffer, binary.LittleEndian, []byte(v))
|
||||
binary.Write(buffer, binary.LittleEndian, []byte("#"))
|
||||
binary.Write(buffer, binary.LittleEndian, []byte(CONN_DATA_SEQ))
|
||||
}
|
||||
binary.Write(raw, binary.LittleEndian, l)
|
||||
binary.Write(raw, binary.LittleEndian, buffer.Bytes())
|
||||
}
|
||||
|
||||
//inArray str interface
|
||||
func InStrArr(arr []string, val string) bool {
|
||||
for _, v := range arr {
|
||||
if v == val {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//inArray int interface
|
||||
func InIntArr(arr []int, val int) bool {
|
||||
for _, v := range arr {
|
||||
if v == val {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//format ports str to a int array
|
||||
func GetPorts(p string) []int {
|
||||
var ps []int
|
||||
arr := strings.Split(p, ",")
|
||||
for _, v := range arr {
|
||||
fw := strings.Split(v, "-")
|
||||
if len(fw) == 2 {
|
||||
if IsPort(fw[0]) && IsPort(fw[1]) {
|
||||
start, _ := strconv.Atoi(fw[0])
|
||||
end, _ := strconv.Atoi(fw[1])
|
||||
for i := start; i <= end; i++ {
|
||||
ps = append(ps, i)
|
||||
}
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
} else if IsPort(v) {
|
||||
p, _ := strconv.Atoi(v)
|
||||
ps = append(ps, p)
|
||||
}
|
||||
}
|
||||
return ps
|
||||
}
|
||||
|
||||
func IsPort(p string) bool {
|
||||
pi, err := strconv.Atoi(p)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if pi > 65536 || pi < 1 {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func FormatAddress(s string) string {
|
||||
if strings.Contains(s, ":") {
|
||||
return s
|
||||
}
|
||||
return "127.0.0.1:" + s
|
||||
}
|
||||
|
||||
func GetIpByAddr(addr string) string {
|
||||
arr := strings.Split(addr, ":")
|
||||
return arr[0]
|
||||
}
|
||||
|
||||
func CopyBuffer(dst io.Writer, src io.Reader) (written int64, err error) {
|
||||
buf := pool.GetBufPoolCopy()
|
||||
defer pool.PutBufPoolCopy(buf)
|
||||
for {
|
||||
nr, er := src.Read(buf)
|
||||
if nr > 0 {
|
||||
nw, ew := dst.Write(buf[0:nr])
|
||||
if nw > 0 {
|
||||
written += int64(nw)
|
||||
}
|
||||
if ew != nil {
|
||||
err = ew
|
||||
break
|
||||
}
|
||||
if nr != nw {
|
||||
err = io.ErrShortWrite
|
||||
break
|
||||
}
|
||||
}
|
||||
if er != nil {
|
||||
if er != io.EOF {
|
||||
err = er
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
return written, err
|
||||
}
|
||||
|
||||
//send this ip forget to get a local udp port
|
||||
func GetLocalUdpAddr() (net.Conn, error) {
|
||||
tmpConn, err := net.Dial("udp", "114.114.114.114:53")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tmpConn, tmpConn.Close()
|
||||
}
|
||||
|
||||
func ParseStr(str string) (string, error) {
|
||||
tmp := template.New("npc")
|
||||
var err error
|
||||
w := new(bytes.Buffer)
|
||||
if tmp, err = tmp.Parse(str); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = tmp.Execute(w, GetEnvMap()); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return w.String(), nil
|
||||
}
|
||||
|
||||
//get env
|
||||
func GetEnvMap() map[string]string {
|
||||
m := make(map[string]string)
|
||||
environ := os.Environ()
|
||||
for i := range environ {
|
||||
tmp := strings.Split(environ[i], "=")
|
||||
if len(tmp) == 2 {
|
||||
m[tmp[0]] = tmp[1]
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TrimArr(arr []string) []string {
|
||||
newArr := make([]string, 0)
|
||||
for _, v := range arr {
|
||||
if v != "" {
|
||||
newArr = append(newArr, v)
|
||||
}
|
||||
}
|
||||
return newArr
|
||||
}
|
||||
|
||||
func IsArrContains(arr []string, val string) bool {
|
||||
if arr == nil {
|
||||
return false
|
||||
}
|
||||
for _, v := range arr {
|
||||
if v == val {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func RemoveArrVal(arr []string, val string) []string {
|
||||
for k, v := range arr {
|
||||
if v == val {
|
||||
arr = append(arr[:k], arr[k+1:]...)
|
||||
return arr
|
||||
}
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
func BytesToNum(b []byte) int {
|
||||
var str string
|
||||
for i := 0; i < len(b); i++ {
|
||||
str += strconv.Itoa(int(b[i]))
|
||||
}
|
||||
x, _ := strconv.Atoi(str)
|
||||
return int(x)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type CommonConfig struct {
|
||||
Server string
|
||||
VKey string
|
||||
Tp string //bridgeType kcp or tcp
|
||||
AutoReconnection bool
|
||||
Cnf *file.Config
|
||||
ProxyUrl string
|
||||
Client *file.Client
|
||||
}
|
||||
type LocalServer struct {
|
||||
Type string
|
||||
Port int
|
||||
Password string
|
||||
Target string
|
||||
}
|
||||
type Config struct {
|
||||
content string
|
||||
title []string
|
||||
CommonConfig *CommonConfig
|
||||
Hosts []*file.Host
|
||||
Tasks []*file.Tunnel
|
||||
Healths []*file.Health
|
||||
LocalServer []*LocalServer
|
||||
}
|
||||
|
||||
func NewConfig(path string) (c *Config, err error) {
|
||||
c = new(Config)
|
||||
var b []byte
|
||||
if b, err = common.ReadAllFromFile(path); err != nil {
|
||||
return
|
||||
} else {
|
||||
if c.content, err = common.ParseStr(string(b)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.title, err = getAllTitle(c.content); err != nil {
|
||||
return
|
||||
}
|
||||
var nowIndex int
|
||||
var nextIndex int
|
||||
var nowContent string
|
||||
for i := 0; i < len(c.title); i++ {
|
||||
nowIndex = strings.Index(c.content, c.title[i]) + len(c.title[i])
|
||||
if i < len(c.title)-1 {
|
||||
nextIndex = strings.Index(c.content, c.title[i+1])
|
||||
} else {
|
||||
nextIndex = len(c.content)
|
||||
}
|
||||
nowContent = c.content[nowIndex:nextIndex]
|
||||
|
||||
if strings.Index(getTitleContent(c.title[i]), "secret") == 0 && !strings.Contains(nowContent, "mode") {
|
||||
local := delLocalService(nowContent)
|
||||
local.Type = "secret"
|
||||
c.LocalServer = append(c.LocalServer, local)
|
||||
continue
|
||||
}
|
||||
//except mode
|
||||
if strings.Index(getTitleContent(c.title[i]), "p2p") == 0 && !strings.Contains(nowContent, "mode") {
|
||||
local := delLocalService(nowContent)
|
||||
local.Type = "p2p"
|
||||
c.LocalServer = append(c.LocalServer, local)
|
||||
continue
|
||||
}
|
||||
//health set
|
||||
if strings.Index(getTitleContent(c.title[i]), "health") == 0 {
|
||||
c.Healths = append(c.Healths, dealHealth(nowContent))
|
||||
continue
|
||||
}
|
||||
switch c.title[i] {
|
||||
case "[common]":
|
||||
c.CommonConfig = dealCommon(nowContent)
|
||||
default:
|
||||
if strings.Index(nowContent, "host") > -1 {
|
||||
h := dealHost(nowContent)
|
||||
h.Remark = getTitleContent(c.title[i])
|
||||
c.Hosts = append(c.Hosts, h)
|
||||
} else {
|
||||
t := dealTunnel(nowContent)
|
||||
t.Remark = getTitleContent(c.title[i])
|
||||
c.Tasks = append(c.Tasks, t)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func getTitleContent(s string) string {
|
||||
re, _ := regexp.Compile(`[\[\]]`)
|
||||
return re.ReplaceAllString(s, "")
|
||||
}
|
||||
|
||||
func dealCommon(s string) *CommonConfig {
|
||||
c := &CommonConfig{}
|
||||
c.Cnf = new(file.Config)
|
||||
c.Client = file.NewClient("", true, true)
|
||||
for _, v := range strings.Split(s, "\n") {
|
||||
item := strings.Split(v, "=")
|
||||
if len(item) == 0 {
|
||||
continue
|
||||
} else if len(item) == 1 {
|
||||
item = append(item, "")
|
||||
}
|
||||
switch item[0] {
|
||||
case "server":
|
||||
c.Server = item[1]
|
||||
case "vkey":
|
||||
c.VKey = item[1]
|
||||
case "tp":
|
||||
c.Tp = item[1]
|
||||
case "auto_reconnection":
|
||||
c.AutoReconnection = common.GetBoolByStr(item[1])
|
||||
case "username":
|
||||
c.Cnf.U = item[1]
|
||||
case "password":
|
||||
c.Cnf.P = item[1]
|
||||
case "compress":
|
||||
c.Cnf.Compress = common.GetBoolByStr(item[1])
|
||||
case "crypt":
|
||||
c.Cnf.Crypt = common.GetBoolByStr(item[1])
|
||||
case "proxy_socks5_url":
|
||||
c.ProxyUrl = item[1]
|
||||
case "rate_limit":
|
||||
c.Client.RateLimit = common.GetIntNoErrByStr(item[1])
|
||||
case "flow_limit":
|
||||
c.Client.Flow.FlowLimit = int64(common.GetIntNoErrByStr(item[1]))
|
||||
case "max_conn":
|
||||
c.Client.MaxConn = common.GetIntNoErrByStr(item[1])
|
||||
case "remark":
|
||||
c.Client.Remark = item[1]
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func dealHost(s string) *file.Host {
|
||||
h := &file.Host{}
|
||||
var headerChange string
|
||||
for _, v := range strings.Split(s, "\n") {
|
||||
item := strings.Split(v, "=")
|
||||
if len(item) == 0 {
|
||||
continue
|
||||
} else if len(item) == 1 {
|
||||
item = append(item, "")
|
||||
}
|
||||
switch strings.TrimSpace(item[0]) {
|
||||
case "host":
|
||||
h.Host = item[1]
|
||||
case "target":
|
||||
h.Target = strings.Replace(item[1], ",", "\n", -1)
|
||||
case "host_change":
|
||||
h.HostChange = item[1]
|
||||
case "schemego":
|
||||
h.Scheme = item[1]
|
||||
case "location":
|
||||
h.Location = item[1]
|
||||
default:
|
||||
if strings.Contains(item[0], "header") {
|
||||
headerChange += strings.Replace(item[0], "header_", "", -1) + ":" + item[1] + "\n"
|
||||
}
|
||||
h.HeaderChange = headerChange
|
||||
}
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func dealHealth(s string) *file.Health {
|
||||
h := &file.Health{}
|
||||
for _, v := range strings.Split(s, "\n") {
|
||||
item := strings.Split(v, "=")
|
||||
if len(item) == 0 {
|
||||
continue
|
||||
} else if len(item) == 1 {
|
||||
item = append(item, "")
|
||||
}
|
||||
switch strings.TrimSpace(item[0]) {
|
||||
case "health_check_timeout":
|
||||
h.HealthCheckTimeout = common.GetIntNoErrByStr(item[1])
|
||||
case "health_check_max_failed":
|
||||
h.HealthMaxFail = common.GetIntNoErrByStr(item[1])
|
||||
case "health_check_interval":
|
||||
h.HealthCheckInterval = common.GetIntNoErrByStr(item[1])
|
||||
case "health_http_url":
|
||||
h.HttpHealthUrl = item[1]
|
||||
case "health_check_type":
|
||||
h.HealthCheckType = item[1]
|
||||
case "health_check_target":
|
||||
h.HealthCheckTarget = item[1]
|
||||
}
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func dealTunnel(s string) *file.Tunnel {
|
||||
t := &file.Tunnel{}
|
||||
for _, v := range strings.Split(s, "\n") {
|
||||
item := strings.Split(v, "=")
|
||||
if len(item) == 0 {
|
||||
continue
|
||||
} else if len(item) == 1 {
|
||||
item = append(item, "")
|
||||
}
|
||||
switch strings.TrimSpace(item[0]) {
|
||||
case "port":
|
||||
t.Ports = item[1]
|
||||
case "mode":
|
||||
t.Mode = item[1]
|
||||
case "target":
|
||||
t.Target = strings.Replace(item[1], ",", "\n", -1)
|
||||
case "targetAddr":
|
||||
t.TargetAddr = item[1]
|
||||
case "password":
|
||||
t.Password = item[1]
|
||||
case "local_path":
|
||||
t.LocalPath = item[1]
|
||||
case "strip_pre":
|
||||
t.StripPre = item[1]
|
||||
}
|
||||
}
|
||||
return t
|
||||
|
||||
}
|
||||
|
||||
func delLocalService(s string) *LocalServer {
|
||||
l := new(LocalServer)
|
||||
for _, v := range strings.Split(s, "\n") {
|
||||
item := strings.Split(v, "=")
|
||||
if len(item) == 0 {
|
||||
continue
|
||||
} else if len(item) == 1 {
|
||||
item = append(item, "")
|
||||
}
|
||||
switch item[0] {
|
||||
case "port":
|
||||
l.Port = common.GetIntNoErrByStr(item[1])
|
||||
case "password":
|
||||
l.Password = item[1]
|
||||
case "target":
|
||||
l.Target = item[1]
|
||||
}
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func getAllTitle(content string) (arr []string, err error) {
|
||||
var re *regexp.Regexp
|
||||
re, err = regexp.Compile(`\[.+?\]`)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
arr = re.FindAllString(content, -1)
|
||||
m := make(map[string]bool)
|
||||
for _, v := range arr {
|
||||
if _, ok := m[v]; ok {
|
||||
err = errors.New("Item names are not allowed to be duplicated")
|
||||
return
|
||||
}
|
||||
m[v] = true
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"log"
|
||||
"regexp"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReg(t *testing.T) {
|
||||
content := `
|
||||
[common]
|
||||
server=127.0.0.1:8284
|
||||
tp=tcp
|
||||
vkey=123
|
||||
[web2]
|
||||
host=www.baidu.com
|
||||
host_change=www.sina.com
|
||||
target=127.0.0.1:8080,127.0.0.1:8082
|
||||
header_cookkile=122123
|
||||
header_user-Agent=122123
|
||||
[web2]
|
||||
host=www.baidu.com
|
||||
host_change=www.sina.com
|
||||
target=127.0.0.1:8080,127.0.0.1:8082
|
||||
header_cookkile="122123"
|
||||
header_user-Agent=122123
|
||||
[tunnel1]
|
||||
type=udp
|
||||
target=127.0.0.1:8080
|
||||
port=9001
|
||||
compress=snappy
|
||||
crypt=true
|
||||
u=1
|
||||
p=2
|
||||
[tunnel2]
|
||||
type=tcp
|
||||
target=127.0.0.1:8080
|
||||
port=9001
|
||||
compress=snappy
|
||||
crypt=true
|
||||
u=1
|
||||
p=2
|
||||
`
|
||||
re, err := regexp.Compile(`\[.+?\]`)
|
||||
if err != nil {
|
||||
t.Fail()
|
||||
}
|
||||
log.Println(re.FindAllString(content, -1))
|
||||
}
|
||||
|
||||
func TestDealCommon(t *testing.T) {
|
||||
s := `server=127.0.0.1:8284
|
||||
tp=tcp
|
||||
vkey=123`
|
||||
f := new(CommonConfig)
|
||||
f.Server = "127.0.0.1:8284"
|
||||
f.Tp = "tcp"
|
||||
f.VKey = "123"
|
||||
if c := dealCommon(s); *c != *f {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetTitleContent(t *testing.T) {
|
||||
s := "[common]"
|
||||
if getTitleContent(s) != "common" {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
+260
-211
@@ -6,10 +6,13 @@ import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/config"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/kcp"
|
||||
"github.com/cnlh/nps/lib/mux"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
@@ -68,198 +71,237 @@ func (s *Conn) GetHost() (method, address string, rb []byte, err error, r *http.
|
||||
return
|
||||
}
|
||||
|
||||
//读取指定长度内容
|
||||
func (s *Conn) ReadLen(cLen int) ([]byte, error) {
|
||||
if cLen > pool.PoolSize {
|
||||
return nil, errors.New("长度错误" + strconv.Itoa(cLen))
|
||||
func (s *Conn) GetShortLenContent() (b []byte, err error) {
|
||||
var l int
|
||||
if l, err = s.GetLen(); err != nil {
|
||||
return
|
||||
}
|
||||
var buf []byte
|
||||
if cLen <= pool.PoolSizeSmall {
|
||||
buf = pool.BufPoolSmall.Get().([]byte)[:cLen]
|
||||
defer pool.BufPoolSmall.Put(buf)
|
||||
} else {
|
||||
buf = pool.BufPoolMax.Get().([]byte)[:cLen]
|
||||
defer pool.BufPoolMax.Put(buf)
|
||||
if l < 0 || l > 32<<10 {
|
||||
err = errors.New("read length error")
|
||||
return
|
||||
}
|
||||
if n, err := io.ReadFull(s, buf); err != nil || n != cLen {
|
||||
return buf, errors.New("读取指定长度错误" + err.Error())
|
||||
}
|
||||
return buf, nil
|
||||
return s.GetShortContent(l)
|
||||
}
|
||||
|
||||
//read length or id (content length=4)
|
||||
func (s *Conn) GetLen() (int, error) {
|
||||
val, err := s.ReadLen(4)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
func (s *Conn) GetShortContent(l int) (b []byte, err error) {
|
||||
buf := make([]byte, l)
|
||||
return buf, binary.Read(s, binary.LittleEndian, &buf)
|
||||
}
|
||||
|
||||
//读取指定长度内容
|
||||
func (s *Conn) ReadLen(cLen int, buf []byte) (int, error) {
|
||||
if cLen > len(buf) {
|
||||
return 0, errors.New("长度错误" + strconv.Itoa(cLen))
|
||||
}
|
||||
return GetLenByBytes(val)
|
||||
if n, err := io.ReadFull(s, buf[:cLen]); err != nil || n != cLen {
|
||||
return n, errors.New("Error reading specified length " + err.Error())
|
||||
}
|
||||
return cLen, nil
|
||||
}
|
||||
|
||||
func (s *Conn) GetLen() (int, error) {
|
||||
var l int32
|
||||
err := binary.Read(s, binary.LittleEndian, &l)
|
||||
return int(l), err
|
||||
}
|
||||
|
||||
func (s *Conn) WriteLenContent(buf []byte) (err error) {
|
||||
var b []byte
|
||||
if b, err = GetLenBytes(buf); err != nil {
|
||||
return
|
||||
}
|
||||
return binary.Write(s.Conn, binary.LittleEndian, b)
|
||||
}
|
||||
|
||||
//read flag
|
||||
func (s *Conn) ReadFlag() (string, error) {
|
||||
val, err := s.ReadLen(4)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(val), err
|
||||
}
|
||||
|
||||
//read connect status
|
||||
func (s *Conn) GetConnStatus() (id int, status bool, err error) {
|
||||
id, err = s.GetLen()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var b []byte
|
||||
if b, err = s.ReadLen(1); err != nil {
|
||||
return
|
||||
} else {
|
||||
status = common.GetBoolByStr(string(b[0]))
|
||||
}
|
||||
return
|
||||
buf := make([]byte, 4)
|
||||
return string(buf), binary.Read(s, binary.LittleEndian, &buf)
|
||||
}
|
||||
|
||||
//设置连接为长连接
|
||||
func (s *Conn) SetAlive(tp string) {
|
||||
if tp == "kcp" {
|
||||
s.setKcpAlive()
|
||||
} else {
|
||||
s.setTcpAlive()
|
||||
switch s.Conn.(type) {
|
||||
case *kcp.UDPSession:
|
||||
s.Conn.(*kcp.UDPSession).SetReadDeadline(time.Time{})
|
||||
case *net.TCPConn:
|
||||
conn := s.Conn.(*net.TCPConn)
|
||||
conn.SetReadDeadline(time.Time{})
|
||||
conn.SetKeepAlive(true)
|
||||
conn.SetKeepAlivePeriod(time.Duration(2 * time.Second))
|
||||
case *mux.PortConn:
|
||||
s.Conn.(*mux.PortConn).SetReadDeadline(time.Time{})
|
||||
}
|
||||
}
|
||||
|
||||
//设置连接为长连接
|
||||
func (s *Conn) setTcpAlive() {
|
||||
conn := s.Conn.(*net.TCPConn)
|
||||
conn.SetReadDeadline(time.Time{})
|
||||
conn.SetKeepAlive(true)
|
||||
conn.SetKeepAlivePeriod(time.Duration(2 * time.Second))
|
||||
}
|
||||
|
||||
//设置连接为长连接
|
||||
func (s *Conn) setKcpAlive() {
|
||||
conn := s.Conn.(*kcp.UDPSession)
|
||||
conn.SetReadDeadline(time.Time{})
|
||||
}
|
||||
|
||||
//设置连接为长连接
|
||||
func (s *Conn) SetReadDeadline(t time.Duration, tp string) {
|
||||
if tp == "kcp" {
|
||||
s.SetKcpReadDeadline(t)
|
||||
} else {
|
||||
s.SetTcpReadDeadline(t)
|
||||
switch s.Conn.(type) {
|
||||
case *kcp.UDPSession:
|
||||
s.Conn.(*kcp.UDPSession).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
|
||||
case *net.TCPConn:
|
||||
s.Conn.(*net.TCPConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
|
||||
case *mux.PortConn:
|
||||
s.Conn.(*mux.PortConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
|
||||
}
|
||||
}
|
||||
|
||||
//set read dead time
|
||||
func (s *Conn) SetTcpReadDeadline(t time.Duration) {
|
||||
s.Conn.(*net.TCPConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
|
||||
}
|
||||
|
||||
//set read dead time
|
||||
func (s *Conn) SetKcpReadDeadline(t time.Duration) {
|
||||
s.Conn.(*kcp.UDPSession).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
|
||||
}
|
||||
|
||||
//单独读(加密|压缩)
|
||||
func (s *Conn) ReadFrom(b []byte, compress int, crypt bool, rate *rate.Rate) (int, error) {
|
||||
if common.COMPRESS_SNAPY_DECODE == compress {
|
||||
return NewSnappyConn(s.Conn, crypt, rate).Read(b)
|
||||
}
|
||||
return NewCryptConn(s.Conn, crypt, rate).Read(b)
|
||||
}
|
||||
|
||||
//单独写(加密|压缩)
|
||||
func (s *Conn) WriteTo(b []byte, compress int, crypt bool, rate *rate.Rate) (n int, err error) {
|
||||
if common.COMPRESS_SNAPY_ENCODE == compress {
|
||||
return NewSnappyConn(s.Conn, crypt, rate).Write(b)
|
||||
}
|
||||
return NewCryptConn(s.Conn, crypt, rate).Write(b)
|
||||
}
|
||||
|
||||
//send msg
|
||||
func (s *Conn) SendMsg(content []byte, link *Link) (n int, err error) {
|
||||
/*
|
||||
The msg info is formed as follows:
|
||||
+----+--------+
|
||||
|id | content |
|
||||
+----+--------+
|
||||
| 4 | ... |
|
||||
+----+--------+
|
||||
*/
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
//send info for link
|
||||
func (s *Conn) SendLinkInfo(link *Link) (int, error) {
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
binary.Write(raw, binary.LittleEndian, int32(link.Id))
|
||||
if n, err = s.Write(raw.Bytes()); err != nil {
|
||||
return
|
||||
}
|
||||
raw.Reset()
|
||||
binary.Write(raw, binary.LittleEndian, content)
|
||||
n, err = s.WriteTo(raw.Bytes(), link.En, link.Crypt, link.Rate)
|
||||
return
|
||||
common.BinaryWrite(raw, link.ConnType, link.Host, common.GetStrByBool(link.Compress), common.GetStrByBool(link.Crypt), link.RemoteAddr)
|
||||
return s.Write(raw.Bytes())
|
||||
}
|
||||
|
||||
//get msg content from conn
|
||||
func (s *Conn) GetMsgContent(link *Link) (content []byte, err error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
buf := pool.BufPoolCopy.Get().([]byte)
|
||||
if n, err := s.ReadFrom(buf, link.De, link.Crypt, link.Rate); err == nil && n > 4 {
|
||||
content = buf[:n]
|
||||
//get link info from conn
|
||||
func (s *Conn) GetLinkInfo() (lk *Link, err error) {
|
||||
lk = new(Link)
|
||||
var l int
|
||||
buf := pool.BufPoolMax.Get().([]byte)
|
||||
defer pool.PutBufPoolMax(buf)
|
||||
if l, err = s.GetLen(); err != nil {
|
||||
return
|
||||
} else if _, err = s.ReadLen(l, buf); err != nil {
|
||||
return
|
||||
} else {
|
||||
arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
|
||||
lk.ConnType = arr[0]
|
||||
lk.Host = arr[1]
|
||||
lk.Compress = common.GetBoolByStr(arr[2])
|
||||
lk.Crypt = common.GetBoolByStr(arr[3])
|
||||
lk.RemoteAddr = arr[4]
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//send info for link
|
||||
func (s *Conn) SendLinkInfo(link *Link) (int, error) {
|
||||
/*
|
||||
The link info is formed as follows:
|
||||
+----------+------+----------+------+----------+-----+
|
||||
| id | len | type | hostlen | host | en | de |crypt |
|
||||
+----------+------+----------+------+---------+------+
|
||||
| 4 | 4 | 3 | 4 | host | 1 | 1 | 1 |
|
||||
+----------+------+----------+------+----+----+------+
|
||||
*/
|
||||
func (s *Conn) SendHealthInfo(info, status string) (int, error) {
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
binary.Write(raw, binary.LittleEndian, []byte(common.NEW_CONN))
|
||||
binary.Write(raw, binary.LittleEndian, int32(14+len(link.Host)))
|
||||
binary.Write(raw, binary.LittleEndian, int32(link.Id))
|
||||
binary.Write(raw, binary.LittleEndian, []byte(link.ConnType))
|
||||
binary.Write(raw, binary.LittleEndian, int32(len(link.Host)))
|
||||
binary.Write(raw, binary.LittleEndian, []byte(link.Host))
|
||||
binary.Write(raw, binary.LittleEndian, []byte(strconv.Itoa(link.En)))
|
||||
binary.Write(raw, binary.LittleEndian, []byte(strconv.Itoa(link.De)))
|
||||
binary.Write(raw, binary.LittleEndian, []byte(common.GetStrByBool(link.Crypt)))
|
||||
common.BinaryWrite(raw, info, status)
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.Write(raw.Bytes())
|
||||
}
|
||||
|
||||
func (s *Conn) GetLinkInfo() (lk *Link, err error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
var hostLen, n int
|
||||
var buf []byte
|
||||
if n, err = s.GetLen(); err != nil {
|
||||
//get health info from conn
|
||||
func (s *Conn) GetHealthInfo() (info string, status bool, err error) {
|
||||
var l int
|
||||
buf := pool.BufPoolMax.Get().([]byte)
|
||||
defer pool.PutBufPoolMax(buf)
|
||||
if l, err = s.GetLen(); err != nil {
|
||||
return
|
||||
}
|
||||
lk = new(Link)
|
||||
if buf, err = s.ReadLen(n); err != nil {
|
||||
return
|
||||
}
|
||||
if lk.Id, err = GetLenByBytes(buf[:4]); err != nil {
|
||||
return
|
||||
}
|
||||
lk.ConnType = string(buf[4:7])
|
||||
if hostLen, err = GetLenByBytes(buf[7:11]); err != nil {
|
||||
} else if _, err = s.ReadLen(l, buf); err != nil {
|
||||
return
|
||||
} else {
|
||||
lk.Host = string(buf[11 : 11+hostLen])
|
||||
lk.En = common.GetIntNoErrByStr(string(buf[11+hostLen]))
|
||||
lk.De = common.GetIntNoErrByStr(string(buf[12+hostLen]))
|
||||
lk.Crypt = common.GetBoolByStr(string(buf[13+hostLen]))
|
||||
arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
|
||||
if len(arr) >= 2 {
|
||||
return arr[0], common.GetBoolByStr(arr[1]), nil
|
||||
}
|
||||
}
|
||||
return "", false, errors.New("receive health info error")
|
||||
}
|
||||
|
||||
//send host info
|
||||
func (s *Conn) SendHostInfo(h *file.Host) (int, error) {
|
||||
/*
|
||||
The task info is formed as follows:
|
||||
+----+-----+---------+
|
||||
|type| len | content |
|
||||
+----+---------------+
|
||||
| 4 | 4 | ... |
|
||||
+----+---------------+
|
||||
*/
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
binary.Write(raw, binary.LittleEndian, []byte(common.NEW_HOST))
|
||||
common.BinaryWrite(raw, h.Host, h.Target, h.HeaderChange, h.HostChange, h.Remark, h.Location, h.Scheme)
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.Write(raw.Bytes())
|
||||
}
|
||||
|
||||
//get task or host result of add
|
||||
func (s *Conn) GetAddStatus() (b bool) {
|
||||
binary.Read(s.Conn, binary.LittleEndian, &b)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Conn) WriteAddOk() error {
|
||||
return binary.Write(s.Conn, binary.LittleEndian, true)
|
||||
}
|
||||
|
||||
func (s *Conn) WriteAddFail() error {
|
||||
defer s.Close()
|
||||
return binary.Write(s.Conn, binary.LittleEndian, false)
|
||||
}
|
||||
|
||||
//get task info
|
||||
func (s *Conn) GetHostInfo() (h *file.Host, err error) {
|
||||
var l int
|
||||
buf := pool.BufPoolMax.Get().([]byte)
|
||||
defer pool.PutBufPoolMax(buf)
|
||||
if l, err = s.GetLen(); err != nil {
|
||||
return
|
||||
} else if _, err = s.ReadLen(l, buf); err != nil {
|
||||
return
|
||||
} else {
|
||||
arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
|
||||
h = new(file.Host)
|
||||
h.Id = file.GetCsvDb().GetHostId()
|
||||
h.Host = arr[0]
|
||||
h.Target = arr[1]
|
||||
h.HeaderChange = arr[2]
|
||||
h.HostChange = arr[3]
|
||||
h.Remark = arr[4]
|
||||
h.Location = arr[5]
|
||||
h.Scheme = arr[6]
|
||||
if h.Scheme == "" {
|
||||
h.Scheme = "all"
|
||||
}
|
||||
h.Flow = new(file.Flow)
|
||||
h.NoStore = true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//send task info
|
||||
func (s *Conn) SendConfigInfo(c *config.CommonConfig) (int, error) {
|
||||
/*
|
||||
The task info is formed as follows:
|
||||
+----+-----+---------+
|
||||
|type| len | content |
|
||||
+----+---------------+
|
||||
| 4 | 4 | ... |
|
||||
+----+---------------+
|
||||
*/
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
binary.Write(raw, binary.LittleEndian, []byte(common.NEW_CONF))
|
||||
common.BinaryWrite(raw, c.Cnf.U, c.Cnf.P, common.GetStrByBool(c.Cnf.Crypt), common.GetStrByBool(c.Cnf.Compress), strconv.Itoa(c.Client.RateLimit),
|
||||
strconv.Itoa(int(c.Client.Flow.FlowLimit)), strconv.Itoa(c.Client.MaxConn), c.Client.Remark)
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.Write(raw.Bytes())
|
||||
}
|
||||
|
||||
//get task info
|
||||
func (s *Conn) GetConfigInfo() (c *file.Client, err error) {
|
||||
var l int
|
||||
buf := pool.BufPoolMax.Get().([]byte)
|
||||
defer pool.PutBufPoolMax(buf)
|
||||
if l, err = s.GetLen(); err != nil {
|
||||
return
|
||||
} else if _, err = s.ReadLen(l, buf); err != nil {
|
||||
return
|
||||
} else {
|
||||
arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
|
||||
c = file.NewClient("", true, false)
|
||||
c.Cnf.U = arr[0]
|
||||
c.Cnf.P = arr[1]
|
||||
c.Cnf.Crypt = common.GetBoolByStr(arr[2])
|
||||
c.Cnf.Compress = common.GetBoolByStr(arr[3])
|
||||
c.RateLimit = common.GetIntNoErrByStr(arr[4])
|
||||
c.Flow.FlowLimit = int64(common.GetIntNoErrByStr(arr[5]))
|
||||
c.MaxConn = common.GetIntNoErrByStr(arr[6])
|
||||
c.Remark = arr[7]
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -273,10 +315,10 @@ func (s *Conn) SendTaskInfo(t *file.Tunnel) (int, error) {
|
||||
+----+---------------+
|
||||
| 4 | 4 | ... |
|
||||
+----+---------------+
|
||||
*/
|
||||
*/
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
binary.Write(raw, binary.LittleEndian, common.NEW_TASK)
|
||||
common.BinaryWrite(raw, t.Mode, string(t.TcpPort), string(t.Target), string(t.Config.U), string(t.Config.P), common.GetStrByBool(t.Config.Crypt), t.Config.Compress, t.Remark)
|
||||
binary.Write(raw, binary.LittleEndian, []byte(common.NEW_TASK))
|
||||
common.BinaryWrite(raw, t.Mode, t.Ports, t.Target, t.Remark, t.TargetAddr, t.Password, t.LocalPath, t.StripPre)
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.Write(raw.Bytes())
|
||||
@@ -285,53 +327,31 @@ func (s *Conn) SendTaskInfo(t *file.Tunnel) (int, error) {
|
||||
//get task info
|
||||
func (s *Conn) GetTaskInfo() (t *file.Tunnel, err error) {
|
||||
var l int
|
||||
var b []byte
|
||||
buf := pool.BufPoolMax.Get().([]byte)
|
||||
defer pool.PutBufPoolMax(buf)
|
||||
if l, err = s.GetLen(); err != nil {
|
||||
return
|
||||
} else if b, err = s.ReadLen(l); err != nil {
|
||||
} else if _, err = s.ReadLen(l, buf); err != nil {
|
||||
return
|
||||
} else {
|
||||
arr := strings.Split(string(b), "#")
|
||||
arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
|
||||
t = new(file.Tunnel)
|
||||
t.Mode = arr[0]
|
||||
t.TcpPort, _ = strconv.Atoi(arr[1])
|
||||
t.Ports = arr[1]
|
||||
t.Target = arr[2]
|
||||
t.Config = new(file.Config)
|
||||
t.Config.U = arr[3]
|
||||
t.Config.P = arr[4]
|
||||
t.Config.Compress = arr[5]
|
||||
t.Config.CompressDecode, t.Config.CompressDecode = common.GetCompressType(arr[5])
|
||||
t.Id = file.GetCsvDb().GetTaskId()
|
||||
t.Status = true
|
||||
if t.Client, err = file.GetCsvDb().GetClient(0); err != nil {
|
||||
return
|
||||
}
|
||||
t.Flow = new(file.Flow)
|
||||
t.Remark = arr[6]
|
||||
t.UseClientCnf = false
|
||||
t.Remark = arr[3]
|
||||
t.TargetAddr = arr[4]
|
||||
t.Password = arr[5]
|
||||
t.LocalPath = arr[6]
|
||||
t.StripPre = arr[7]
|
||||
t.NoStore = true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//write connect success
|
||||
func (s *Conn) WriteSuccess(id int) (int, error) {
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
binary.Write(raw, binary.LittleEndian, int32(id))
|
||||
binary.Write(raw, binary.LittleEndian, []byte("1"))
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.Write(raw.Bytes())
|
||||
}
|
||||
|
||||
//write connect fail
|
||||
func (s *Conn) WriteFail(id int) (int, error) {
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
binary.Write(raw, binary.LittleEndian, int32(id))
|
||||
binary.Write(raw, binary.LittleEndian, []byte("0"))
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.Write(raw.Bytes())
|
||||
}
|
||||
|
||||
//close
|
||||
func (s *Conn) Close() error {
|
||||
return s.Conn.Close()
|
||||
@@ -347,16 +367,6 @@ func (s *Conn) Read(b []byte) (int, error) {
|
||||
return s.Conn.Read(b)
|
||||
}
|
||||
|
||||
//write error
|
||||
func (s *Conn) WriteError() (int, error) {
|
||||
return s.Write([]byte(common.RES_MSG))
|
||||
}
|
||||
|
||||
//write sign flag
|
||||
func (s *Conn) WriteSign() (int, error) {
|
||||
return s.Write([]byte(common.RES_SIGN))
|
||||
}
|
||||
|
||||
//write sign flag
|
||||
func (s *Conn) WriteClose() (int, error) {
|
||||
return s.Write([]byte(common.RES_CLOSE))
|
||||
@@ -369,6 +379,13 @@ func (s *Conn) WriteMain() (int, error) {
|
||||
return s.Write([]byte(common.WORK_MAIN))
|
||||
}
|
||||
|
||||
//write main
|
||||
func (s *Conn) WriteConfig() (int, error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.Write([]byte(common.WORK_CONFIG))
|
||||
}
|
||||
|
||||
//write chan
|
||||
func (s *Conn) WriteChan() (int, error) {
|
||||
s.Lock()
|
||||
@@ -389,15 +406,6 @@ func GetLenBytes(buf []byte) (b []byte, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
//解析出长度
|
||||
func GetLenByBytes(buf []byte) (int, error) {
|
||||
nlen := binary.LittleEndian.Uint32(buf)
|
||||
if nlen <= 0 {
|
||||
return 0, errors.New("数据长度错误")
|
||||
}
|
||||
return int(nlen), nil
|
||||
}
|
||||
|
||||
func SetUdpSession(sess *kcp.UDPSession) {
|
||||
sess.SetStreamMode(true)
|
||||
sess.SetWindowSize(1024, 1024)
|
||||
@@ -406,4 +414,45 @@ func SetUdpSession(sess *kcp.UDPSession) {
|
||||
sess.SetNoDelay(1, 10, 2, 1)
|
||||
sess.SetMtu(1600)
|
||||
sess.SetACKNoDelay(true)
|
||||
sess.SetWriteDelay(false)
|
||||
}
|
||||
|
||||
//conn1 mux conn
|
||||
func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Rate, flow *file.Flow, isServer bool) {
|
||||
var in, out int64
|
||||
var wg sync.WaitGroup
|
||||
connHandle := GetConn(conn1, crypt, snappy, rate, isServer)
|
||||
go func(in *int64) {
|
||||
wg.Add(1)
|
||||
*in, _ = common.CopyBuffer(connHandle, conn2)
|
||||
connHandle.Close()
|
||||
conn2.Close()
|
||||
wg.Done()
|
||||
}(&in)
|
||||
out, _ = common.CopyBuffer(conn2, connHandle)
|
||||
connHandle.Close()
|
||||
conn2.Close()
|
||||
wg.Wait()
|
||||
if flow != nil {
|
||||
flow.Add(in, out)
|
||||
}
|
||||
}
|
||||
|
||||
//get crypt or snappy conn
|
||||
func GetConn(conn net.Conn, cpt, snappy bool, rate *rate.Rate, isServer bool) (io.ReadWriteCloser) {
|
||||
if cpt {
|
||||
if isServer {
|
||||
return crypt.NewTlsServerConn(conn)
|
||||
}
|
||||
return crypt.NewTlsClientConn(conn)
|
||||
} else if snappy {
|
||||
return NewSnappyConn(conn, cpt, rate)
|
||||
}
|
||||
return conn
|
||||
}
|
||||
|
||||
//read length or id (content length=4)
|
||||
func GetLen(reader io.Reader) (int, error) {
|
||||
var l int32
|
||||
return int(l), binary.Read(reader, binary.LittleEndian, &l)
|
||||
}
|
||||
|
||||
+24
-30
@@ -1,37 +1,31 @@
|
||||
package conn
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
"net"
|
||||
)
|
||||
|
||||
type Link struct {
|
||||
Id int //id
|
||||
ConnType string //连接类型
|
||||
Host string //目标
|
||||
En int //加密
|
||||
De int //解密
|
||||
Crypt bool //加密
|
||||
Conn *Conn
|
||||
Flow *file.Flow
|
||||
UdpListener *net.UDPConn
|
||||
Rate *rate.Rate
|
||||
UdpRemoteAddr *net.UDPAddr
|
||||
type Secret struct {
|
||||
Password string
|
||||
Conn *Conn
|
||||
}
|
||||
|
||||
func NewLink(id int, connType string, host string, en, de int, crypt bool, c *Conn, flow *file.Flow, udpListener *net.UDPConn, rate *rate.Rate, UdpRemoteAddr *net.UDPAddr) *Link {
|
||||
func NewSecret(p string, conn *Conn) *Secret {
|
||||
return &Secret{
|
||||
Password: p,
|
||||
Conn: conn,
|
||||
}
|
||||
}
|
||||
|
||||
type Link struct {
|
||||
ConnType string //连接类型
|
||||
Host string //目标
|
||||
Crypt bool //加密
|
||||
Compress bool
|
||||
RemoteAddr string
|
||||
}
|
||||
|
||||
func NewLink(connType string, host string, crypt bool, compress bool, remoteAddr string) *Link {
|
||||
return &Link{
|
||||
Id: id,
|
||||
ConnType: connType,
|
||||
Host: host,
|
||||
En: en,
|
||||
De: de,
|
||||
Crypt: crypt,
|
||||
Conn: c,
|
||||
Flow: flow,
|
||||
UdpListener: udpListener,
|
||||
Rate: rate,
|
||||
UdpRemoteAddr: UdpRemoteAddr,
|
||||
RemoteAddr: remoteAddr,
|
||||
ConnType: connType,
|
||||
Host: host,
|
||||
Crypt: crypt,
|
||||
Compress: compress,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
package conn
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
"net"
|
||||
)
|
||||
|
||||
type CryptConn struct {
|
||||
conn net.Conn
|
||||
crypt bool
|
||||
rate *rate.Rate
|
||||
}
|
||||
|
||||
func NewCryptConn(conn net.Conn, crypt bool, rate *rate.Rate) *CryptConn {
|
||||
c := new(CryptConn)
|
||||
c.conn = conn
|
||||
c.crypt = crypt
|
||||
c.rate = rate
|
||||
return c
|
||||
}
|
||||
|
||||
//加密写
|
||||
func (s *CryptConn) Write(b []byte) (n int, err error) {
|
||||
n = len(b)
|
||||
if s.crypt {
|
||||
if b, err = crypt.AesEncrypt(b, []byte(cryptKey)); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if b, err = GetLenBytes(b); err != nil {
|
||||
return
|
||||
}
|
||||
_, err = s.conn.Write(b)
|
||||
if s.rate != nil {
|
||||
s.rate.Get(int64(n))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//解密读
|
||||
func (s *CryptConn) Read(b []byte) (n int, err error) {
|
||||
var lens int
|
||||
var buf []byte
|
||||
var rb []byte
|
||||
c := NewConn(s.conn)
|
||||
if lens, err = c.GetLen(); err != nil {
|
||||
return
|
||||
}
|
||||
if buf, err = c.ReadLen(lens); err != nil {
|
||||
return
|
||||
}
|
||||
if s.crypt {
|
||||
if rb, err = crypt.AesDecrypt(buf, []byte(cryptKey)); err != nil {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
rb = buf
|
||||
}
|
||||
copy(b, rb)
|
||||
n = len(rb)
|
||||
if s.rate != nil {
|
||||
s.rate.Get(int64(n))
|
||||
}
|
||||
return
|
||||
}
|
||||
+15
-32
@@ -1,41 +1,29 @@
|
||||
package conn
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
"github.com/cnlh/nps/lib/snappy"
|
||||
"log"
|
||||
"net"
|
||||
"github.com/cnlh/nps/vender/github.com/golang/snappy"
|
||||
"io"
|
||||
)
|
||||
|
||||
type SnappyConn struct {
|
||||
w *snappy.Writer
|
||||
r *snappy.Reader
|
||||
crypt bool
|
||||
rate *rate.Rate
|
||||
w *snappy.Writer
|
||||
r *snappy.Reader
|
||||
rate *rate.Rate
|
||||
}
|
||||
|
||||
func NewSnappyConn(conn net.Conn, crypt bool, rate *rate.Rate) *SnappyConn {
|
||||
func NewSnappyConn(conn io.ReadWriteCloser, crypt bool, rate *rate.Rate) *SnappyConn {
|
||||
c := new(SnappyConn)
|
||||
c.w = snappy.NewBufferedWriter(conn)
|
||||
c.r = snappy.NewReader(conn)
|
||||
c.crypt = crypt
|
||||
c.rate = rate
|
||||
return c
|
||||
}
|
||||
|
||||
//snappy压缩写 包含加密
|
||||
//snappy压缩写
|
||||
func (s *SnappyConn) Write(b []byte) (n int, err error) {
|
||||
n = len(b)
|
||||
if s.crypt {
|
||||
if b, err = crypt.AesEncrypt(b, []byte(cryptKey)); err != nil {
|
||||
lg.Println("encode crypt error:", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if _, err = s.w.Write(b); err != nil {
|
||||
if n, err = s.w.Write(b); err != nil {
|
||||
return
|
||||
}
|
||||
if err = s.w.Flush(); err != nil {
|
||||
@@ -47,26 +35,21 @@ func (s *SnappyConn) Write(b []byte) (n int, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
//snappy压缩读 包含解密
|
||||
//snappy压缩读
|
||||
func (s *SnappyConn) Read(b []byte) (n int, err error) {
|
||||
buf := pool.BufPool.Get().([]byte)
|
||||
defer pool.BufPool.Put(buf)
|
||||
if n, err = s.r.Read(buf); err != nil {
|
||||
return
|
||||
}
|
||||
var bs []byte
|
||||
if s.crypt {
|
||||
if bs, err = crypt.AesDecrypt(buf[:n], []byte(cryptKey)); err != nil {
|
||||
log.Println("decode crypt error:", err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
bs = buf[:n]
|
||||
}
|
||||
n = len(bs)
|
||||
copy(b, bs)
|
||||
copy(b, buf[:n])
|
||||
if s.rate != nil {
|
||||
s.rate.Get(int64(n))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *SnappyConn) Close() error {
|
||||
s.w.Close()
|
||||
return s.w.Close()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package crypt
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func NewTlsServerConn(conn net.Conn) net.Conn {
|
||||
cert, err := tls.LoadX509KeyPair(filepath.Join(beego.AppPath, "conf", "server.pem"), filepath.Join(beego.AppPath, "conf", "server.key"))
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
return nil
|
||||
}
|
||||
config := &tls.Config{Certificates: []tls.Certificate{cert}}
|
||||
return tls.Server(conn, config)
|
||||
}
|
||||
|
||||
func NewTlsClientConn(conn net.Conn) net.Conn {
|
||||
conf := &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
}
|
||||
return tls.Client(conn, conf)
|
||||
}
|
||||
@@ -49,7 +49,7 @@ func status(f string, pidPath string) bool {
|
||||
if !common.IsWindows() {
|
||||
cmd = exec.Command("/bin/sh", "-c", "ps -ax | awk '{ print $1 }' | grep "+string(b))
|
||||
} else {
|
||||
cmd = exec.Command("tasklist", )
|
||||
cmd = exec.Command("tasklist")
|
||||
}
|
||||
out, _ := cmd.Output()
|
||||
if strings.Index(string(out), string(b)) > -1 {
|
||||
|
||||
+4
-1
@@ -9,11 +9,14 @@ var (
|
||||
CsvDb *Csv
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
//init csv from file
|
||||
func GetCsvDb() *Csv {
|
||||
once.Do(func() {
|
||||
CsvDb = NewCsv(common.GetRunPath())
|
||||
CsvDb.Init()
|
||||
CsvDb.LoadClientFromCsv()
|
||||
CsvDb.LoadTaskFromCsv()
|
||||
CsvDb.LoadHostFromCsv()
|
||||
})
|
||||
return CsvDb
|
||||
}
|
||||
|
||||
+251
-62
@@ -3,11 +3,15 @@ package file
|
||||
import (
|
||||
"encoding/csv"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -27,45 +31,41 @@ type Csv struct {
|
||||
RunPath string //存储根目录
|
||||
ClientIncreaseId int //客户端id
|
||||
TaskIncreaseId int //任务自增ID
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
func (s *Csv) Init() {
|
||||
s.LoadClientFromCsv()
|
||||
s.LoadTaskFromCsv()
|
||||
s.LoadHostFromCsv()
|
||||
HostIncreaseId int
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func (s *Csv) StoreTasksToCsv() {
|
||||
// 创建文件
|
||||
csvFile, err := os.Create(filepath.Join(s.RunPath, "conf", "tasks.csv"))
|
||||
if err != nil {
|
||||
lg.Fatalf(err.Error())
|
||||
logs.Error(err.Error())
|
||||
}
|
||||
defer csvFile.Close()
|
||||
writer := csv.NewWriter(csvFile)
|
||||
s.Lock()
|
||||
for _, task := range s.Tasks {
|
||||
if task.NoStore {
|
||||
continue
|
||||
}
|
||||
record := []string{
|
||||
strconv.Itoa(task.TcpPort),
|
||||
strconv.Itoa(task.Port),
|
||||
task.Mode,
|
||||
task.Target,
|
||||
task.Config.U,
|
||||
task.Config.P,
|
||||
task.Config.Compress,
|
||||
common.GetStrByBool(task.Status),
|
||||
common.GetStrByBool(task.Config.Crypt),
|
||||
strconv.Itoa(task.Config.CompressEncode),
|
||||
strconv.Itoa(task.Config.CompressDecode),
|
||||
strconv.Itoa(task.Id),
|
||||
strconv.Itoa(task.Client.Id),
|
||||
strconv.FormatBool(task.UseClientCnf),
|
||||
task.Remark,
|
||||
strconv.Itoa(int(task.Flow.ExportFlow)),
|
||||
strconv.Itoa(int(task.Flow.InletFlow)),
|
||||
task.Password,
|
||||
}
|
||||
err := writer.Write(record)
|
||||
if err != nil {
|
||||
lg.Fatalf(err.Error())
|
||||
logs.Error(err.Error())
|
||||
}
|
||||
}
|
||||
s.Unlock()
|
||||
writer.Flush()
|
||||
}
|
||||
|
||||
@@ -91,30 +91,25 @@ func (s *Csv) LoadTaskFromCsv() {
|
||||
path := filepath.Join(s.RunPath, "conf", "tasks.csv")
|
||||
records, err := s.openFile(path)
|
||||
if err != nil {
|
||||
lg.Fatalln("配置文件打开错误:", path)
|
||||
logs.Error("Profile Opening Error:", path)
|
||||
os.Exit(0)
|
||||
}
|
||||
var tasks []*Tunnel
|
||||
// 将每一行数据保存到内存slice中
|
||||
for _, item := range records {
|
||||
post := &Tunnel{
|
||||
TcpPort: common.GetIntNoErrByStr(item[0]),
|
||||
Mode: item[1],
|
||||
Target: item[2],
|
||||
Config: &Config{
|
||||
U: item[3],
|
||||
P: item[4],
|
||||
Compress: item[5],
|
||||
Crypt: common.GetBoolByStr(item[7]),
|
||||
CompressEncode: common.GetIntNoErrByStr(item[8]),
|
||||
CompressDecode: common.GetIntNoErrByStr(item[9]),
|
||||
},
|
||||
Status: common.GetBoolByStr(item[6]),
|
||||
Id: common.GetIntNoErrByStr(item[10]),
|
||||
UseClientCnf: common.GetBoolByStr(item[12]),
|
||||
Remark: item[13],
|
||||
Port: common.GetIntNoErrByStr(item[0]),
|
||||
Mode: item[1],
|
||||
Target: item[2],
|
||||
Status: common.GetBoolByStr(item[3]),
|
||||
Id: common.GetIntNoErrByStr(item[4]),
|
||||
Remark: item[6],
|
||||
Password: item[9],
|
||||
}
|
||||
post.Flow = new(Flow)
|
||||
if post.Client, err = s.GetClient(common.GetIntNoErrByStr(item[11])); err != nil {
|
||||
post.Flow.ExportFlow = int64(common.GetIntNoErrByStr(item[7]))
|
||||
post.Flow.InletFlow = int64(common.GetIntNoErrByStr(item[8]))
|
||||
if post.Client, err = s.GetClient(common.GetIntNoErrByStr(item[5])); err != nil {
|
||||
continue
|
||||
}
|
||||
tasks = append(tasks, post)
|
||||
@@ -132,6 +127,13 @@ func (s *Csv) GetTaskId() int {
|
||||
return s.TaskIncreaseId
|
||||
}
|
||||
|
||||
func (s *Csv) GetHostId() int {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.HostIncreaseId++
|
||||
return s.HostIncreaseId
|
||||
}
|
||||
|
||||
func (s *Csv) GetIdByVerifyKey(vKey string, addr string) (int, error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
@@ -146,36 +148,62 @@ func (s *Csv) GetIdByVerifyKey(vKey string, addr string) (int, error) {
|
||||
return 0, errors.New("not found")
|
||||
}
|
||||
|
||||
func (s *Csv) NewTask(t *Tunnel) {
|
||||
func (s *Csv) NewTask(t *Tunnel) error {
|
||||
s.Lock()
|
||||
for _, v := range s.Tasks {
|
||||
if (v.Mode == "secret" || v.Mode == "p2p") && v.Password == t.Password {
|
||||
return errors.New(fmt.Sprintf("Secret mode keys %s must be unique", t.Password))
|
||||
}
|
||||
}
|
||||
t.Flow = new(Flow)
|
||||
s.Tasks = append(s.Tasks, t)
|
||||
s.Unlock()
|
||||
s.StoreTasksToCsv()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Csv) UpdateTask(t *Tunnel) error {
|
||||
for k, v := range s.Tasks {
|
||||
s.Lock()
|
||||
for _, v := range s.Tasks {
|
||||
if v.Id == t.Id {
|
||||
s.Tasks = append(s.Tasks[:k], s.Tasks[k+1:]...)
|
||||
s.Tasks = append(s.Tasks, t)
|
||||
s.Unlock()
|
||||
s.StoreTasksToCsv()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errors.New("不存在")
|
||||
s.Unlock()
|
||||
return errors.New("the task is not exist")
|
||||
}
|
||||
|
||||
func (s *Csv) DelTask(id int) error {
|
||||
s.Lock()
|
||||
for k, v := range s.Tasks {
|
||||
if v.Id == id {
|
||||
s.Tasks = append(s.Tasks[:k], s.Tasks[k+1:]...)
|
||||
s.Unlock()
|
||||
s.StoreTasksToCsv()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
s.Unlock()
|
||||
return errors.New("不存在")
|
||||
}
|
||||
|
||||
//md5 password
|
||||
func (s *Csv) GetTaskByMd5Password(p string) *Tunnel {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
for _, v := range s.Tasks {
|
||||
if crypt.Md5(v.Password) == p {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Csv) GetTask(id int) (v *Tunnel, err error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
for _, v = range s.Tasks {
|
||||
if v.Id == id {
|
||||
return
|
||||
@@ -196,7 +224,12 @@ func (s *Csv) StoreHostToCsv() {
|
||||
writer := csv.NewWriter(csvFile)
|
||||
// 将map中的Post转换成slice,因为csv的Write需要slice参数
|
||||
// 并写入csv文件
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
for _, host := range s.Hosts {
|
||||
if host.NoStore {
|
||||
continue
|
||||
}
|
||||
record := []string{
|
||||
host.Host,
|
||||
host.Target,
|
||||
@@ -204,6 +237,11 @@ func (s *Csv) StoreHostToCsv() {
|
||||
host.HeaderChange,
|
||||
host.HostChange,
|
||||
host.Remark,
|
||||
host.Location,
|
||||
strconv.Itoa(host.Id),
|
||||
strconv.Itoa(int(host.Flow.ExportFlow)),
|
||||
strconv.Itoa(int(host.Flow.InletFlow)),
|
||||
host.Scheme,
|
||||
}
|
||||
err1 := writer.Write(record)
|
||||
if err1 != nil {
|
||||
@@ -218,7 +256,8 @@ func (s *Csv) LoadClientFromCsv() {
|
||||
path := filepath.Join(s.RunPath, "conf", "clients.csv")
|
||||
records, err := s.openFile(path)
|
||||
if err != nil {
|
||||
lg.Fatalln("配置文件打开错误:", path)
|
||||
logs.Error("Profile Opening Error:", path)
|
||||
os.Exit(0)
|
||||
}
|
||||
var clients []*Client
|
||||
// 将每一行数据保存到内存slice中
|
||||
@@ -233,8 +272,9 @@ func (s *Csv) LoadClientFromCsv() {
|
||||
U: item[4],
|
||||
P: item[5],
|
||||
Crypt: common.GetBoolByStr(item[6]),
|
||||
Compress: item[7],
|
||||
Compress: common.GetBoolByStr(item[7]),
|
||||
},
|
||||
MaxConn: common.GetIntNoErrByStr(item[10]),
|
||||
}
|
||||
if post.Id > s.ClientIncreaseId {
|
||||
s.ClientIncreaseId = post.Id
|
||||
@@ -254,7 +294,8 @@ func (s *Csv) LoadHostFromCsv() {
|
||||
path := filepath.Join(s.RunPath, "conf", "hosts.csv")
|
||||
records, err := s.openFile(path)
|
||||
if err != nil {
|
||||
lg.Fatalln("配置文件打开错误:", path)
|
||||
logs.Error("Profile Opening Error:", path)
|
||||
os.Exit(0)
|
||||
}
|
||||
var hosts []*Host
|
||||
// 将每一行数据保存到内存slice中
|
||||
@@ -265,49 +306,86 @@ func (s *Csv) LoadHostFromCsv() {
|
||||
HeaderChange: item[3],
|
||||
HostChange: item[4],
|
||||
Remark: item[5],
|
||||
Location: item[6],
|
||||
Id: common.GetIntNoErrByStr(item[7]),
|
||||
}
|
||||
if post.Client, err = s.GetClient(common.GetIntNoErrByStr(item[2])); err != nil {
|
||||
continue
|
||||
}
|
||||
post.Flow = new(Flow)
|
||||
post.Flow.ExportFlow = int64(common.GetIntNoErrByStr(item[8]))
|
||||
post.Flow.InletFlow = int64(common.GetIntNoErrByStr(item[9]))
|
||||
if len(item) > 10 {
|
||||
post.Scheme = item[10]
|
||||
} else {
|
||||
post.Scheme = "all"
|
||||
}
|
||||
hosts = append(hosts, post)
|
||||
if post.Id > s.HostIncreaseId {
|
||||
s.HostIncreaseId = post.Id
|
||||
}
|
||||
}
|
||||
s.Hosts = hosts
|
||||
}
|
||||
|
||||
func (s *Csv) DelHost(host string) error {
|
||||
func (s *Csv) DelHost(id int) error {
|
||||
s.Lock()
|
||||
for k, v := range s.Hosts {
|
||||
if v.Host == host {
|
||||
if v.Id == id {
|
||||
s.Hosts = append(s.Hosts[:k], s.Hosts[k+1:]...)
|
||||
s.Unlock()
|
||||
s.StoreHostToCsv()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
s.Unlock()
|
||||
return errors.New("不存在")
|
||||
}
|
||||
|
||||
func (s *Csv) NewHost(t *Host) {
|
||||
t.Flow = new(Flow)
|
||||
s.Hosts = append(s.Hosts, t)
|
||||
s.StoreHostToCsv()
|
||||
func (s *Csv) IsHostExist(h *Host) bool {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
for _, v := range s.Hosts {
|
||||
if v.Host == h.Host && h.Location == v.Location && (v.Scheme == "all" || v.Scheme == h.Scheme) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Csv) NewHost(t *Host) error {
|
||||
if s.IsHostExist(t) {
|
||||
return errors.New("host has exist")
|
||||
}
|
||||
if t.Location == "" {
|
||||
t.Location = "/"
|
||||
}
|
||||
t.Flow = new(Flow)
|
||||
s.Lock()
|
||||
s.Hosts = append(s.Hosts, t)
|
||||
s.Unlock()
|
||||
s.StoreHostToCsv()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Csv) UpdateHost(t *Host) error {
|
||||
for k, v := range s.Hosts {
|
||||
s.Lock()
|
||||
for _, v := range s.Hosts {
|
||||
if v.Host == t.Host {
|
||||
s.Hosts = append(s.Hosts[:k], s.Hosts[k+1:]...)
|
||||
s.Hosts = append(s.Hosts, t)
|
||||
s.Unlock()
|
||||
s.StoreHostToCsv()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
s.Unlock()
|
||||
return errors.New("不存在")
|
||||
}
|
||||
|
||||
func (s *Csv) GetHost(start, length int, id int) ([]*Host, int) {
|
||||
list := make([]*Host, 0)
|
||||
var cnt int
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
for _, v := range s.Hosts {
|
||||
if id == 0 || v.Client.Id == id {
|
||||
cnt++
|
||||
@@ -322,22 +400,54 @@ func (s *Csv) GetHost(start, length int, id int) ([]*Host, int) {
|
||||
}
|
||||
|
||||
func (s *Csv) DelClient(id int) error {
|
||||
s.Lock()
|
||||
for k, v := range s.Clients {
|
||||
if v.Id == id {
|
||||
s.Clients = append(s.Clients[:k], s.Clients[k+1:]...)
|
||||
s.Unlock()
|
||||
s.StoreClientsToCsv()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
s.Unlock()
|
||||
return errors.New("不存在")
|
||||
}
|
||||
|
||||
func (s *Csv) NewClient(c *Client) {
|
||||
func (s *Csv) NewClient(c *Client) error {
|
||||
var isNotSet bool
|
||||
reset:
|
||||
if c.VerifyKey == "" || isNotSet {
|
||||
isNotSet = true
|
||||
c.VerifyKey = crypt.GetRandomString(16)
|
||||
}
|
||||
if !s.VerifyVkey(c.VerifyKey, c.id) {
|
||||
if isNotSet {
|
||||
goto reset
|
||||
}
|
||||
return errors.New("Vkey duplicate, please reset")
|
||||
}
|
||||
if c.Id == 0 {
|
||||
c.Id = s.GetClientId()
|
||||
}
|
||||
if c.Flow == nil {
|
||||
c.Flow = new(Flow)
|
||||
}
|
||||
s.Lock()
|
||||
s.Clients = append(s.Clients, c)
|
||||
s.Unlock()
|
||||
s.StoreClientsToCsv()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Csv) VerifyVkey(vkey string, id int) bool {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
c.Flow = new(Flow)
|
||||
s.Clients = append(s.Clients, c)
|
||||
s.StoreClientsToCsv()
|
||||
for _, v := range s.Clients {
|
||||
if v.VerifyKey == vkey && v.Id != id {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Csv) GetClientId() int {
|
||||
@@ -349,7 +459,6 @@ func (s *Csv) GetClientId() int {
|
||||
|
||||
func (s *Csv) UpdateClient(t *Client) error {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
for _, v := range s.Clients {
|
||||
if v.Id == t.Id {
|
||||
v.Cnf = t.Cnf
|
||||
@@ -358,17 +467,24 @@ func (s *Csv) UpdateClient(t *Client) error {
|
||||
v.RateLimit = t.RateLimit
|
||||
v.Flow = t.Flow
|
||||
v.Rate = t.Rate
|
||||
s.Unlock()
|
||||
s.StoreClientsToCsv()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errors.New("不存在")
|
||||
s.Unlock()
|
||||
return errors.New("该客户端不存在")
|
||||
}
|
||||
|
||||
func (s *Csv) GetClientList(start, length int) ([]*Client, int) {
|
||||
list := make([]*Client, 0)
|
||||
var cnt int
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
for _, v := range s.Clients {
|
||||
if v.NoDisplay {
|
||||
continue
|
||||
}
|
||||
cnt++
|
||||
if start--; start < 0 {
|
||||
if length--; length > 0 {
|
||||
@@ -380,24 +496,96 @@ func (s *Csv) GetClientList(start, length int) ([]*Client, int) {
|
||||
}
|
||||
|
||||
func (s *Csv) GetClient(id int) (v *Client, err error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
for _, v = range s.Clients {
|
||||
if v.Id == id {
|
||||
return
|
||||
}
|
||||
}
|
||||
err = errors.New("未找到")
|
||||
err = errors.New("未找到客户端")
|
||||
return
|
||||
}
|
||||
func (s *Csv) GetClientIdByVkey(vkey string) (id int, err error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
for _, v := range s.Clients {
|
||||
if crypt.Md5(v.VerifyKey) == vkey {
|
||||
id = v.Id
|
||||
return
|
||||
}
|
||||
}
|
||||
err = errors.New("未找到客户端")
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Csv) GetHostById(id int) (h *Host, err error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
for _, v := range s.Hosts {
|
||||
if v.Id == id {
|
||||
h = v
|
||||
return
|
||||
}
|
||||
}
|
||||
err = errors.New("The host could not be parsed")
|
||||
return
|
||||
}
|
||||
|
||||
//get key by host from x
|
||||
func (s *Csv) GetInfoByHost(host string, r *http.Request) (h *Host, err error) {
|
||||
var hosts []*Host
|
||||
//Handling Ported Access
|
||||
host = common.GetIpByAddr(host)
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
for _, v := range s.Hosts {
|
||||
if v.IsClose {
|
||||
continue
|
||||
}
|
||||
//Remove http(s) http(s)://a.proxy.com
|
||||
//*.proxy.com *.a.proxy.com Do some pan-parsing
|
||||
tmp := strings.Replace(v.Host, "*", `\w+?`, -1)
|
||||
var re *regexp.Regexp
|
||||
if re, err = regexp.Compile(tmp); err != nil {
|
||||
return
|
||||
}
|
||||
if len(re.FindAllString(host, -1)) > 0 && (v.Scheme == "all" || v.Scheme == r.URL.Scheme) {
|
||||
//URL routing
|
||||
hosts = append(hosts, v)
|
||||
}
|
||||
}
|
||||
for _, v := range hosts {
|
||||
//If not set, default matches all
|
||||
if v.Location == "" {
|
||||
v.Location = "/"
|
||||
}
|
||||
if strings.Index(r.RequestURI, v.Location) == 0 {
|
||||
if h == nil || (len(v.Location) < len(h.Location)) {
|
||||
h = v
|
||||
}
|
||||
}
|
||||
}
|
||||
if h != nil {
|
||||
return
|
||||
}
|
||||
err = errors.New("The host could not be parsed")
|
||||
return
|
||||
}
|
||||
func (s *Csv) StoreClientsToCsv() {
|
||||
// 创建文件
|
||||
csvFile, err := os.Create(filepath.Join(s.RunPath, "conf", "clients.csv"))
|
||||
if err != nil {
|
||||
lg.Fatalln(err.Error())
|
||||
logs.Error(err.Error())
|
||||
}
|
||||
defer csvFile.Close()
|
||||
writer := csv.NewWriter(csvFile)
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
for _, client := range s.Clients {
|
||||
if client.NoStore {
|
||||
continue
|
||||
}
|
||||
record := []string{
|
||||
strconv.Itoa(client.Id),
|
||||
client.VerifyKey,
|
||||
@@ -406,13 +594,14 @@ func (s *Csv) StoreClientsToCsv() {
|
||||
client.Cnf.U,
|
||||
client.Cnf.P,
|
||||
common.GetStrByBool(client.Cnf.Crypt),
|
||||
client.Cnf.Compress,
|
||||
strconv.FormatBool(client.Cnf.Compress),
|
||||
strconv.Itoa(client.RateLimit),
|
||||
strconv.Itoa(int(client.Flow.FlowLimit)),
|
||||
strconv.Itoa(int(client.MaxConn)),
|
||||
}
|
||||
err := writer.Write(record)
|
||||
if err != nil {
|
||||
lg.Fatalln(err.Error())
|
||||
logs.Error(err.Error())
|
||||
}
|
||||
}
|
||||
writer.Flush()
|
||||
|
||||
+138
-37
@@ -2,8 +2,10 @@ package file
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
"github.com/pkg/errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Flow struct {
|
||||
@@ -13,7 +15,7 @@ type Flow struct {
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func (s *Flow) Add(in, out int) {
|
||||
func (s *Flow) Add(in, out int64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.InletFlow += int64(in)
|
||||
@@ -31,74 +33,173 @@ type Client struct {
|
||||
RateLimit int //速度限制 /kb
|
||||
Flow *Flow //流量
|
||||
Rate *rate.Rate //速度控制
|
||||
NoStore bool
|
||||
NoDisplay bool
|
||||
MaxConn int //客户端最大连接数
|
||||
NowConn int //当前连接数
|
||||
id int
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func (s *Client) GetId() int {
|
||||
func NewClient(vKey string, noStore bool, noDisplay bool) *Client {
|
||||
return &Client{
|
||||
Cnf: new(Config),
|
||||
Id: 0,
|
||||
VerifyKey: vKey,
|
||||
Addr: "",
|
||||
Remark: "",
|
||||
Status: true,
|
||||
IsConnect: false,
|
||||
RateLimit: 0,
|
||||
Flow: new(Flow),
|
||||
Rate: nil,
|
||||
NoStore: noStore,
|
||||
RWMutex: sync.RWMutex{},
|
||||
NoDisplay: noDisplay,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Client) CutConn() {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.id++
|
||||
return s.id
|
||||
s.NowConn++
|
||||
}
|
||||
|
||||
func (s *Client) AddConn() {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.NowConn--
|
||||
}
|
||||
|
||||
func (s *Client) GetConn() bool {
|
||||
if s.MaxConn == 0 || s.NowConn < s.MaxConn {
|
||||
s.CutConn()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//modify the hosts and the tunnels by health information
|
||||
func (s *Client) ModifyTarget() {
|
||||
|
||||
}
|
||||
|
||||
func (s *Client) HasTunnel(t *Tunnel) bool {
|
||||
GetCsvDb().Lock()
|
||||
defer GetCsvDb().Unlock()
|
||||
for _, v := range GetCsvDb().Tasks {
|
||||
if v.Client.Id == s.Id && v.Port == t.Port {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Client) HasHost(h *Host) bool {
|
||||
GetCsvDb().Lock()
|
||||
defer GetCsvDb().Unlock()
|
||||
for _, v := range GetCsvDb().Hosts {
|
||||
if v.Client.Id == s.Id && v.Host == h.Host && h.Location == v.Location {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type Tunnel struct {
|
||||
Id int //Id
|
||||
TcpPort int //服务端监听端口
|
||||
Mode string //启动方式
|
||||
Target string //目标
|
||||
Status bool //是否开启
|
||||
Client *Client //所属客户端id
|
||||
Flow *Flow
|
||||
Config *Config
|
||||
UseClientCnf bool //是否继承客户端配置
|
||||
Remark string //备注
|
||||
Id int //Id
|
||||
Port int //服务端监听端口
|
||||
Mode string //启动方式
|
||||
Target string //目标
|
||||
TargetArr []string //目标
|
||||
Status bool //设置是否开启
|
||||
RunStatus bool //当前运行状态
|
||||
Client *Client //所属客户端id
|
||||
Ports string //客户端与服务端传递
|
||||
Flow *Flow
|
||||
Password string //私密模式密码,唯一
|
||||
Remark string //备注
|
||||
TargetAddr string
|
||||
NoStore bool
|
||||
LocalPath string
|
||||
StripPre string
|
||||
NowIndex int
|
||||
Health
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
type Health struct {
|
||||
HealthCheckTimeout int
|
||||
HealthMaxFail int
|
||||
HealthCheckInterval int
|
||||
HealthNextTime time.Time
|
||||
HealthMap map[string]int
|
||||
HttpHealthUrl string
|
||||
HealthRemoveArr []string
|
||||
HealthCheckType string
|
||||
HealthCheckTarget string
|
||||
}
|
||||
|
||||
func (s *Tunnel) GetRandomTarget() (string, error) {
|
||||
if s.TargetArr == nil {
|
||||
s.TargetArr = strings.Split(s.Target, "\n")
|
||||
}
|
||||
if len(s.TargetArr) == 1 {
|
||||
return s.TargetArr[0], nil
|
||||
}
|
||||
if len(s.TargetArr) == 0 {
|
||||
return "", errors.New("all inward-bending targets are offline")
|
||||
}
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
if s.NowIndex >= len(s.TargetArr)-1 {
|
||||
s.NowIndex = -1
|
||||
}
|
||||
s.NowIndex++
|
||||
return s.TargetArr[s.NowIndex], nil
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
U string //socks5验证用户名
|
||||
P string //socks5验证密码
|
||||
Compress string //压缩方式
|
||||
Crypt bool //是否加密
|
||||
CompressEncode int //加密方式
|
||||
CompressDecode int //解密方式
|
||||
U string //socks5验证用户名
|
||||
P string //socks5验证密码
|
||||
Compress bool //压缩方式
|
||||
Crypt bool //是否加密
|
||||
}
|
||||
|
||||
type Host struct {
|
||||
Id int
|
||||
Host string //启动方式
|
||||
Target string //目标
|
||||
HeaderChange string //host修改
|
||||
HostChange string //host修改
|
||||
Location string //url 路由
|
||||
Flow *Flow
|
||||
Client *Client
|
||||
Remark string //备注
|
||||
NowIndex int
|
||||
TargetArr []string
|
||||
NoStore bool
|
||||
Scheme string //http https all
|
||||
IsClose bool
|
||||
Health
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func (s *Host) GetRandomTarget() string {
|
||||
func (s *Host) GetRandomTarget() (string, error) {
|
||||
if s.TargetArr == nil {
|
||||
s.TargetArr = strings.Split(s.Target, "\n")
|
||||
}
|
||||
if len(s.TargetArr) == 1 {
|
||||
return s.TargetArr[0], nil
|
||||
}
|
||||
if len(s.TargetArr) == 0 {
|
||||
return "", errors.New("all inward-bending targets are offline")
|
||||
}
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
if s.NowIndex >= len(s.TargetArr)-1 {
|
||||
s.NowIndex = 0
|
||||
} else {
|
||||
s.NowIndex++
|
||||
}
|
||||
return s.TargetArr[s.NowIndex]
|
||||
}
|
||||
|
||||
//深拷贝Config
|
||||
func DeepCopyConfig(c *Config) *Config {
|
||||
return &Config{
|
||||
U: c.U,
|
||||
P: c.P,
|
||||
Compress: c.Compress,
|
||||
Crypt: c.Crypt,
|
||||
CompressEncode: c.CompressEncode,
|
||||
CompressDecode: c.CompressDecode,
|
||||
s.NowIndex = -1
|
||||
}
|
||||
s.NowIndex++
|
||||
return s.TargetArr[s.NowIndex], nil
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ func InstallNps() {
|
||||
log.Println("You can copy executable files to any directory and start working with nps.exe test|start|stop|restart|status")
|
||||
}
|
||||
}
|
||||
func MkidrDirAll(path string, v ... string) {
|
||||
func MkidrDirAll(path string, v ...string) {
|
||||
for _, item := range v {
|
||||
if err := os.MkdirAll(filepath.Join(path, item), 0755); err != nil {
|
||||
log.Fatalf("Failed to create directory %s error:%s", path, err.Error())
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
package lg
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
var Log *log.Logger
|
||||
|
||||
func InitLogFile(f string, isStdout bool, logPath string) {
|
||||
var prefix string
|
||||
if !isStdout {
|
||||
logFile, err := os.OpenFile(filepath.Join(logPath, f+"_log.txt"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
|
||||
if err != nil {
|
||||
log.Fatalln("open file error !", err)
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
prefix = "\r\n"
|
||||
}
|
||||
Log = log.New(logFile, prefix, log.Ldate|log.Ltime)
|
||||
} else {
|
||||
Log = log.New(os.Stdout, "", log.Ldate|log.Ltime)
|
||||
}
|
||||
}
|
||||
|
||||
func Println(v ...interface{}) {
|
||||
Log.Println(v ...)
|
||||
}
|
||||
|
||||
func Fatalln(v ...interface{}) {
|
||||
Log.SetPrefix("error ")
|
||||
Log.Fatalln(v ...)
|
||||
Log.SetPrefix("")
|
||||
}
|
||||
func Fatalf(format string, v ...interface{}) {
|
||||
Log.SetPrefix("error ")
|
||||
Log.Fatalf(format, v...)
|
||||
Log.SetPrefix("")
|
||||
}
|
||||
|
||||
func Printf(format string, v ...interface{}) {
|
||||
Log.Printf(format, v...)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
)
|
||||
|
||||
//write bytes with int32 length
|
||||
func WriteLenBytes(buf []byte, w io.Writer) (int, error) {
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
if err := binary.Write(raw, binary.LittleEndian, int32(len(buf))); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := binary.Write(raw, binary.LittleEndian, buf); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return w.Write(raw.Bytes())
|
||||
}
|
||||
|
||||
//read bytes by length
|
||||
func ReadLenBytes(buf []byte, r io.Reader) (int, error) {
|
||||
var l int32
|
||||
var err error
|
||||
if binary.Read(r, binary.LittleEndian, &l) != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err = io.ReadFull(r, buf[:l]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(l), nil
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type conn struct {
|
||||
net.Conn
|
||||
getStatusCh chan struct{}
|
||||
connStatusOkCh chan struct{}
|
||||
connStatusFailCh chan struct{}
|
||||
readTimeOut time.Time
|
||||
writeTimeOut time.Time
|
||||
readBuffer []byte
|
||||
startRead int //now read position
|
||||
endRead int //now end read
|
||||
readFlag bool
|
||||
readCh chan struct{}
|
||||
waitQueue *sliceEntry
|
||||
stopWrite bool
|
||||
connId int32
|
||||
isClose bool
|
||||
readWait bool
|
||||
hasWrite int
|
||||
mux *Mux
|
||||
}
|
||||
|
||||
var connPool = sync.Pool{}
|
||||
|
||||
func NewConn(connId int32, mux *Mux) *conn {
|
||||
c := &conn{
|
||||
readCh: make(chan struct{}),
|
||||
getStatusCh: make(chan struct{}),
|
||||
connStatusOkCh: make(chan struct{}),
|
||||
connStatusFailCh: make(chan struct{}),
|
||||
waitQueue: NewQueue(),
|
||||
connId: connId,
|
||||
mux: mux,
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (s *conn) Read(buf []byte) (n int, err error) {
|
||||
if s.isClose || buf == nil {
|
||||
return 0, errors.New("the conn has closed")
|
||||
}
|
||||
if s.endRead-s.startRead == 0 { //read finish or start
|
||||
if s.waitQueue.Size() == 0 {
|
||||
s.readWait = true
|
||||
if t := s.readTimeOut.Sub(time.Now()); t > 0 {
|
||||
timer := time.NewTimer(t)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
s.readWait = false
|
||||
return 0, errors.New("read timeout")
|
||||
case <-s.readCh:
|
||||
}
|
||||
} else {
|
||||
<-s.readCh
|
||||
}
|
||||
}
|
||||
if s.isClose { //If the connection is closed instead of continuing command
|
||||
return 0, errors.New("the conn has closed")
|
||||
}
|
||||
if node, err := s.waitQueue.Pop(); err != nil {
|
||||
s.Close()
|
||||
return 0, io.EOF
|
||||
} else {
|
||||
pool.PutBufPoolCopy(s.readBuffer)
|
||||
s.readBuffer = node.val
|
||||
s.endRead = node.l
|
||||
s.startRead = 0
|
||||
}
|
||||
}
|
||||
if len(buf) < s.endRead-s.startRead {
|
||||
n = copy(buf, s.readBuffer[s.startRead:s.startRead+len(buf)])
|
||||
s.startRead += n
|
||||
} else {
|
||||
n = copy(buf, s.readBuffer[s.startRead:s.endRead])
|
||||
s.startRead += n
|
||||
s.mux.sendInfo(MUX_MSG_SEND_OK, s.connId, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *conn) Write(buf []byte) (int, error) {
|
||||
if s.isClose {
|
||||
return 0, errors.New("the conn has closed")
|
||||
}
|
||||
ch := make(chan struct{})
|
||||
go s.write(buf, ch)
|
||||
if t := s.writeTimeOut.Sub(time.Now()); t > 0 {
|
||||
timer := time.NewTimer(t)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
return 0, errors.New("write timeout")
|
||||
case <-ch:
|
||||
}
|
||||
} else {
|
||||
<-ch
|
||||
}
|
||||
if s.isClose {
|
||||
return 0, io.EOF
|
||||
}
|
||||
return len(buf), nil
|
||||
}
|
||||
func (s *conn) write(buf []byte, ch chan struct{}) {
|
||||
start := 0
|
||||
l := len(buf)
|
||||
for {
|
||||
if s.hasWrite > 50 {
|
||||
<-s.getStatusCh
|
||||
}
|
||||
s.hasWrite++
|
||||
if l-start > pool.PoolSizeCopy {
|
||||
s.mux.sendInfo(MUX_NEW_MSG, s.connId, buf[start:start+pool.PoolSizeCopy])
|
||||
start += pool.PoolSizeCopy
|
||||
} else {
|
||||
s.mux.sendInfo(MUX_NEW_MSG, s.connId, buf[start:l])
|
||||
break
|
||||
}
|
||||
}
|
||||
ch <- struct{}{}
|
||||
}
|
||||
|
||||
func (s *conn) Close() error {
|
||||
if s.isClose {
|
||||
return errors.New("the conn has closed")
|
||||
}
|
||||
times := 0
|
||||
retry:
|
||||
if s.waitQueue.Size() > 0 && times < 600 {
|
||||
time.Sleep(time.Millisecond * 100)
|
||||
times++
|
||||
goto retry
|
||||
}
|
||||
if s.isClose {
|
||||
return errors.New("the conn has closed")
|
||||
}
|
||||
s.isClose = true
|
||||
pool.PutBufPoolCopy(s.readBuffer)
|
||||
if s.readWait {
|
||||
s.readCh <- struct{}{}
|
||||
}
|
||||
s.waitQueue.Clear()
|
||||
s.mux.connMap.Delete(s.connId)
|
||||
if !s.mux.IsClose {
|
||||
s.mux.sendInfo(MUX_CONN_CLOSE, s.connId, nil)
|
||||
}
|
||||
connPool.Put(s)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *conn) LocalAddr() net.Addr {
|
||||
return s.mux.conn.LocalAddr()
|
||||
}
|
||||
|
||||
func (s *conn) RemoteAddr() net.Addr {
|
||||
return s.mux.conn.RemoteAddr()
|
||||
}
|
||||
|
||||
func (s *conn) SetDeadline(t time.Time) error {
|
||||
s.readTimeOut = t
|
||||
s.writeTimeOut = t
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *conn) SetReadDeadline(t time.Time) error {
|
||||
s.readTimeOut = t
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *conn) SetWriteDeadline(t time.Time) error {
|
||||
s.writeTimeOut = t
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type connMap struct {
|
||||
connMap map[int32]*conn
|
||||
closeCh chan struct{}
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func NewConnMap() *connMap {
|
||||
connMap := &connMap{
|
||||
connMap: make(map[int32]*conn),
|
||||
closeCh: make(chan struct{}),
|
||||
}
|
||||
go connMap.clean()
|
||||
return connMap
|
||||
}
|
||||
|
||||
func (s *connMap) Get(id int32) (*conn, bool) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
if v, ok := s.connMap[id]; ok && v != nil {
|
||||
return v, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func (s *connMap) Set(id int32, v *conn) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.connMap[id] = v
|
||||
}
|
||||
|
||||
func (s *connMap) Close() {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
for _, v := range s.connMap {
|
||||
v.isClose = true
|
||||
}
|
||||
s.closeCh <- struct{}{}
|
||||
}
|
||||
|
||||
func (s *connMap) Delete(id int32) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
delete(s.connMap, id)
|
||||
}
|
||||
|
||||
func (s *connMap) clean() {
|
||||
ticker := time.NewTimer(time.Minute * 1)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
s.Lock()
|
||||
for _, v := range s.connMap {
|
||||
if v.isClose {
|
||||
delete(s.connMap, v.connId)
|
||||
}
|
||||
}
|
||||
s.Unlock()
|
||||
case <-s.closeCh:
|
||||
ticker.Stop()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"math"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
MUX_PING_FLAG int32 = iota
|
||||
MUX_NEW_CONN_OK
|
||||
MUX_NEW_CONN_Fail
|
||||
MUX_NEW_MSG
|
||||
MUX_MSG_SEND_OK
|
||||
MUX_NEW_CONN
|
||||
MUX_PING
|
||||
MUX_CONN_CLOSE
|
||||
MUX_PING_RETURN
|
||||
)
|
||||
|
||||
type Mux struct {
|
||||
net.Listener
|
||||
conn net.Conn
|
||||
connMap *connMap
|
||||
newConnCh chan *conn
|
||||
id int32
|
||||
closeChan chan struct{}
|
||||
IsClose bool
|
||||
pingOk int
|
||||
connType string
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
func NewMux(c net.Conn, connType string) *Mux {
|
||||
m := &Mux{
|
||||
conn: c,
|
||||
connMap: NewConnMap(),
|
||||
id: 0,
|
||||
closeChan: make(chan struct{}),
|
||||
newConnCh: make(chan *conn),
|
||||
IsClose: false,
|
||||
connType: connType,
|
||||
}
|
||||
//read session by flag
|
||||
go m.readSession()
|
||||
//ping
|
||||
go m.ping()
|
||||
return m
|
||||
}
|
||||
|
||||
func (s *Mux) NewConn() (*conn, error) {
|
||||
if s.IsClose {
|
||||
return nil, errors.New("the mux has closed")
|
||||
}
|
||||
conn := NewConn(s.getId(), s)
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
if err := binary.Write(raw, binary.LittleEndian, MUX_NEW_CONN); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := binary.Write(raw, binary.LittleEndian, conn.connId); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
//it must be set before send
|
||||
s.connMap.Set(conn.connId, conn)
|
||||
if _, err := s.conn.Write(raw.Bytes()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
//set a timer timeout 30 second
|
||||
timer := time.NewTimer(time.Second * 30)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-conn.connStatusOkCh:
|
||||
return conn, nil
|
||||
case <-conn.connStatusFailCh:
|
||||
case <-timer.C:
|
||||
}
|
||||
return nil, errors.New("create connection fail,the server refused the connection")
|
||||
}
|
||||
|
||||
func (s *Mux) Accept() (net.Conn, error) {
|
||||
if s.IsClose {
|
||||
return nil, errors.New("accpet error,the conn has closed")
|
||||
}
|
||||
conn := <-s.newConnCh
|
||||
if conn == nil {
|
||||
return nil, errors.New("accpet error,the conn has closed")
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (s *Mux) Addr() net.Addr {
|
||||
return s.conn.LocalAddr()
|
||||
}
|
||||
|
||||
func (s *Mux) sendInfo(flag int32, id int32, content []byte) error {
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
binary.Write(raw, binary.LittleEndian, flag)
|
||||
binary.Write(raw, binary.LittleEndian, id)
|
||||
if content != nil && len(content) > 0 {
|
||||
binary.Write(raw, binary.LittleEndian, int32(len(content)))
|
||||
binary.Write(raw, binary.LittleEndian, content)
|
||||
}
|
||||
if _, err := s.conn.Write(raw.Bytes()); err != nil {
|
||||
s.Close()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Mux) ping() {
|
||||
go func() {
|
||||
ticker := time.NewTicker(time.Second * 1)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
}
|
||||
//Avoid going beyond the scope
|
||||
if (math.MaxInt32 - s.id) < 10000 {
|
||||
s.id = 0
|
||||
}
|
||||
if err := s.sendInfo(MUX_PING_FLAG, MUX_PING, nil); err != nil || (s.pingOk > 10 && s.connType == "kcp") {
|
||||
s.Close()
|
||||
break
|
||||
}
|
||||
s.pingOk++
|
||||
}
|
||||
}()
|
||||
select {
|
||||
case <-s.closeChan:
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Mux) readSession() {
|
||||
var buf []byte
|
||||
go func() {
|
||||
for {
|
||||
var flag, i int32
|
||||
var n int
|
||||
var err error
|
||||
if binary.Read(s.conn, binary.LittleEndian, &flag) == nil {
|
||||
if binary.Read(s.conn, binary.LittleEndian, &i) != nil {
|
||||
break
|
||||
}
|
||||
s.pingOk = 0
|
||||
switch flag {
|
||||
case MUX_NEW_CONN: //new conn
|
||||
conn := NewConn(i, s)
|
||||
s.connMap.Set(i, conn) //it has been set before send ok
|
||||
s.newConnCh <- conn
|
||||
s.sendInfo(MUX_NEW_CONN_OK, i, nil)
|
||||
continue
|
||||
case MUX_PING_FLAG: //ping
|
||||
s.sendInfo(MUX_PING_RETURN, MUX_PING, nil)
|
||||
continue
|
||||
case MUX_PING_RETURN:
|
||||
continue
|
||||
case MUX_NEW_MSG:
|
||||
buf = pool.GetBufPoolCopy()
|
||||
if n, err = ReadLenBytes(buf, s.conn); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if conn, ok := s.connMap.Get(i); ok && !conn.isClose {
|
||||
switch flag {
|
||||
case MUX_NEW_MSG: //new msg from remote conn
|
||||
//insert wait queue
|
||||
conn.waitQueue.Push(NewBufNode(buf, n))
|
||||
//judge len if >xxx ,send stop
|
||||
if conn.readWait {
|
||||
conn.readWait = false
|
||||
conn.readCh <- struct{}{}
|
||||
}
|
||||
case MUX_MSG_SEND_OK: //the remote has read
|
||||
select {
|
||||
case conn.getStatusCh <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
conn.hasWrite --
|
||||
case MUX_NEW_CONN_OK: //conn ok
|
||||
conn.connStatusOkCh <- struct{}{}
|
||||
case MUX_NEW_CONN_Fail:
|
||||
conn.connStatusFailCh <- struct{}{}
|
||||
case MUX_CONN_CLOSE: //close the connection
|
||||
go conn.Close()
|
||||
s.connMap.Delete(i)
|
||||
}
|
||||
} else if flag == MUX_NEW_MSG {
|
||||
pool.PutBufPoolCopy(buf)
|
||||
}
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
s.Close()
|
||||
}()
|
||||
select {
|
||||
case <-s.closeChan:
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Mux) Close() error {
|
||||
if s.IsClose {
|
||||
return errors.New("the mux has closed")
|
||||
}
|
||||
s.IsClose = true
|
||||
s.connMap.Close()
|
||||
select {
|
||||
case s.closeChan <- struct{}{}:
|
||||
}
|
||||
select {
|
||||
case s.closeChan <- struct{}{}:
|
||||
}
|
||||
close(s.newConnCh)
|
||||
return s.conn.Close()
|
||||
}
|
||||
|
||||
//get new connId as unique flag
|
||||
func (s *Mux) getId() int32 {
|
||||
return atomic.AddInt32(&s.id, 1)
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
_ "net/http/pprof"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var conn1 net.Conn
|
||||
var conn2 net.Conn
|
||||
|
||||
func TestNewMux(t *testing.T) {
|
||||
go func() {
|
||||
http.ListenAndServe("0.0.0.0:8889", nil)
|
||||
}()
|
||||
logs.EnableFuncCallDepth(true)
|
||||
logs.SetLogFuncCallDepth(3)
|
||||
server()
|
||||
client()
|
||||
time.Sleep(time.Second * 3)
|
||||
go func() {
|
||||
m2 := NewMux(conn2)
|
||||
for {
|
||||
c, err := m2.Accept()
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
go func(c net.Conn) {
|
||||
c2, err := net.Dial("tcp", "10.1.50.196:4000")
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
go common.CopyBuffer(c2, c)
|
||||
common.CopyBuffer(c, c2)
|
||||
c.Close()
|
||||
c2.Close()
|
||||
}(c)
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
m1 := NewMux(conn1)
|
||||
l, err := net.Listen("tcp", "127.0.0.1:7777")
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
for {
|
||||
conn, err := l.Accept()
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
go func(conn net.Conn) {
|
||||
tmpCpnn, err := m1.NewConn()
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
go common.CopyBuffer(tmpCpnn, conn)
|
||||
common.CopyBuffer(conn, tmpCpnn)
|
||||
conn.Close()
|
||||
tmpCpnn.Close()
|
||||
}(conn)
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
}
|
||||
|
||||
func server() {
|
||||
var err error
|
||||
l, err := net.Listen("tcp", "127.0.0.1:9999")
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
go func() {
|
||||
conn1, err = l.Accept()
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
}()
|
||||
return
|
||||
}
|
||||
|
||||
func client() {
|
||||
var err error
|
||||
conn2, err = net.Dial("tcp", "127.0.0.1:9999")
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewConn(t *testing.T) {
|
||||
buf := pool.GetBufPoolCopy()
|
||||
logs.Warn(len(buf), cap(buf))
|
||||
//b := pool.GetBufPoolCopy()
|
||||
//b[0] = 1
|
||||
//b[1] = 2
|
||||
//b[2] = 3
|
||||
b := []byte{1, 2, 3}
|
||||
logs.Warn(copy(buf[:3], b), len(buf), cap(buf))
|
||||
logs.Warn(len(buf), buf[0])
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
type PortConn struct {
|
||||
Conn net.Conn
|
||||
rs []byte
|
||||
start int
|
||||
}
|
||||
|
||||
func newPortConn(conn net.Conn, rs []byte) *PortConn {
|
||||
return &PortConn{
|
||||
Conn: conn,
|
||||
rs: rs,
|
||||
}
|
||||
}
|
||||
|
||||
func (pConn *PortConn) Read(b []byte) (n int, err error) {
|
||||
if len(b) < len(pConn.rs)-pConn.start {
|
||||
defer func() {
|
||||
pConn.start = pConn.start + len(b)
|
||||
}()
|
||||
return copy(b, pConn.rs), nil
|
||||
}
|
||||
if pConn.start < len(pConn.rs) {
|
||||
defer func() {
|
||||
pConn.start = len(pConn.rs)
|
||||
}()
|
||||
return copy(b, pConn.rs[pConn.start:]), nil
|
||||
}
|
||||
return pConn.Conn.Read(b)
|
||||
}
|
||||
|
||||
func (pConn *PortConn) Write(b []byte) (n int, err error) {
|
||||
return pConn.Conn.Write(b)
|
||||
}
|
||||
|
||||
func (pConn *PortConn) Close() error {
|
||||
return pConn.Conn.Close()
|
||||
}
|
||||
|
||||
func (pConn *PortConn) LocalAddr() net.Addr {
|
||||
return pConn.Conn.LocalAddr()
|
||||
}
|
||||
|
||||
func (pConn *PortConn) RemoteAddr() net.Addr {
|
||||
return pConn.Conn.RemoteAddr()
|
||||
}
|
||||
|
||||
func (pConn *PortConn) SetDeadline(t time.Time) error {
|
||||
return pConn.Conn.SetDeadline(t)
|
||||
}
|
||||
|
||||
func (pConn *PortConn) SetReadDeadline(t time.Time) error {
|
||||
return pConn.Conn.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
func (pConn *PortConn) SetWriteDeadline(t time.Time) error {
|
||||
return pConn.Conn.SetWriteDeadline(t)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
)
|
||||
|
||||
type PortListener struct {
|
||||
net.Listener
|
||||
connCh chan *PortConn
|
||||
addr net.Addr
|
||||
isClose bool
|
||||
}
|
||||
|
||||
func NewPortListener(connCh chan *PortConn, addr net.Addr) *PortListener {
|
||||
return &PortListener{
|
||||
connCh: connCh,
|
||||
addr: addr,
|
||||
}
|
||||
}
|
||||
|
||||
func (pListener *PortListener) Accept() (net.Conn, error) {
|
||||
if pListener.isClose {
|
||||
return nil, errors.New("the listener has closed")
|
||||
}
|
||||
conn := <-pListener.connCh
|
||||
if conn != nil {
|
||||
return conn, nil
|
||||
}
|
||||
return nil, errors.New("the listener has closed")
|
||||
}
|
||||
|
||||
func (pListener *PortListener) Close() error {
|
||||
//close
|
||||
if pListener.isClose {
|
||||
return errors.New("the listener has closed")
|
||||
}
|
||||
pListener.isClose = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pListener *PortListener) Addr() net.Addr {
|
||||
return pListener.addr
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
// This module is used for port reuse
|
||||
// Distinguish client, web manager , HTTP and HTTPS according to the difference of protocol
|
||||
package mux
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"github.com/pkg/errors"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
HTTP_GET = 716984
|
||||
HTTP_POST = 807983
|
||||
HTTP_HEAD = 726965
|
||||
HTTP_PUT = 808585
|
||||
HTTP_DELETE = 686976
|
||||
HTTP_CONNECT = 677978
|
||||
HTTP_OPTIONS = 798084
|
||||
HTTP_TRACE = 848265
|
||||
CLIENT = 848384
|
||||
ACCEPT_TIME_OUT = 10
|
||||
)
|
||||
|
||||
type PortMux struct {
|
||||
net.Listener
|
||||
port int
|
||||
isClose bool
|
||||
managerHost string
|
||||
clientConn chan *PortConn
|
||||
httpConn chan *PortConn
|
||||
httpsConn chan *PortConn
|
||||
managerConn chan *PortConn
|
||||
}
|
||||
|
||||
func NewPortMux(port int, managerHost string) *PortMux {
|
||||
pMux := &PortMux{
|
||||
managerHost: managerHost,
|
||||
port: port,
|
||||
clientConn: make(chan *PortConn),
|
||||
httpConn: make(chan *PortConn),
|
||||
httpsConn: make(chan *PortConn),
|
||||
managerConn: make(chan *PortConn),
|
||||
}
|
||||
pMux.Start()
|
||||
return pMux
|
||||
}
|
||||
|
||||
func (pMux *PortMux) Start() error {
|
||||
// Port multiplexing is based on TCP only
|
||||
tcpAddr, err := net.ResolveTCPAddr("tcp", "0.0.0.0:"+strconv.Itoa(pMux.port))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pMux.Listener, err = net.ListenTCP("tcp", tcpAddr)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
go func() {
|
||||
for {
|
||||
conn, err := pMux.Listener.Accept()
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
//close
|
||||
pMux.Close()
|
||||
}
|
||||
go pMux.process(conn)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pMux *PortMux) process(conn net.Conn) {
|
||||
// Recognition according to different signs
|
||||
// read 3 byte
|
||||
buf := make([]byte, 3)
|
||||
if n, err := io.ReadFull(conn, buf); err != nil || n != 3 {
|
||||
return
|
||||
}
|
||||
var ch chan *PortConn
|
||||
var rs []byte
|
||||
var buffer bytes.Buffer
|
||||
switch common.BytesToNum(buf) {
|
||||
case HTTP_CONNECT, HTTP_DELETE, HTTP_GET, HTTP_HEAD, HTTP_OPTIONS, HTTP_POST, HTTP_PUT, HTTP_TRACE: //http and manager
|
||||
buffer.Reset()
|
||||
r := bufio.NewReader(conn)
|
||||
buffer.Write(buf)
|
||||
for {
|
||||
b, _, err := r.ReadLine()
|
||||
if err != nil {
|
||||
logs.Warn("read line error", err.Error())
|
||||
conn.Close()
|
||||
break
|
||||
}
|
||||
buffer.Write(b)
|
||||
buffer.Write([]byte("\r\n"))
|
||||
if strings.Index(string(b), "Host:") == 0 || strings.Index(string(b), "host:") == 0 {
|
||||
// Remove host and space effects
|
||||
str := strings.Replace(string(b), "Host:", "", -1)
|
||||
str = strings.Replace(str, "host:", "", -1)
|
||||
str = strings.TrimSpace(str)
|
||||
// Determine whether it is the same as the manager domain name
|
||||
if common.GetIpByAddr(str) == pMux.managerHost {
|
||||
ch = pMux.managerConn
|
||||
} else {
|
||||
ch = pMux.httpConn
|
||||
}
|
||||
b, _ := r.Peek(r.Buffered())
|
||||
buffer.Write(b)
|
||||
rs = buffer.Bytes()
|
||||
break
|
||||
}
|
||||
}
|
||||
case CLIENT: // client connection
|
||||
ch = pMux.clientConn
|
||||
default: // https
|
||||
ch = pMux.httpsConn
|
||||
}
|
||||
if len(rs) == 0 {
|
||||
rs = buf
|
||||
}
|
||||
timer := time.NewTimer(ACCEPT_TIME_OUT)
|
||||
select {
|
||||
case <-timer.C:
|
||||
case ch <- newPortConn(conn, rs):
|
||||
}
|
||||
}
|
||||
|
||||
func (pMux *PortMux) Close() error {
|
||||
if pMux.isClose {
|
||||
return errors.New("the port mux has closed")
|
||||
}
|
||||
pMux.isClose = true
|
||||
close(pMux.clientConn)
|
||||
close(pMux.httpsConn)
|
||||
close(pMux.httpConn)
|
||||
close(pMux.managerConn)
|
||||
return pMux.Listener.Close()
|
||||
}
|
||||
|
||||
func (pMux *PortMux) GetClientListener() net.Listener {
|
||||
return NewPortListener(pMux.clientConn, pMux.Listener.Addr())
|
||||
}
|
||||
|
||||
func (pMux *PortMux) GetHttpListener() net.Listener {
|
||||
return NewPortListener(pMux.httpConn, pMux.Listener.Addr())
|
||||
}
|
||||
|
||||
func (pMux *PortMux) GetHttpsListener() net.Listener {
|
||||
return NewPortListener(pMux.httpsConn, pMux.Listener.Addr())
|
||||
}
|
||||
|
||||
func (pMux *PortMux) GetManagerListener() net.Listener {
|
||||
return NewPortListener(pMux.managerConn, pMux.Listener.Addr())
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestPortMux_Close(t *testing.T) {
|
||||
logs.Reset()
|
||||
logs.EnableFuncCallDepth(true)
|
||||
logs.SetLogFuncCallDepth(3)
|
||||
|
||||
pMux := NewPortMux(8888,"Ds")
|
||||
go func() {
|
||||
if pMux.Start() != nil {
|
||||
logs.Warn("Error")
|
||||
}
|
||||
}()
|
||||
time.Sleep(time.Second * 3)
|
||||
go func() {
|
||||
l := pMux.GetHttpListener()
|
||||
conn, err := l.Accept()
|
||||
logs.Warn(conn, err)
|
||||
}()
|
||||
go func() {
|
||||
l := pMux.GetHttpListener()
|
||||
conn, err := l.Accept()
|
||||
logs.Warn(conn, err)
|
||||
}()
|
||||
go func() {
|
||||
l := pMux.GetHttpListener()
|
||||
conn, err := l.Accept()
|
||||
logs.Warn(conn, err)
|
||||
}()
|
||||
l := pMux.GetHttpListener()
|
||||
conn, err := l.Accept()
|
||||
logs.Warn(conn, err)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Element *bufNode
|
||||
|
||||
type bufNode struct {
|
||||
val []byte //buf value
|
||||
l int //length
|
||||
}
|
||||
|
||||
func NewBufNode(buf []byte, l int) *bufNode {
|
||||
return &bufNode{
|
||||
val: buf,
|
||||
l: l,
|
||||
}
|
||||
}
|
||||
|
||||
type Queue interface {
|
||||
Push(e Element) //向队列中添加元素
|
||||
Pop() Element //移除队列中最前面的元素
|
||||
Clear() bool //清空队列
|
||||
Size() int //获取队列的元素个数
|
||||
IsEmpty() bool //判断队列是否是空
|
||||
}
|
||||
|
||||
type sliceEntry struct {
|
||||
element []Element
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
func NewQueue() *sliceEntry {
|
||||
return &sliceEntry{}
|
||||
}
|
||||
|
||||
//向队列中添加元素
|
||||
func (entry *sliceEntry) Push(e Element) {
|
||||
entry.Lock()
|
||||
defer entry.Unlock()
|
||||
entry.element = append(entry.element, e)
|
||||
}
|
||||
|
||||
//移除队列中最前面的额元素
|
||||
func (entry *sliceEntry) Pop() (Element, error) {
|
||||
if entry.IsEmpty() {
|
||||
return nil, errors.New("queue is empty!")
|
||||
}
|
||||
entry.Lock()
|
||||
defer entry.Unlock()
|
||||
firstElement := entry.element[0]
|
||||
entry.element = entry.element[1:]
|
||||
return firstElement, nil
|
||||
}
|
||||
|
||||
func (entry *sliceEntry) Clear() bool {
|
||||
entry.Lock()
|
||||
defer entry.Unlock()
|
||||
if entry.IsEmpty() {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < entry.Size(); i++ {
|
||||
pool.PutBufPoolCopy(entry.element[i].val)
|
||||
entry.element[i] = nil
|
||||
}
|
||||
entry.element = nil
|
||||
return true
|
||||
}
|
||||
|
||||
func (entry *sliceEntry) Size() int {
|
||||
return len(entry.element)
|
||||
}
|
||||
|
||||
func (entry *sliceEntry) IsEmpty() bool {
|
||||
if len(entry.element) == 0 {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
+25
-9
@@ -7,7 +7,7 @@ import (
|
||||
const PoolSize = 64 * 1024
|
||||
const PoolSizeSmall = 100
|
||||
const PoolSizeUdp = 1472
|
||||
const PoolSizeCopy = 32 * 1024
|
||||
const PoolSizeCopy = 32 << 10
|
||||
|
||||
var BufPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
@@ -32,18 +32,34 @@ var BufPoolSmall = sync.Pool{
|
||||
}
|
||||
var BufPoolCopy = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, PoolSizeCopy)
|
||||
buf := make([]byte, PoolSizeCopy)
|
||||
return &buf
|
||||
},
|
||||
}
|
||||
|
||||
func PutBufPoolCopy(buf []byte) {
|
||||
if cap(buf) == PoolSizeCopy {
|
||||
BufPoolCopy.Put(buf[:PoolSizeCopy])
|
||||
}
|
||||
}
|
||||
|
||||
func PutBufPoolUdp(buf []byte) {
|
||||
if cap(buf) == PoolSizeUdp {
|
||||
BufPoolUdp.Put(buf[:PoolSizeUdp])
|
||||
}
|
||||
}
|
||||
|
||||
func PutBufPoolCopy(buf []byte) {
|
||||
if cap(buf) == PoolSizeCopy {
|
||||
BufPoolCopy.Put(&buf)
|
||||
}
|
||||
}
|
||||
|
||||
func GetBufPoolCopy() ([]byte) {
|
||||
return (*BufPoolCopy.Get().(*[]byte))[:PoolSizeCopy]
|
||||
}
|
||||
|
||||
func PutBufPoolSmall(buf []byte) {
|
||||
if cap(buf) == PoolSizeSmall {
|
||||
BufPoolSmall.Put(buf[:PoolSizeSmall])
|
||||
}
|
||||
}
|
||||
|
||||
func PutBufPoolMax(buf []byte) {
|
||||
if cap(buf) == PoolSize {
|
||||
BufPoolMax.Put(buf[:PoolSize])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package sheap
|
||||
|
||||
type IntHeap []int64
|
||||
|
||||
func (h IntHeap) Len() int { return len(h) }
|
||||
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
|
||||
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
|
||||
|
||||
func (h *IntHeap) Push(x interface{}) {
|
||||
// Push and Pop use pointer receivers because they modify the slice's length,
|
||||
// not just its contents.
|
||||
*h = append(*h, x.(int64))
|
||||
}
|
||||
|
||||
func (h *IntHeap) Pop() interface{} {
|
||||
old := *h
|
||||
n := len(old)
|
||||
x := old[n-1]
|
||||
*h = old[0 : n-1]
|
||||
return x
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package version
|
||||
|
||||
const VERSION = "0.18.2"
|
||||
|
||||
// Compulsory minimum version, Minimum downward compatibility to this version
|
||||
func GetVersion() string {
|
||||
return "0.18.2"
|
||||
}
|
||||
-110
@@ -1,110 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/cnlh/nps/bridge"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
//server base struct
|
||||
type server struct {
|
||||
id int
|
||||
bridge *bridge.Bridge
|
||||
task *file.Tunnel
|
||||
config *file.Config
|
||||
errorContent []byte
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
func (s *server) FlowAdd(in, out int64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.task.Flow.ExportFlow += out
|
||||
s.task.Flow.InletFlow += in
|
||||
}
|
||||
|
||||
func (s *server) FlowAddHost(host *file.Host, in, out int64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
host.Flow.ExportFlow += out
|
||||
host.Flow.InletFlow += in
|
||||
}
|
||||
|
||||
//热更新配置
|
||||
func (s *server) ResetConfig() bool {
|
||||
//获取最新数据
|
||||
task, err := file.GetCsvDb().GetTask(s.task.Id)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if s.task.Client.Flow.FlowLimit > 0 && (s.task.Client.Flow.FlowLimit<<20) < (s.task.Client.Flow.ExportFlow+s.task.Client.Flow.InletFlow) {
|
||||
return false
|
||||
}
|
||||
s.task.UseClientCnf = task.UseClientCnf
|
||||
//使用客户端配置
|
||||
client, err := file.GetCsvDb().GetClient(s.task.Client.Id)
|
||||
if s.task.UseClientCnf {
|
||||
if err == nil {
|
||||
s.config.U = client.Cnf.U
|
||||
s.config.P = client.Cnf.P
|
||||
s.config.Compress = client.Cnf.Compress
|
||||
s.config.Crypt = client.Cnf.Crypt
|
||||
}
|
||||
} else {
|
||||
if err == nil {
|
||||
s.config.U = task.Config.U
|
||||
s.config.P = task.Config.P
|
||||
s.config.Compress = task.Config.Compress
|
||||
s.config.Crypt = task.Config.Crypt
|
||||
}
|
||||
}
|
||||
s.task.Client.Rate = client.Rate
|
||||
s.config.CompressDecode, s.config.CompressEncode = common.GetCompressType(s.config.Compress)
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *server) linkCopy(link *conn.Link, c *conn.Conn, rb []byte, tunnel *conn.Conn, flow *file.Flow) {
|
||||
if rb != nil {
|
||||
if _, err := tunnel.SendMsg(rb, link); err != nil {
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
flow.Add(len(rb), 0)
|
||||
}
|
||||
|
||||
buf := pool.BufPoolCopy.Get().([]byte)
|
||||
for {
|
||||
if n, err := c.Read(buf); err != nil {
|
||||
tunnel.SendMsg([]byte(common.IO_EOF), link)
|
||||
break
|
||||
} else {
|
||||
if _, err := tunnel.SendMsg(buf[:n], link); err != nil {
|
||||
c.Close()
|
||||
break
|
||||
}
|
||||
flow.Add(n, 0)
|
||||
}
|
||||
}
|
||||
pool.PutBufPoolCopy(buf)
|
||||
}
|
||||
|
||||
func (s *server) writeConnFail(c net.Conn) {
|
||||
c.Write([]byte(common.ConnectionFailBytes))
|
||||
c.Write(s.errorContent)
|
||||
}
|
||||
|
||||
//权限认证
|
||||
func (s *server) auth(r *http.Request, c *conn.Conn, u, p string) error {
|
||||
if u != "" && p != "" && !common.CheckAuth(r, u, p) {
|
||||
c.Write([]byte(common.UnauthorizedBytes))
|
||||
c.Close()
|
||||
return errors.New("401 Unauthorized")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package connection
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/mux"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
var pMux *mux.PortMux
|
||||
var bridgePort string
|
||||
var httpsPort string
|
||||
var httpPort string
|
||||
var webPort string
|
||||
|
||||
func InitConnectionService() {
|
||||
bridgePort = beego.AppConfig.String("bridge_port")
|
||||
httpsPort = beego.AppConfig.String("https_proxy_port")
|
||||
httpPort = beego.AppConfig.String("http_proxy_port")
|
||||
webPort = beego.AppConfig.String("web_port")
|
||||
|
||||
if httpPort == bridgePort || httpsPort == bridgePort || webPort == bridgePort {
|
||||
port, err := strconv.Atoi(bridgePort)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
pMux = mux.NewPortMux(port, beego.AppConfig.String("web_host"))
|
||||
}
|
||||
}
|
||||
|
||||
func GetBridgeListener(tp string) (net.Listener, error) {
|
||||
logs.Info("server start, the bridge type is %s, the bridge port is %s", tp, bridgePort)
|
||||
var p int
|
||||
var err error
|
||||
if p, err = strconv.Atoi(bridgePort); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if pMux != nil {
|
||||
return pMux.GetClientListener(), nil
|
||||
}
|
||||
return net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP(beego.AppConfig.String("bridge_ip")), p, ""})
|
||||
}
|
||||
|
||||
func GetHttpListener() (net.Listener, error) {
|
||||
if pMux != nil && httpPort == bridgePort {
|
||||
logs.Info("start http listener, port is", bridgePort)
|
||||
return pMux.GetHttpListener(), nil
|
||||
}
|
||||
logs.Info("start http listener, port is", httpPort)
|
||||
return getTcpListener("", httpPort)
|
||||
}
|
||||
|
||||
func GetHttpsListener() (net.Listener, error) {
|
||||
if pMux != nil && httpsPort == bridgePort {
|
||||
logs.Info("start https listener, port is", bridgePort)
|
||||
return pMux.GetHttpsListener(), nil
|
||||
}
|
||||
logs.Info("start https listener, port is", httpsPort)
|
||||
return getTcpListener("", httpsPort)
|
||||
}
|
||||
|
||||
func GetWebManagerListener() (net.Listener, error) {
|
||||
if pMux != nil && webPort == bridgePort {
|
||||
logs.Info("Web management start, access port is", bridgePort)
|
||||
return pMux.GetManagerListener(), nil
|
||||
}
|
||||
logs.Info("web management start, access port is", webPort)
|
||||
return getTcpListener(beego.AppConfig.String("web_ip"), webPort)
|
||||
}
|
||||
|
||||
func getTcpListener(ip, p string) (net.Listener, error) {
|
||||
port, err := strconv.Atoi(p)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
if ip == "" {
|
||||
ip = "0.0.0.0"
|
||||
}
|
||||
return net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP(ip), port, ""})
|
||||
}
|
||||
-179
@@ -1,179 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"github.com/cnlh/nps/lib/beego"
|
||||
"github.com/cnlh/nps/bridge"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type httpServer struct {
|
||||
server
|
||||
httpPort int //http端口
|
||||
httpsPort int //https监听端口
|
||||
pemPath string
|
||||
keyPath string
|
||||
stop chan bool
|
||||
}
|
||||
|
||||
func NewHttp(bridge *bridge.Bridge, c *file.Tunnel) *httpServer {
|
||||
httpPort, _ := beego.AppConfig.Int("httpProxyPort")
|
||||
httpsPort, _ := beego.AppConfig.Int("httpsProxyPort")
|
||||
pemPath := beego.AppConfig.String("pemPath")
|
||||
keyPath := beego.AppConfig.String("keyPath")
|
||||
return &httpServer{
|
||||
server: server{
|
||||
task: c,
|
||||
bridge: bridge,
|
||||
Mutex: sync.Mutex{},
|
||||
},
|
||||
httpPort: httpPort,
|
||||
httpsPort: httpsPort,
|
||||
pemPath: pemPath,
|
||||
keyPath: keyPath,
|
||||
stop: make(chan bool),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *httpServer) Start() error {
|
||||
var err error
|
||||
var http, https *http.Server
|
||||
if s.errorContent, err = common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "error.html")); err != nil {
|
||||
s.errorContent = []byte("easyProxy 404")
|
||||
}
|
||||
|
||||
if s.httpPort > 0 {
|
||||
http = s.NewServer(s.httpPort)
|
||||
go func() {
|
||||
lg.Println("启动http监听,端口为", s.httpPort)
|
||||
err := http.ListenAndServe()
|
||||
if err != nil {
|
||||
lg.Fatalln(err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
if s.httpsPort > 0 {
|
||||
if !common.FileExists(s.pemPath) {
|
||||
lg.Fatalf("ssl certFile文件%s不存在", s.pemPath)
|
||||
}
|
||||
if !common.FileExists(s.keyPath) {
|
||||
lg.Fatalf("ssl keyFile文件%s不存在", s.keyPath)
|
||||
}
|
||||
https = s.NewServer(s.httpsPort)
|
||||
go func() {
|
||||
lg.Println("启动https监听,端口为", s.httpsPort)
|
||||
err := https.ListenAndServeTLS(s.pemPath, s.keyPath)
|
||||
if err != nil {
|
||||
lg.Fatalln(err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
select {
|
||||
case <-s.stop:
|
||||
if http != nil {
|
||||
http.Close()
|
||||
}
|
||||
if https != nil {
|
||||
https.Close()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *httpServer) Close() {
|
||||
s.stop <- true
|
||||
}
|
||||
|
||||
func (s *httpServer) handleTunneling(w http.ResponseWriter, r *http.Request) {
|
||||
hijacker, ok := w.(http.Hijacker)
|
||||
if !ok {
|
||||
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
c, _, err := hijacker.Hijack()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
||||
}
|
||||
s.process(conn.NewConn(c), r)
|
||||
}
|
||||
|
||||
func (s *httpServer) process(c *conn.Conn, r *http.Request) {
|
||||
//多客户端域名代理
|
||||
var (
|
||||
isConn = true
|
||||
lk *conn.Link
|
||||
host *file.Host
|
||||
tunnel *conn.Conn
|
||||
err error
|
||||
)
|
||||
for {
|
||||
//首次获取conn
|
||||
if isConn {
|
||||
if host, err = GetInfoByHost(r.Host); err != nil {
|
||||
lg.Printf("the host %s is not found !", r.Host)
|
||||
break
|
||||
}
|
||||
//流量限制
|
||||
if host.Client.Flow.FlowLimit > 0 && (host.Client.Flow.FlowLimit<<20) < (host.Client.Flow.ExportFlow+host.Client.Flow.InletFlow) {
|
||||
break
|
||||
}
|
||||
host.Client.Cnf.CompressDecode, host.Client.Cnf.CompressEncode = common.GetCompressType(host.Client.Cnf.Compress)
|
||||
//权限控制
|
||||
if err = s.auth(r, c, host.Client.Cnf.U, host.Client.Cnf.P); err != nil {
|
||||
break
|
||||
}
|
||||
lk = conn.NewLink(host.Client.GetId(), common.CONN_TCP, host.GetRandomTarget(), host.Client.Cnf.CompressEncode, host.Client.Cnf.CompressDecode, host.Client.Cnf.Crypt, c, host.Flow, nil, host.Client.Rate, nil)
|
||||
if tunnel, err = s.bridge.SendLinkInfo(host.Client.Id, lk); err != nil {
|
||||
log.Println(err)
|
||||
break
|
||||
}
|
||||
isConn = false
|
||||
} else {
|
||||
r, err = http.ReadRequest(bufio.NewReader(c))
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
//根据设定,修改header和host
|
||||
common.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, c.Conn.RemoteAddr().String())
|
||||
b, err := httputil.DumpRequest(r, true)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
host.Flow.Add(len(b), 0)
|
||||
if _, err := tunnel.SendMsg(b, lk); err != nil {
|
||||
c.Close()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if isConn {
|
||||
s.writeConnFail(c.Conn)
|
||||
} else {
|
||||
tunnel.SendMsg([]byte(common.IO_EOF), lk)
|
||||
}
|
||||
|
||||
c.Close()
|
||||
|
||||
}
|
||||
|
||||
func (s *httpServer) NewServer(port int) *http.Server {
|
||||
return &http.Server{
|
||||
Addr: ":" + strconv.Itoa(port),
|
||||
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
s.handleTunneling(w, r)
|
||||
}),
|
||||
// Disable HTTP/2.
|
||||
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/cnlh/nps/bridge"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Service interface {
|
||||
Start() error
|
||||
Close() error
|
||||
}
|
||||
|
||||
//Server BaseServer struct
|
||||
type BaseServer struct {
|
||||
id int
|
||||
bridge *bridge.Bridge
|
||||
task *file.Tunnel
|
||||
errorContent []byte
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
func NewBaseServer(bridge *bridge.Bridge, task *file.Tunnel) *BaseServer {
|
||||
return &BaseServer{
|
||||
bridge: bridge,
|
||||
task: task,
|
||||
errorContent: nil,
|
||||
Mutex: sync.Mutex{},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *BaseServer) FlowAdd(in, out int64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.task.Flow.ExportFlow += out
|
||||
s.task.Flow.InletFlow += in
|
||||
}
|
||||
|
||||
func (s *BaseServer) FlowAddHost(host *file.Host, in, out int64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
host.Flow.ExportFlow += out
|
||||
host.Flow.InletFlow += in
|
||||
}
|
||||
|
||||
func (s *BaseServer) writeConnFail(c net.Conn) {
|
||||
c.Write([]byte(common.ConnectionFailBytes))
|
||||
c.Write(s.errorContent)
|
||||
}
|
||||
|
||||
//权限认证
|
||||
func (s *BaseServer) auth(r *http.Request, c *conn.Conn, u, p string) error {
|
||||
if u != "" && p != "" && !common.CheckAuth(r, u, p) {
|
||||
c.Write([]byte(common.UnauthorizedBytes))
|
||||
c.Close()
|
||||
return errors.New("401 Unauthorized")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *BaseServer) checkFlow() error {
|
||||
if s.task.Client.Flow.FlowLimit > 0 && (s.task.Client.Flow.FlowLimit<<20) < (s.task.Client.Flow.ExportFlow+s.task.Client.Flow.InletFlow) {
|
||||
return errors.New("Traffic exceeded")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//与客户端建立通道
|
||||
func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string, rb []byte, tp string) error {
|
||||
link := conn.NewLink(tp, addr, client.Cnf.Crypt, client.Cnf.Compress, c.Conn.RemoteAddr().String())
|
||||
|
||||
if target, err := s.bridge.SendLinkInfo(client.Id, link, c.Conn.RemoteAddr().String(), s.task); err != nil {
|
||||
logs.Warn("task id %d get connection from client id %d error %s", s.task.Id, client.Id, err.Error())
|
||||
c.Close()
|
||||
return err
|
||||
} else {
|
||||
if rb != nil {
|
||||
//HTTP proxy crypt or compress
|
||||
conn.GetConn(target, link.Crypt, link.Compress, client.Rate, true).Write(rb)
|
||||
}
|
||||
conn.CopyWaitGroup(target, c.Conn, link.Crypt, link.Compress, client.Rate, s.task.Flow, true)
|
||||
}
|
||||
|
||||
client.AddConn()
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"github.com/cnlh/nps/bridge"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/server/connection"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type httpServer struct {
|
||||
BaseServer
|
||||
httpPort int //http端口
|
||||
httpsPort int //https监听端口
|
||||
pemPath string
|
||||
keyPath string
|
||||
stop chan bool
|
||||
httpslistener net.Listener
|
||||
}
|
||||
|
||||
func NewHttp(bridge *bridge.Bridge, c *file.Tunnel) *httpServer {
|
||||
httpPort, _ := beego.AppConfig.Int("http_proxy_port")
|
||||
httpsPort, _ := beego.AppConfig.Int("https_proxy_port")
|
||||
pemPath := beego.AppConfig.String("pem_path")
|
||||
keyPath := beego.AppConfig.String("key_path")
|
||||
return &httpServer{
|
||||
BaseServer: BaseServer{
|
||||
task: c,
|
||||
bridge: bridge,
|
||||
Mutex: sync.Mutex{},
|
||||
},
|
||||
httpPort: httpPort,
|
||||
httpsPort: httpsPort,
|
||||
pemPath: pemPath,
|
||||
keyPath: keyPath,
|
||||
stop: make(chan bool),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *httpServer) processHttps(c net.Conn) {
|
||||
buf := make([]byte, 2<<10)
|
||||
n, err := c.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var host *file.Host
|
||||
file.GetCsvDb().Lock()
|
||||
for _, host = range file.GetCsvDb().Hosts {
|
||||
if bytes.Index(buf[:n], []byte(host.Host)) >= 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
file.GetCsvDb().Unlock()
|
||||
if host == nil {
|
||||
logs.Error("new https connection can't be parsed!", c.RemoteAddr().String())
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
var targetAddr string
|
||||
r := new(http.Request)
|
||||
r.RequestURI = "/"
|
||||
r.URL = new(url.URL)
|
||||
r.URL.Scheme = "https"
|
||||
r.Host = host.Host
|
||||
//read the host form connection
|
||||
if !host.Client.GetConn() { //conn num limit
|
||||
logs.Notice("connections exceed the current client %d limit %d ,now connection num %d", host.Client.Id, host.Client.MaxConn, host.Client.NowConn)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
//流量限制
|
||||
if host.Client.Flow.FlowLimit > 0 && (host.Client.Flow.FlowLimit<<20) < (host.Client.Flow.ExportFlow+host.Client.Flow.InletFlow) {
|
||||
logs.Warn("Traffic exceeded client id %s", host.Client.Id)
|
||||
return
|
||||
}
|
||||
if targetAddr, err = host.GetRandomTarget(); err != nil {
|
||||
logs.Warn(err.Error())
|
||||
}
|
||||
logs.Trace("new https connection,clientId %d,host %s,remote address %s", host.Client.Id, r.Host, c.RemoteAddr().String())
|
||||
s.DealClient(conn.NewConn(c), host.Client, targetAddr, buf[:n], common.CONN_TCP)
|
||||
}
|
||||
|
||||
func (s *httpServer) Start() error {
|
||||
var err error
|
||||
var httpSrv, httpsSrv *http.Server
|
||||
if s.errorContent, err = common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "error.html")); err != nil {
|
||||
s.errorContent = []byte("easyProxy 404")
|
||||
}
|
||||
|
||||
if s.httpPort > 0 {
|
||||
httpSrv = s.NewServer(s.httpPort, "http")
|
||||
go func() {
|
||||
l, err := connection.GetHttpListener()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
err = httpSrv.Serve(l)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
}()
|
||||
}
|
||||
if s.httpsPort > 0 {
|
||||
if !common.FileExists(s.pemPath) {
|
||||
os.Exit(0)
|
||||
}
|
||||
if !common.FileExists(s.keyPath) {
|
||||
logs.Error("ssl keyFile %s exist", s.keyPath)
|
||||
os.Exit(0)
|
||||
}
|
||||
httpsSrv = s.NewServer(s.httpsPort, "https")
|
||||
go func() {
|
||||
l, err := connection.GetHttpsListener()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
if b, err := beego.AppConfig.Bool("https_just_proxy"); err == nil && b {
|
||||
for {
|
||||
c, err := l.Accept()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
break
|
||||
}
|
||||
go s.processHttps(c)
|
||||
}
|
||||
} else {
|
||||
err = httpsSrv.ServeTLS(l, s.pemPath, s.keyPath)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
select {
|
||||
case <-s.stop:
|
||||
if httpSrv != nil {
|
||||
httpsSrv.Close()
|
||||
}
|
||||
if httpsSrv != nil {
|
||||
httpsSrv.Close()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *httpServer) Close() error {
|
||||
s.stop <- true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *httpServer) handleTunneling(w http.ResponseWriter, r *http.Request) {
|
||||
hijacker, ok := w.(http.Hijacker)
|
||||
if !ok {
|
||||
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
c, _, err := hijacker.Hijack()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
||||
}
|
||||
s.process(conn.NewConn(c), r)
|
||||
}
|
||||
|
||||
func (s *httpServer) process(c *conn.Conn, r *http.Request) {
|
||||
//多客户端域名代理
|
||||
var (
|
||||
isConn = true
|
||||
host *file.Host
|
||||
target net.Conn
|
||||
lastHost *file.Host
|
||||
err error
|
||||
connClient io.ReadWriteCloser
|
||||
scheme = r.URL.Scheme
|
||||
lk *conn.Link
|
||||
targetAddr string
|
||||
wg sync.WaitGroup
|
||||
)
|
||||
if host, err = file.GetCsvDb().GetInfoByHost(r.Host, r); err != nil {
|
||||
logs.Notice("the url %s %s %s can't be parsed!", r.URL.Scheme, r.Host, r.RequestURI)
|
||||
goto end
|
||||
} else if !host.Client.GetConn() { //conn num limit
|
||||
logs.Notice("connections exceed the current client %d limit %d ,now connection num %d", host.Client.Id, host.Client.MaxConn, host.Client.NowConn)
|
||||
c.Close()
|
||||
return
|
||||
} else {
|
||||
logs.Trace("new %s connection,clientId %d,host %s,url %s,remote address %s", r.URL.Scheme, host.Client.Id, r.Host, r.URL, r.RemoteAddr)
|
||||
lastHost = host
|
||||
}
|
||||
for {
|
||||
start:
|
||||
if isConn {
|
||||
//流量限制
|
||||
if host.Client.Flow.FlowLimit > 0 && (host.Client.Flow.FlowLimit<<20) < (host.Client.Flow.ExportFlow+host.Client.Flow.InletFlow) {
|
||||
logs.Warn("Traffic exceeded client id %s", host.Client.Id)
|
||||
break
|
||||
}
|
||||
//权限控制
|
||||
if err = s.auth(r, c, host.Client.Cnf.U, host.Client.Cnf.P); err != nil {
|
||||
logs.Warn("auth error", err, r.RemoteAddr)
|
||||
break
|
||||
}
|
||||
if targetAddr, err = host.GetRandomTarget(); err != nil {
|
||||
logs.Warn(err.Error())
|
||||
break
|
||||
}
|
||||
lk = conn.NewLink(common.CONN_TCP, targetAddr, host.Client.Cnf.Crypt, host.Client.Cnf.Compress, r.RemoteAddr)
|
||||
if target, err = s.bridge.SendLinkInfo(host.Client.Id, lk, c.Conn.RemoteAddr().String(), nil); err != nil {
|
||||
logs.Notice("connect to target %s error %s", lk.Host, err)
|
||||
break
|
||||
}
|
||||
connClient = conn.GetConn(target, lk.Crypt, lk.Compress, host.Client.Rate, true)
|
||||
isConn = false
|
||||
go func() {
|
||||
wg.Add(1)
|
||||
w, _ := common.CopyBuffer(c, connClient)
|
||||
host.Flow.Add(0, w)
|
||||
c.Close()
|
||||
target.Close()
|
||||
wg.Done()
|
||||
}()
|
||||
} else {
|
||||
r, err = http.ReadRequest(bufio.NewReader(c))
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
r.URL.Scheme = scheme
|
||||
//What happened ,Why one character less???
|
||||
if r.Method == "ET" {
|
||||
r.Method = "GET"
|
||||
}
|
||||
if r.Method == "OST" {
|
||||
r.Method = "POST"
|
||||
}
|
||||
logs.Trace("new %s connection,clientId %d,host %s,url %s,remote address %s", r.URL.Scheme, host.Client.Id, r.Host, r.URL, r.RemoteAddr)
|
||||
if hostTmp, err := file.GetCsvDb().GetInfoByHost(r.Host, r); err != nil {
|
||||
logs.Notice("the url %s %s %s can't be parsed!", r.URL.Scheme, r.Host, r.RequestURI)
|
||||
break
|
||||
} else if host != lastHost {
|
||||
host.Client.AddConn()
|
||||
if !hostTmp.Client.GetConn() {
|
||||
break
|
||||
}
|
||||
host = hostTmp
|
||||
lastHost = host
|
||||
isConn = true
|
||||
goto start
|
||||
}
|
||||
}
|
||||
//根据设定,修改header和host
|
||||
common.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, c.Conn.RemoteAddr().String())
|
||||
b, err := httputil.DumpRequest(r, false)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
logs.Trace("%s request, method %s, host %s, url %s, remote address %s, target %s", r.URL.Scheme, r.Method, r.Host, r.RequestURI, r.RemoteAddr, lk.Host)
|
||||
//write
|
||||
connClient.Write(b)
|
||||
if bodyLen, err := common.CopyBuffer(connClient, r.Body); err != nil {
|
||||
break
|
||||
} else {
|
||||
host.Flow.Add(int64(len(b))+bodyLen, 0)
|
||||
}
|
||||
}
|
||||
end:
|
||||
if isConn {
|
||||
s.writeConnFail(c.Conn)
|
||||
}
|
||||
c.Close()
|
||||
if target != nil {
|
||||
target.Close()
|
||||
}
|
||||
wg.Wait()
|
||||
if host != nil {
|
||||
host.Client.AddConn()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *httpServer) NewServer(port int, scheme string) *http.Server {
|
||||
return &http.Server{
|
||||
Addr: ":" + strconv.Itoa(port),
|
||||
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.URL.Scheme = scheme
|
||||
s.handleTunneling(w, r)
|
||||
}),
|
||||
// Disable HTTP/2.
|
||||
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type P2PServer struct {
|
||||
BaseServer
|
||||
p2pPort int
|
||||
p2p map[string]*p2p
|
||||
}
|
||||
|
||||
type p2p struct {
|
||||
provider *conn.Conn
|
||||
visitor *conn.Conn
|
||||
visitorAddr string
|
||||
providerAddr string
|
||||
}
|
||||
|
||||
func NewP2PServer(p2pPort int) *P2PServer {
|
||||
return &P2PServer{
|
||||
p2pPort: p2pPort,
|
||||
p2p: make(map[string]*p2p),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *P2PServer) Start() error {
|
||||
kcpListener, err := kcp.ListenWithOptions(":"+strconv.Itoa(s.p2pPort), nil, 150, 3)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return err
|
||||
}
|
||||
for {
|
||||
c, err := kcpListener.AcceptKCP()
|
||||
conn.SetUdpSession(c)
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
continue
|
||||
}
|
||||
go s.p2pProcess(conn.NewConn(c))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *P2PServer) p2pProcess(c *conn.Conn) {
|
||||
//获取密钥
|
||||
var (
|
||||
f string
|
||||
b []byte
|
||||
err error
|
||||
v *p2p
|
||||
ok bool
|
||||
)
|
||||
if b, err = c.GetShortContent(32); err != nil {
|
||||
return
|
||||
}
|
||||
//获取角色
|
||||
if f, err = c.ReadFlag(); err != nil {
|
||||
return
|
||||
}
|
||||
if v, ok = s.p2p[string(b)]; !ok {
|
||||
v = new(p2p)
|
||||
s.p2p[string(b)] = v
|
||||
}
|
||||
//存储
|
||||
if f == common.WORK_P2P_VISITOR {
|
||||
v.visitorAddr = c.Conn.RemoteAddr().String()
|
||||
v.visitor = c
|
||||
for {
|
||||
time.Sleep(time.Second)
|
||||
if v.provider != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if _, err := v.provider.ReadFlag(); err == nil {
|
||||
v.visitor.WriteLenContent([]byte(v.providerAddr))
|
||||
delete(s.p2p, string(b))
|
||||
} else {
|
||||
}
|
||||
} else {
|
||||
v.providerAddr = c.Conn.RemoteAddr().String()
|
||||
v.provider = c
|
||||
for {
|
||||
time.Sleep(time.Second)
|
||||
if v.visitor != nil {
|
||||
v.provider.WriteLenContent([]byte(v.visitorAddr))
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package server
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
@@ -48,8 +48,7 @@ const (
|
||||
)
|
||||
|
||||
type Sock5ModeServer struct {
|
||||
server
|
||||
isVerify bool
|
||||
BaseServer
|
||||
listener net.Listener
|
||||
}
|
||||
|
||||
@@ -68,7 +67,7 @@ func (s *Sock5ModeServer) handleRequest(c net.Conn) {
|
||||
_, err := io.ReadFull(c, header)
|
||||
|
||||
if err != nil {
|
||||
lg.Println("illegal request", err)
|
||||
logs.Warn("illegal request", err)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
@@ -142,15 +141,18 @@ func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
|
||||
} else {
|
||||
ltype = common.CONN_TCP
|
||||
}
|
||||
link := conn.NewLink(s.task.Client.GetId(), ltype, addr, s.config.CompressEncode, s.config.CompressDecode, s.config.Crypt, conn.NewConn(c), s.task.Flow, nil, s.task.Client.Rate, nil)
|
||||
//s.DealClient(conn.NewConn(c), addr, nil, ltype)
|
||||
link := conn.NewLink(ltype, addr, s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, c.RemoteAddr().String())
|
||||
|
||||
if tunnel, err := s.bridge.SendLinkInfo(s.task.Client.Id, link); err != nil {
|
||||
if target, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, c.RemoteAddr().String(), s.task); err != nil {
|
||||
c.Close()
|
||||
return
|
||||
} else {
|
||||
s.sendReply(c, succeeded)
|
||||
s.linkCopy(link, conn.NewConn(c), nil, tunnel, s.task.Flow)
|
||||
conn.CopyWaitGroup(target, c, link.Crypt, link.Compress, s.task.Client.Rate, s.task.Flow, true)
|
||||
}
|
||||
|
||||
s.task.Client.AddConn()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -165,7 +167,6 @@ func (s *Sock5ModeServer) handleBind(c net.Conn) {
|
||||
|
||||
//udp
|
||||
func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
lg.Println("UDP Associate")
|
||||
/*
|
||||
+----+------+------+----------+----------+----------+
|
||||
|RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
|
||||
@@ -178,7 +179,7 @@ func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
// relay udp datagram silently, without any notification to the requesting client
|
||||
if buf[2] != 0 {
|
||||
// does not support fragmentation, drop it
|
||||
lg.Println("does not support fragmentation, drop")
|
||||
logs.Warn("does not support fragmentation, drop")
|
||||
dummy := make([]byte, maxUDPPacketSize)
|
||||
c.Read(dummy)
|
||||
}
|
||||
@@ -190,13 +191,13 @@ func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
func (s *Sock5ModeServer) handleConn(c net.Conn) {
|
||||
buf := make([]byte, 2)
|
||||
if _, err := io.ReadFull(c, buf); err != nil {
|
||||
lg.Println("negotiation err", err)
|
||||
logs.Warn("negotiation err", err)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
|
||||
if version := buf[0]; version != 5 {
|
||||
lg.Println("only support socks5, request from: ", c.RemoteAddr())
|
||||
logs.Warn("only support socks5, request from: ", c.RemoteAddr())
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
@@ -204,16 +205,16 @@ func (s *Sock5ModeServer) handleConn(c net.Conn) {
|
||||
|
||||
methods := make([]byte, nMethods)
|
||||
if len, err := c.Read(methods); len != int(nMethods) || err != nil {
|
||||
lg.Println("wrong method")
|
||||
logs.Warn("wrong method")
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
if s.isVerify {
|
||||
if s.task.Client.Cnf.U != "" && s.task.Client.Cnf.P != "" {
|
||||
buf[1] = UserPassAuth
|
||||
c.Write(buf)
|
||||
if err := s.Auth(c); err != nil {
|
||||
c.Close()
|
||||
lg.Println("验证失败:", err)
|
||||
logs.Warn("Validation failed:", err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
@@ -245,7 +246,7 @@ func (s *Sock5ModeServer) Auth(c net.Conn) error {
|
||||
if _, err := io.ReadAtLeast(c, pass, passLen); err != nil {
|
||||
return err
|
||||
}
|
||||
if string(pass) == s.config.U && string(user) == s.config.P {
|
||||
if string(user) == s.task.Client.Cnf.U && string(pass) == s.task.Client.Cnf.P {
|
||||
if _, err := c.Write([]byte{userAuthVersion, authSuccess}); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -256,13 +257,12 @@ func (s *Sock5ModeServer) Auth(c net.Conn) error {
|
||||
}
|
||||
return errors.New("验证不通过")
|
||||
}
|
||||
return errors.New("未知错误")
|
||||
}
|
||||
|
||||
//start
|
||||
func (s *Sock5ModeServer) Start() error {
|
||||
var err error
|
||||
s.listener, err = net.Listen("tcp", ":"+strconv.Itoa(s.task.TcpPort))
|
||||
s.listener, err = net.Listen("tcp", ":"+strconv.Itoa(s.task.Port))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -272,13 +272,19 @@ func (s *Sock5ModeServer) Start() error {
|
||||
if strings.Contains(err.Error(), "use of closed network connection") {
|
||||
break
|
||||
}
|
||||
lg.Fatalln("accept error: ", err)
|
||||
logs.Warn("accept error: ", err)
|
||||
}
|
||||
if !s.ResetConfig() {
|
||||
if err := s.checkFlow(); err != nil {
|
||||
logs.Warn("client id %d task id %d error %s", s.task.Client.Id, s.task.Id, err.Error())
|
||||
conn.Close()
|
||||
}
|
||||
if s.task.Client.GetConn() {
|
||||
logs.Trace("New socks5 connection,client %d,remote address %s", s.task.Client.Id, conn.RemoteAddr())
|
||||
go s.handleConn(conn)
|
||||
} else {
|
||||
logs.Warn("Connections exceed the current client %d limit", s.task.Client.Id)
|
||||
conn.Close()
|
||||
continue
|
||||
}
|
||||
go s.handleConn(conn)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -293,11 +299,5 @@ func NewSock5ModeServer(bridge *bridge.Bridge, task *file.Tunnel) *Sock5ModeServ
|
||||
s := new(Sock5ModeServer)
|
||||
s.bridge = bridge
|
||||
s.task = task
|
||||
s.config = file.DeepCopyConfig(task.Config)
|
||||
if s.config.U != "" && s.config.P != "" {
|
||||
s.isVerify = true
|
||||
} else {
|
||||
s.isVerify = false
|
||||
}
|
||||
return s
|
||||
}
|
||||
Executable
+137
@@ -0,0 +1,137 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/cnlh/nps/bridge"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/server/connection"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"net"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type TunnelModeServer struct {
|
||||
BaseServer
|
||||
process process
|
||||
listener *net.TCPListener
|
||||
}
|
||||
|
||||
//tcp|http|host
|
||||
func NewTunnelModeServer(process process, bridge *bridge.Bridge, task *file.Tunnel) *TunnelModeServer {
|
||||
s := new(TunnelModeServer)
|
||||
s.bridge = bridge
|
||||
s.process = process
|
||||
s.task = task
|
||||
return s
|
||||
}
|
||||
|
||||
//开始
|
||||
func (s *TunnelModeServer) Start() error {
|
||||
var err error
|
||||
s.listener, err = net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), s.task.Port, ""})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
c, err := s.listener.AcceptTCP()
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "use of closed network connection") {
|
||||
break
|
||||
}
|
||||
logs.Info(err)
|
||||
continue
|
||||
}
|
||||
if err := s.checkFlow(); err != nil {
|
||||
logs.Warn("client id %d task id %d error %s", s.task.Client.Id, s.task.Id, err.Error())
|
||||
c.Close()
|
||||
}
|
||||
if s.task.Client.GetConn() {
|
||||
logs.Trace("New tcp connection,local port %d,client %d,remote address %s", s.task.Port, s.task.Client.Id, c.RemoteAddr())
|
||||
go s.process(conn.NewConn(c), s)
|
||||
} else {
|
||||
logs.Info("Connections exceed the current client %d limit", s.task.Client.Id)
|
||||
c.Close()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//close
|
||||
func (s *TunnelModeServer) Close() error {
|
||||
return s.listener.Close()
|
||||
}
|
||||
|
||||
//web管理方式
|
||||
type WebServer struct {
|
||||
BaseServer
|
||||
}
|
||||
|
||||
//开始
|
||||
func (s *WebServer) Start() error {
|
||||
p, _ := beego.AppConfig.Int("web_port")
|
||||
if p == 0 {
|
||||
stop := make(chan struct{})
|
||||
<-stop
|
||||
}
|
||||
//if !common.TestTcpPort(p) {
|
||||
// // logs.Error("Web management port %d is occupied", p)
|
||||
// // os.Exit(0)
|
||||
// //}
|
||||
beego.BConfig.WebConfig.Session.SessionOn = true
|
||||
beego.SetStaticPath("/static", filepath.Join(common.GetRunPath(), "web", "static"))
|
||||
beego.SetViewsPath(filepath.Join(common.GetRunPath(), "web", "views"))
|
||||
if l, err := connection.GetWebManagerListener(); err == nil {
|
||||
beego.InitBeforeHTTPRun()
|
||||
http.Serve(l, beego.BeeApp.Handlers)
|
||||
} else {
|
||||
logs.Error(err)
|
||||
}
|
||||
return errors.New("Web management startup failure")
|
||||
}
|
||||
|
||||
func (s *WebServer) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
//new
|
||||
func NewWebServer(bridge *bridge.Bridge) *WebServer {
|
||||
s := new(WebServer)
|
||||
s.bridge = bridge
|
||||
return s
|
||||
}
|
||||
|
||||
type process func(c *conn.Conn, s *TunnelModeServer) error
|
||||
|
||||
//tcp隧道模式
|
||||
func ProcessTunnel(c *conn.Conn, s *TunnelModeServer) error {
|
||||
targetAddr, err := s.task.GetRandomTarget()
|
||||
if err != nil {
|
||||
c.Close()
|
||||
logs.Warn("tcp port %d ,client id %d,task id %d connect error %s", s.task.Port, s.task.Client.Id, s.task.Id, err.Error())
|
||||
return err
|
||||
}
|
||||
return s.DealClient(c, s.task.Client, targetAddr, nil, common.CONN_TCP)
|
||||
}
|
||||
|
||||
//http代理模式
|
||||
func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error {
|
||||
_, addr, rb, err, r := c.GetHost()
|
||||
if err != nil {
|
||||
c.Close()
|
||||
logs.Info(err)
|
||||
return err
|
||||
}
|
||||
if r.Method == "CONNECT" {
|
||||
c.Write([]byte("HTTP/1.1 200 Connection Established\r\n"))
|
||||
rb = nil
|
||||
}
|
||||
if err := s.auth(r, c, s.task.Client.Cnf.U, s.task.Client.Cnf.P); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.DealClient(c, s.task.Client, addr, rb, common.CONN_TCP)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package server
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/bridge"
|
||||
@@ -6,29 +6,27 @@ import (
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/pool"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type UdpModeServer struct {
|
||||
server
|
||||
BaseServer
|
||||
listener *net.UDPConn
|
||||
udpMap map[string]*conn.Conn
|
||||
}
|
||||
|
||||
func NewUdpModeServer(bridge *bridge.Bridge, task *file.Tunnel) *UdpModeServer {
|
||||
s := new(UdpModeServer)
|
||||
s.bridge = bridge
|
||||
s.udpMap = make(map[string]*conn.Conn)
|
||||
s.task = task
|
||||
s.config = file.DeepCopyConfig(task.Config)
|
||||
return s
|
||||
}
|
||||
|
||||
//开始
|
||||
func (s *UdpModeServer) Start() error {
|
||||
var err error
|
||||
s.listener, err = net.ListenUDP("udp", &net.UDPAddr{net.ParseIP("0.0.0.0"), s.task.TcpPort, ""})
|
||||
s.listener, err = net.ListenUDP("udp", &net.UDPAddr{net.ParseIP("0.0.0.0"), s.task.Port, ""})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -41,23 +39,32 @@ func (s *UdpModeServer) Start() error {
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !s.ResetConfig() {
|
||||
continue
|
||||
}
|
||||
logs.Trace("New udp connection,client %d,remote address %s", s.task.Client.Id, addr)
|
||||
go s.process(addr, buf[:n])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *UdpModeServer) process(addr *net.UDPAddr, data []byte) {
|
||||
link := conn.NewLink(s.task.Client.GetId(), common.CONN_UDP, s.task.Target, s.config.CompressEncode, s.config.CompressDecode, s.config.Crypt, nil, s.task.Flow, s.listener, s.task.Client.Rate, addr)
|
||||
|
||||
if tunnel, err := s.bridge.SendLinkInfo(s.task.Client.Id, link); err != nil {
|
||||
link := conn.NewLink(common.CONN_UDP, s.task.Target, s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, addr.String())
|
||||
if err := s.checkFlow(); err != nil {
|
||||
return
|
||||
}
|
||||
if target, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, addr.String(), s.task); err != nil {
|
||||
return
|
||||
} else {
|
||||
s.task.Flow.Add(len(data), 0)
|
||||
tunnel.SendMsg(data, link)
|
||||
pool.PutBufPoolUdp(data)
|
||||
s.task.Flow.Add(int64(len(data)), 0)
|
||||
buf := pool.BufPoolUdp.Get().([]byte)
|
||||
defer pool.BufPoolUdp.Put(buf)
|
||||
target.Write(data)
|
||||
s.task.Flow.Add(int64(len(data)), 0)
|
||||
if n, err := target.Read(buf); err != nil {
|
||||
logs.Warn(err)
|
||||
return
|
||||
} else {
|
||||
s.listener.WriteTo(buf[:n], addr)
|
||||
s.task.Flow.Add(0, int64(n))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+269
-67
@@ -3,104 +3,190 @@ package server
|
||||
import (
|
||||
"errors"
|
||||
"github.com/cnlh/nps/bridge"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"reflect"
|
||||
"strings"
|
||||
"github.com/cnlh/nps/server/proxy"
|
||||
"github.com/cnlh/nps/server/tool"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
|
||||
"github.com/shirou/gopsutil/cpu"
|
||||
"github.com/shirou/gopsutil/load"
|
||||
"github.com/shirou/gopsutil/mem"
|
||||
"github.com/shirou/gopsutil/net"
|
||||
"math"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
Bridge *bridge.Bridge
|
||||
RunList map[int]interface{} //运行中的任务
|
||||
Bridge *bridge.Bridge
|
||||
RunList map[int]interface{} //运行中的任务
|
||||
serverStatus []map[string]interface{}
|
||||
)
|
||||
|
||||
func init() {
|
||||
RunList = make(map[int]interface{})
|
||||
serverStatus = make([]map[string]interface{}, 0, 1500)
|
||||
go getSeverStatus()
|
||||
}
|
||||
|
||||
//从csv文件中恢复任务
|
||||
func InitFromCsv() {
|
||||
//Add a public password
|
||||
if vkey := beego.AppConfig.String("public_vkey"); vkey != "" {
|
||||
c := file.NewClient(vkey, true, true)
|
||||
file.GetCsvDb().NewClient(c)
|
||||
RunList[c.Id] = nil
|
||||
}
|
||||
//Initialize services in server-side files
|
||||
for _, v := range file.GetCsvDb().Tasks {
|
||||
if v.Status {
|
||||
lg.Println("启动模式:", v.Mode, "监听端口:", v.TcpPort)
|
||||
AddTask(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func DealBridgeTask() {
|
||||
for {
|
||||
select {
|
||||
case t := <-Bridge.OpenTask:
|
||||
AddTask(t)
|
||||
case t := <-Bridge.CloseTask:
|
||||
StopServer(t.Id)
|
||||
case id := <-Bridge.CloseClient:
|
||||
DelTunnelAndHostByClientId(id)
|
||||
file.GetCsvDb().DelClient(id)
|
||||
case tunnel := <-Bridge.OpenTask:
|
||||
StartTask(tunnel.Id)
|
||||
case s := <-Bridge.SecretChan:
|
||||
logs.Trace("New secret connection, addr", s.Conn.Conn.RemoteAddr())
|
||||
if t := file.GetCsvDb().GetTaskByMd5Password(s.Password); t != nil {
|
||||
if !t.Client.GetConn() {
|
||||
logs.Info("Connections exceed the current client %d limit", t.Client.Id)
|
||||
s.Conn.Close()
|
||||
} else if t.Status {
|
||||
go proxy.NewBaseServer(Bridge, t).DealClient(s.Conn, t.Client, t.Target, nil, common.CONN_TCP)
|
||||
} else {
|
||||
s.Conn.Close()
|
||||
logs.Trace("This key %s cannot be processed,status is close", s.Password)
|
||||
}
|
||||
} else {
|
||||
logs.Trace("This key %s cannot be processed", s.Password)
|
||||
s.Conn.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//start a new server
|
||||
func StartNewServer(bridgePort int, cnf *file.Tunnel, bridgeType string) {
|
||||
Bridge = bridge.NewTunnel(bridgePort, RunList, bridgeType)
|
||||
Bridge = bridge.NewTunnel(bridgePort, bridgeType, common.GetBoolByStr(beego.AppConfig.String("ip_limit")), RunList)
|
||||
if err := Bridge.StartTunnel(); err != nil {
|
||||
lg.Fatalln("服务端开启失败", err)
|
||||
logs.Error("start server bridge error", err)
|
||||
os.Exit(0)
|
||||
}
|
||||
if p, err := beego.AppConfig.Int("p2p_port"); err == nil {
|
||||
logs.Info("start p2p server port", p)
|
||||
go proxy.NewP2PServer(p).Start()
|
||||
}
|
||||
go DealBridgeTask()
|
||||
go dealClientFlow()
|
||||
if svr := NewMode(Bridge, cnf); svr != nil {
|
||||
RunList[cnf.Id] = svr
|
||||
err := reflect.ValueOf(svr).MethodByName("Start").Call(nil)[0]
|
||||
if err.Interface() != nil {
|
||||
lg.Fatalln(err)
|
||||
if err := svr.Start(); err != nil {
|
||||
logs.Error(err)
|
||||
}
|
||||
RunList[cnf.Id] = svr
|
||||
} else {
|
||||
lg.Fatalln("启动模式不正确")
|
||||
logs.Error("Incorrect startup mode %s", cnf.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
func dealClientFlow() {
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
dealClientData(file.GetCsvDb().Clients)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//new a server by mode name
|
||||
func NewMode(Bridge *bridge.Bridge, c *file.Tunnel) interface{} {
|
||||
func NewMode(Bridge *bridge.Bridge, c *file.Tunnel) proxy.Service {
|
||||
var service proxy.Service
|
||||
switch c.Mode {
|
||||
case "tunnelServer":
|
||||
return NewTunnelModeServer(ProcessTunnel, Bridge, c)
|
||||
case "socks5Server":
|
||||
return NewSock5ModeServer(Bridge, c)
|
||||
case "httpProxyServer":
|
||||
return NewTunnelModeServer(ProcessHttp, Bridge, c)
|
||||
case "udpServer":
|
||||
return NewUdpModeServer(Bridge, c)
|
||||
case "tcp", "file":
|
||||
service = proxy.NewTunnelModeServer(proxy.ProcessTunnel, Bridge, c)
|
||||
case "socks5":
|
||||
service = proxy.NewSock5ModeServer(Bridge, c)
|
||||
case "httpProxy":
|
||||
service = proxy.NewTunnelModeServer(proxy.ProcessHttp, Bridge, c)
|
||||
case "udp":
|
||||
service = proxy.NewUdpModeServer(Bridge, c)
|
||||
case "webServer":
|
||||
InitFromCsv()
|
||||
t := &file.Tunnel{
|
||||
TcpPort: 0,
|
||||
Mode: "httpHostServer",
|
||||
Target: "",
|
||||
Config: &file.Config{},
|
||||
Status: true,
|
||||
Port: 0,
|
||||
Mode: "httpHostServer",
|
||||
Target: "",
|
||||
Status: true,
|
||||
}
|
||||
AddTask(t)
|
||||
return NewWebServer(Bridge)
|
||||
service = proxy.NewWebServer(Bridge)
|
||||
case "httpHostServer":
|
||||
return NewHttp(Bridge, c)
|
||||
service = proxy.NewHttp(Bridge, c)
|
||||
}
|
||||
return nil
|
||||
return service
|
||||
}
|
||||
|
||||
//stop server
|
||||
func StopServer(id int) error {
|
||||
if v, ok := RunList[id]; ok {
|
||||
reflect.ValueOf(v).MethodByName("Close").Call(nil)
|
||||
if svr, ok := v.(proxy.Service); ok {
|
||||
if err := svr.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
logs.Info("stop server id %d", id)
|
||||
}
|
||||
if t, err := file.GetCsvDb().GetTask(id); err != nil {
|
||||
return err
|
||||
} else {
|
||||
t.Status = false
|
||||
file.GetCsvDb().UpdateTask(t)
|
||||
}
|
||||
delete(RunList, id)
|
||||
return nil
|
||||
}
|
||||
return errors.New("未在运行中")
|
||||
return errors.New("task is not running")
|
||||
}
|
||||
|
||||
//add task
|
||||
func AddTask(t *file.Tunnel) error {
|
||||
if t.Mode == "secret" || t.Mode == "p2p" {
|
||||
logs.Info("secret task %s start ", t.Remark)
|
||||
RunList[t.Id] = nil
|
||||
return nil
|
||||
}
|
||||
if b := tool.TestServerPort(t.Port, t.Mode); !b && t.Mode != "httpHostServer" {
|
||||
logs.Error("taskId %d start error port %d open failed", t.Id, t.Port)
|
||||
return errors.New("the port open error")
|
||||
}
|
||||
if minute, err := beego.AppConfig.Int("flow_store_interval"); err == nil && minute > 0 {
|
||||
go flowSession(time.Minute * time.Duration(minute))
|
||||
}
|
||||
if svr := NewMode(Bridge, t); svr != nil {
|
||||
logs.Info("tunnel task %s start mode:%s port %d", t.Remark, t.Mode, t.Port)
|
||||
RunList[t.Id] = svr
|
||||
go func() {
|
||||
err := reflect.ValueOf(svr).MethodByName("Start").Call(nil)[0]
|
||||
if err.Interface() != nil {
|
||||
lg.Fatalln("客户端", t.Id, "启动失败,错误:", err)
|
||||
if err := svr.Start(); err != nil {
|
||||
logs.Error("clientId %d taskId %d start error %s", t.Client.Id, t.Id, err)
|
||||
delete(RunList, t.Id)
|
||||
return
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
return errors.New("启动模式不正确")
|
||||
return errors.New("the mode is not correct")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -119,29 +205,20 @@ func StartTask(id int) error {
|
||||
|
||||
//delete task
|
||||
func DelTask(id int) error {
|
||||
if err := StopServer(id); err != nil {
|
||||
return err
|
||||
}
|
||||
return file.GetCsvDb().DelTask(id)
|
||||
}
|
||||
|
||||
//get key by host from x
|
||||
func GetInfoByHost(host string) (h *file.Host, err error) {
|
||||
for _, v := range file.GetCsvDb().Hosts {
|
||||
s := strings.Split(host, ":")
|
||||
if s[0] == v.Host {
|
||||
h = v
|
||||
return
|
||||
if _, ok := RunList[id]; ok {
|
||||
if err := StopServer(id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
err = errors.New("未找到host对应的内网目标")
|
||||
return
|
||||
return file.GetCsvDb().DelTask(id)
|
||||
}
|
||||
|
||||
//get task list by page num
|
||||
func GetTunnel(start, length int, typeVal string, clientId int) ([]*file.Tunnel, int) {
|
||||
list := make([]*file.Tunnel, 0)
|
||||
var cnt int
|
||||
file.GetCsvDb().Lock()
|
||||
defer file.GetCsvDb().Unlock()
|
||||
for _, v := range file.GetCsvDb().Tasks {
|
||||
if (typeVal != "" && v.Mode != typeVal) || (typeVal == "" && clientId != v.Client.Id) {
|
||||
continue
|
||||
@@ -155,9 +232,9 @@ func GetTunnel(start, length int, typeVal string, clientId int) ([]*file.Tunnel,
|
||||
if start--; start < 0 {
|
||||
if length--; length > 0 {
|
||||
if _, ok := RunList[v.Id]; ok {
|
||||
v.Client.Status = true
|
||||
v.RunStatus = true
|
||||
} else {
|
||||
v.Client.Status = false
|
||||
v.RunStatus = false
|
||||
}
|
||||
list = append(list, v)
|
||||
}
|
||||
@@ -174,6 +251,8 @@ func GetClientList(start, length int) (list []*file.Client, cnt int) {
|
||||
}
|
||||
|
||||
func dealClientData(list []*file.Client) {
|
||||
file.GetCsvDb().Lock()
|
||||
defer file.GetCsvDb().Unlock()
|
||||
for _, v := range list {
|
||||
if _, ok := Bridge.Client[v.Id]; ok {
|
||||
v.IsConnect = true
|
||||
@@ -200,27 +279,39 @@ func dealClientData(list []*file.Client) {
|
||||
|
||||
//根据客户端id删除其所属的所有隧道和域名
|
||||
func DelTunnelAndHostByClientId(clientId int) {
|
||||
var ids []int
|
||||
file.GetCsvDb().Lock()
|
||||
for _, v := range file.GetCsvDb().Tasks {
|
||||
if v.Client.Id == clientId {
|
||||
DelTask(v.Id)
|
||||
ids = append(ids, v.Id)
|
||||
}
|
||||
}
|
||||
file.GetCsvDb().Unlock()
|
||||
for _, id := range ids {
|
||||
DelTask(id)
|
||||
}
|
||||
ids = ids[:0]
|
||||
file.GetCsvDb().Lock()
|
||||
for _, v := range file.GetCsvDb().Hosts {
|
||||
if v.Client.Id == clientId {
|
||||
file.GetCsvDb().DelHost(v.Host)
|
||||
ids = append(ids, v.Id)
|
||||
}
|
||||
}
|
||||
file.GetCsvDb().Unlock()
|
||||
for _, id := range ids {
|
||||
file.GetCsvDb().DelHost(id)
|
||||
}
|
||||
}
|
||||
|
||||
//关闭客户端连接
|
||||
func DelClientConnect(clientId int) {
|
||||
Bridge.DelClient(clientId)
|
||||
Bridge.DelClient(clientId, false)
|
||||
}
|
||||
|
||||
func GetDashboardData() map[string]int {
|
||||
data := make(map[string]int)
|
||||
func GetDashboardData() map[string]interface{} {
|
||||
data := make(map[string]interface{})
|
||||
data["hostCount"] = len(file.GetCsvDb().Hosts)
|
||||
data["clientCount"] = len(file.GetCsvDb().Clients)
|
||||
data["clientCount"] = len(file.GetCsvDb().Clients) - 1 //Remove the public key client
|
||||
list := file.GetCsvDb().Clients
|
||||
dealClientData(list)
|
||||
c := 0
|
||||
@@ -235,17 +326,128 @@ func GetDashboardData() map[string]int {
|
||||
data["clientOnlineCount"] = c
|
||||
data["inletFlowCount"] = int(in)
|
||||
data["exportFlowCount"] = int(out)
|
||||
var tcp, udp, secret, socks5, p2p, http int
|
||||
file.GetCsvDb().Lock()
|
||||
defer file.GetCsvDb().Unlock()
|
||||
for _, v := range file.GetCsvDb().Tasks {
|
||||
switch v.Mode {
|
||||
case "tunnelServer":
|
||||
data["tunnelServerCount"] += 1
|
||||
case "socks5Server":
|
||||
data["socks5ServerCount"] += 1
|
||||
case "httpProxyServer":
|
||||
data["httpProxyServerCount"] += 1
|
||||
case "udpServer":
|
||||
data["udpServerCount"] += 1
|
||||
case "tcp":
|
||||
tcp += 1
|
||||
case "socks5":
|
||||
udp += 1
|
||||
case "httpProxy":
|
||||
http += 1
|
||||
case "udp":
|
||||
udp += 1
|
||||
case "p2p":
|
||||
p2p += 1
|
||||
case "secret":
|
||||
secret += 1
|
||||
}
|
||||
}
|
||||
data["tcpC"] = tcp
|
||||
data["udpCount"] = udp
|
||||
data["socks5Count"] = socks5
|
||||
data["httpProxyCount"] = http
|
||||
data["secretCount"] = secret
|
||||
data["p2pCount"] = p2p
|
||||
data["bridgeType"] = beego.AppConfig.String("bridge_type")
|
||||
data["httpProxyPort"] = beego.AppConfig.String("http_proxy_port")
|
||||
data["httpsProxyPort"] = beego.AppConfig.String("https_proxy_port")
|
||||
data["ipLimit"] = beego.AppConfig.String("ip_limit")
|
||||
data["flowStoreInterval"] = beego.AppConfig.String("flow_store_interval")
|
||||
data["serverIp"] = beego.AppConfig.String("p2p_ip")
|
||||
data["p2pPort"] = beego.AppConfig.String("p2p_port")
|
||||
data["logLevel"] = beego.AppConfig.String("log_level")
|
||||
tcpCount := 0
|
||||
for _, v := range file.GetCsvDb().Clients {
|
||||
tcpCount += v.NowConn
|
||||
}
|
||||
data["tcpCount"] = tcpCount
|
||||
cpuPercet, _ := cpu.Percent(0, true)
|
||||
var cpuAll float64
|
||||
for _, v := range cpuPercet {
|
||||
cpuAll += v
|
||||
}
|
||||
loads, _ := load.Avg()
|
||||
data["load"] = loads.String()
|
||||
data["cpu"] = math.Round(cpuAll / float64(len(cpuPercet)))
|
||||
swap, _ := mem.SwapMemory()
|
||||
data["swap_mem"] = math.Round(swap.UsedPercent)
|
||||
vir, _ := mem.VirtualMemory()
|
||||
data["virtual_mem"] = math.Round(vir.UsedPercent)
|
||||
conn, _ := net.ProtoCounters(nil)
|
||||
io1, _ := net.IOCounters(false)
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
io2, _ := net.IOCounters(false)
|
||||
if len(io2) > 0 && len(io1) > 0 {
|
||||
data["io_send"] = (io2[0].BytesSent - io1[0].BytesSent) * 2
|
||||
data["io_recv"] = (io2[0].BytesRecv - io1[0].BytesRecv) * 2
|
||||
}
|
||||
for _, v := range conn {
|
||||
data[v.Protocol] = v.Stats["CurrEstab"]
|
||||
}
|
||||
//chart
|
||||
var fg int
|
||||
if len(serverStatus) >= 10 {
|
||||
fg = len(serverStatus) / 10
|
||||
for i := 0; i <= 9; i++ {
|
||||
data["sys"+strconv.Itoa(i+1)] = serverStatus[i*fg]
|
||||
}
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func flowSession(m time.Duration) {
|
||||
ticker := time.NewTicker(m)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
file.GetCsvDb().StoreHostToCsv()
|
||||
file.GetCsvDb().StoreTasksToCsv()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getSeverStatus() {
|
||||
for {
|
||||
if len(serverStatus) < 10 {
|
||||
time.Sleep(time.Second)
|
||||
} else {
|
||||
time.Sleep(time.Minute)
|
||||
}
|
||||
cpuPercet, _ := cpu.Percent(0, true)
|
||||
var cpuAll float64
|
||||
for _, v := range cpuPercet {
|
||||
cpuAll += v
|
||||
}
|
||||
m := make(map[string]interface{})
|
||||
loads, _ := load.Avg()
|
||||
m["load1"] = loads.Load1
|
||||
m["load5"] = loads.Load5
|
||||
m["load15"] = loads.Load15
|
||||
m["cpu"] = math.Round(cpuAll / float64(len(cpuPercet)))
|
||||
swap, _ := mem.SwapMemory()
|
||||
m["swap_mem"] = math.Round(swap.UsedPercent)
|
||||
vir, _ := mem.VirtualMemory()
|
||||
m["virtual_mem"] = math.Round(vir.UsedPercent)
|
||||
conn, _ := net.ProtoCounters(nil)
|
||||
io1, _ := net.IOCounters(false)
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
io2, _ := net.IOCounters(false)
|
||||
if len(io2) > 0 && len(io1) > 0 {
|
||||
m["io_send"] = (io2[0].BytesSent - io1[0].BytesSent) * 2
|
||||
m["io_recv"] = (io2[0].BytesRecv - io1[0].BytesRecv) * 2
|
||||
}
|
||||
t := time.Now()
|
||||
m["time"] = strconv.Itoa(t.Hour()) + ":" + strconv.Itoa(t.Minute()) + ":" + strconv.Itoa(t.Second())
|
||||
|
||||
for _, v := range conn {
|
||||
m[v.Protocol] = v.Stats["CurrEstab"]
|
||||
}
|
||||
if len(serverStatus) >= 1440 {
|
||||
serverStatus = serverStatus[1:]
|
||||
}
|
||||
serverStatus = append(serverStatus, m)
|
||||
}
|
||||
}
|
||||
|
||||
-123
@@ -1,123 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/cnlh/nps/lib/beego"
|
||||
"github.com/cnlh/nps/bridge"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/lg"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type TunnelModeServer struct {
|
||||
server
|
||||
process process
|
||||
listener *net.TCPListener
|
||||
}
|
||||
|
||||
//tcp|http|host
|
||||
func NewTunnelModeServer(process process, bridge *bridge.Bridge, task *file.Tunnel) *TunnelModeServer {
|
||||
s := new(TunnelModeServer)
|
||||
s.bridge = bridge
|
||||
s.process = process
|
||||
s.task = task
|
||||
s.config = file.DeepCopyConfig(task.Config)
|
||||
return s
|
||||
}
|
||||
|
||||
//开始
|
||||
func (s *TunnelModeServer) Start() error {
|
||||
var err error
|
||||
s.listener, err = net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), s.task.TcpPort, ""})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
c, err := s.listener.AcceptTCP()
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "use of closed network connection") {
|
||||
break
|
||||
}
|
||||
lg.Println(err)
|
||||
continue
|
||||
}
|
||||
go s.process(conn.NewConn(c), s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//与客户端建立通道
|
||||
func (s *TunnelModeServer) dealClient(c *conn.Conn, cnf *file.Config, addr string, method string, rb []byte) error {
|
||||
link := conn.NewLink(s.task.Client.GetId(), common.CONN_TCP, addr, cnf.CompressEncode, cnf.CompressDecode, cnf.Crypt, c, s.task.Flow, nil, s.task.Client.Rate, nil)
|
||||
|
||||
if tunnel, err := s.bridge.SendLinkInfo(s.task.Client.Id, link); err != nil {
|
||||
c.Close()
|
||||
return err
|
||||
} else {
|
||||
s.linkCopy(link, c, rb, tunnel, s.task.Flow)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//close
|
||||
func (s *TunnelModeServer) Close() error {
|
||||
return s.listener.Close()
|
||||
}
|
||||
|
||||
//web管理方式
|
||||
type WebServer struct {
|
||||
server
|
||||
}
|
||||
|
||||
//开始
|
||||
func (s *WebServer) Start() error {
|
||||
p, _ := beego.AppConfig.Int("httpport")
|
||||
if !common.TestTcpPort(p) {
|
||||
lg.Fatalln("web管理端口", p, "被占用!")
|
||||
}
|
||||
beego.BConfig.WebConfig.Session.SessionOn = true
|
||||
lg.Println("web管理启动,访问端口为", p)
|
||||
beego.SetStaticPath("/static", filepath.Join(common.GetRunPath(), "web", "static"))
|
||||
beego.SetViewsPath(filepath.Join(common.GetRunPath(), "web", "views"))
|
||||
beego.Run()
|
||||
return errors.New("web管理启动失败")
|
||||
}
|
||||
|
||||
//new
|
||||
func NewWebServer(bridge *bridge.Bridge) *WebServer {
|
||||
s := new(WebServer)
|
||||
s.bridge = bridge
|
||||
return s
|
||||
}
|
||||
|
||||
type process func(c *conn.Conn, s *TunnelModeServer) error
|
||||
|
||||
//tcp隧道模式
|
||||
func ProcessTunnel(c *conn.Conn, s *TunnelModeServer) error {
|
||||
if !s.ResetConfig() {
|
||||
c.Close()
|
||||
return errors.New("流量超出")
|
||||
}
|
||||
return s.dealClient(c, s.config, s.task.Target, "", nil)
|
||||
}
|
||||
|
||||
//http代理模式
|
||||
func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error {
|
||||
if !s.ResetConfig() {
|
||||
c.Close()
|
||||
return errors.New("流量超出")
|
||||
}
|
||||
method, addr, rb, err, r := c.GetHost()
|
||||
if err != nil {
|
||||
c.Close()
|
||||
return err
|
||||
}
|
||||
if err := s.auth(r, c, s.config.U, s.config.P); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.dealClient(c, s.config, addr, method, rb)
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
package server
|
||||
package test
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/beego"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
"log"
|
||||
"strconv"
|
||||
)
|
||||
@@ -12,23 +12,23 @@ func TestServerConfig() {
|
||||
var postTcpArr []int
|
||||
var postUdpArr []int
|
||||
for _, v := range file.GetCsvDb().Tasks {
|
||||
if v.Mode == "udpServer" {
|
||||
isInArr(&postUdpArr, v.TcpPort, v.Remark, "udp")
|
||||
if v.Mode == "udp" {
|
||||
isInArr(&postUdpArr, v.Port, v.Remark, "udp")
|
||||
} else {
|
||||
isInArr(&postTcpArr, v.TcpPort, v.Remark, "tcp")
|
||||
isInArr(&postTcpArr, v.Port, v.Remark, "tcp")
|
||||
}
|
||||
}
|
||||
p, err := beego.AppConfig.Int("httpport")
|
||||
p, err := beego.AppConfig.Int("web_port")
|
||||
if err != nil {
|
||||
log.Fatalln("Getting web management port error :", err)
|
||||
} else {
|
||||
isInArr(&postTcpArr, p, "Web Management port", "tcp")
|
||||
}
|
||||
|
||||
if p := beego.AppConfig.String("bridgePort"); p != "" {
|
||||
if p := beego.AppConfig.String("bridge_port"); p != "" {
|
||||
if port, err := strconv.Atoi(p); err != nil {
|
||||
log.Fatalln("get Server and client communication portserror:", err)
|
||||
} else if beego.AppConfig.String("bridgeType") == "kcp" {
|
||||
} else if beego.AppConfig.String("bridge_type") == "kcp" {
|
||||
isInArr(&postUdpArr, port, "Server and client communication ports", "udp")
|
||||
} else {
|
||||
isInArr(&postTcpArr, port, "Server and client communication ports", "tcp")
|
||||
@@ -42,7 +42,7 @@ func TestServerConfig() {
|
||||
isInArr(&postTcpArr, port, "https port", "tcp")
|
||||
}
|
||||
}
|
||||
if p := beego.AppConfig.String("httpsProxyPort"); p != "" {
|
||||
if p := beego.AppConfig.String("https_proxy_port"); p != "" {
|
||||
if port, err := strconv.Atoi(p); err != nil {
|
||||
log.Fatalln("get https port error", err)
|
||||
} else {
|
||||
@@ -72,7 +72,6 @@ func isInArr(arr *[]int, val int, remark string, tp string) {
|
||||
log.Fatalf("open the %d port error ,remark: %s", val, remark)
|
||||
}
|
||||
}
|
||||
|
||||
*arr = append(*arr, val)
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
)
|
||||
|
||||
var ports []int
|
||||
|
||||
func init() {
|
||||
p := beego.AppConfig.String("allow_ports")
|
||||
ports = common.GetPorts(p)
|
||||
}
|
||||
|
||||
func TestServerPort(p int, m string) (b bool) {
|
||||
if p > 65535 || p < 0 {
|
||||
return false
|
||||
}
|
||||
if len(ports) != 0 {
|
||||
if !common.InIntArr(ports, p) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if m == "udp" {
|
||||
b = common.TestUdpPort(p)
|
||||
} else {
|
||||
b = common.TestTcpPort(p)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -121,7 +121,7 @@ doLit:
|
||||
//
|
||||
// This always copies 16 bytes, instead of only length bytes, but that's
|
||||
// OK. If the input is a valid Snappy encoding then subsequent iterations
|
||||
// will fix up the overrun. Otherwise, Decode returns a nil []byte (and a
|
||||
// will fix up the overserver. Otherwise, Decode returns a nil []byte (and a
|
||||
// non-nil error), so the overrun will be ignored.
|
||||
//
|
||||
// Note that on amd64, it is legal and cheap to issue unaligned 8-byte or
|
||||
@@ -473,7 +473,7 @@ emitLiteralFastPath:
|
||||
// (Encode's documentation says that dst and src must not overlap.)
|
||||
//
|
||||
// This always copies 16 bytes, instead of only len(lit) bytes, but that's
|
||||
// OK. Subsequent iterations will fix up the overrun.
|
||||
// OK. Subsequent iterations will fix up the overserver.
|
||||
//
|
||||
// Note that on amd64, it is legal and cheap to issue unaligned 8-byte or
|
||||
// 16-byte loads and stores. This technique probably wouldn't be as
|
||||
@@ -0,0 +1,168 @@
|
||||
// Copyright 2018 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
noDeadline = time.Time{}
|
||||
aLongTimeAgo = time.Unix(1, 0)
|
||||
)
|
||||
|
||||
func (d *Dialer) connect(ctx context.Context, c net.Conn, address string) (_ net.Addr, ctxErr error) {
|
||||
host, port, err := splitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if deadline, ok := ctx.Deadline(); ok && !deadline.IsZero() {
|
||||
c.SetDeadline(deadline)
|
||||
defer c.SetDeadline(noDeadline)
|
||||
}
|
||||
if ctx != context.Background() {
|
||||
errCh := make(chan error, 1)
|
||||
done := make(chan struct{})
|
||||
defer func() {
|
||||
close(done)
|
||||
if ctxErr == nil {
|
||||
ctxErr = <-errCh
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
c.SetDeadline(aLongTimeAgo)
|
||||
errCh <- ctx.Err()
|
||||
case <-done:
|
||||
errCh <- nil
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
b := make([]byte, 0, 6+len(host)) // the size here is just an estimate
|
||||
b = append(b, Version5)
|
||||
if len(d.AuthMethods) == 0 || d.Authenticate == nil {
|
||||
b = append(b, 1, byte(AuthMethodNotRequired))
|
||||
} else {
|
||||
ams := d.AuthMethods
|
||||
if len(ams) > 255 {
|
||||
return nil, errors.New("too many authentication methods")
|
||||
}
|
||||
b = append(b, byte(len(ams)))
|
||||
for _, am := range ams {
|
||||
b = append(b, byte(am))
|
||||
}
|
||||
}
|
||||
if _, ctxErr = c.Write(b); ctxErr != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if _, ctxErr = io.ReadFull(c, b[:2]); ctxErr != nil {
|
||||
return
|
||||
}
|
||||
if b[0] != Version5 {
|
||||
return nil, errors.New("unexpected protocol version " + strconv.Itoa(int(b[0])))
|
||||
}
|
||||
am := AuthMethod(b[1])
|
||||
if am == AuthMethodNoAcceptableMethods {
|
||||
return nil, errors.New("no acceptable authentication methods")
|
||||
}
|
||||
if d.Authenticate != nil {
|
||||
if ctxErr = d.Authenticate(ctx, c, am); ctxErr != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
b = b[:0]
|
||||
b = append(b, Version5, byte(d.cmd), 0)
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
if ip4 := ip.To4(); ip4 != nil {
|
||||
b = append(b, AddrTypeIPv4)
|
||||
b = append(b, ip4...)
|
||||
} else if ip6 := ip.To16(); ip6 != nil {
|
||||
b = append(b, AddrTypeIPv6)
|
||||
b = append(b, ip6...)
|
||||
} else {
|
||||
return nil, errors.New("unknown address type")
|
||||
}
|
||||
} else {
|
||||
if len(host) > 255 {
|
||||
return nil, errors.New("FQDN too long")
|
||||
}
|
||||
b = append(b, AddrTypeFQDN)
|
||||
b = append(b, byte(len(host)))
|
||||
b = append(b, host...)
|
||||
}
|
||||
b = append(b, byte(port>>8), byte(port))
|
||||
if _, ctxErr = c.Write(b); ctxErr != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if _, ctxErr = io.ReadFull(c, b[:4]); ctxErr != nil {
|
||||
return
|
||||
}
|
||||
if b[0] != Version5 {
|
||||
return nil, errors.New("unexpected protocol version " + strconv.Itoa(int(b[0])))
|
||||
}
|
||||
if cmdErr := Reply(b[1]); cmdErr != StatusSucceeded {
|
||||
return nil, errors.New("unknown error " + cmdErr.String())
|
||||
}
|
||||
if b[2] != 0 {
|
||||
return nil, errors.New("non-zero reserved field")
|
||||
}
|
||||
l := 2
|
||||
var a Addr
|
||||
switch b[3] {
|
||||
case AddrTypeIPv4:
|
||||
l += net.IPv4len
|
||||
a.IP = make(net.IP, net.IPv4len)
|
||||
case AddrTypeIPv6:
|
||||
l += net.IPv6len
|
||||
a.IP = make(net.IP, net.IPv6len)
|
||||
case AddrTypeFQDN:
|
||||
if _, err := io.ReadFull(c, b[:1]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l += int(b[0])
|
||||
default:
|
||||
return nil, errors.New("unknown address type " + strconv.Itoa(int(b[3])))
|
||||
}
|
||||
if cap(b) < l {
|
||||
b = make([]byte, l)
|
||||
} else {
|
||||
b = b[:l]
|
||||
}
|
||||
if _, ctxErr = io.ReadFull(c, b); ctxErr != nil {
|
||||
return
|
||||
}
|
||||
if a.IP != nil {
|
||||
copy(a.IP, b)
|
||||
} else {
|
||||
a.Name = string(b[:len(b)-2])
|
||||
}
|
||||
a.Port = int(b[len(b)-2])<<8 | int(b[len(b)-1])
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
func splitHostPort(address string) (string, int, error) {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
portnum, err := strconv.Atoi(port)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
if 1 > portnum || portnum > 0xffff {
|
||||
return "", 0, errors.New("port number out of range " + port)
|
||||
}
|
||||
return host, portnum, nil
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
// Copyright 2018 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package socks_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/internal/socks"
|
||||
"golang.org/x/net/internal/sockstest"
|
||||
)
|
||||
|
||||
func TestDial(t *testing.T) {
|
||||
t.Run("Connect", func(t *testing.T) {
|
||||
ss, err := sockstest.NewServer(sockstest.NoAuthRequired, sockstest.NoProxyRequired)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ss.Close()
|
||||
d := socks.NewDialer(ss.Addr().Network(), ss.Addr().String())
|
||||
d.AuthMethods = []socks.AuthMethod{
|
||||
socks.AuthMethodNotRequired,
|
||||
socks.AuthMethodUsernamePassword,
|
||||
}
|
||||
d.Authenticate = (&socks.UsernamePassword{
|
||||
Username: "username",
|
||||
Password: "password",
|
||||
}).Authenticate
|
||||
c, err := d.DialContext(context.Background(), ss.TargetAddr().Network(), ss.TargetAddr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.(*socks.Conn).BoundAddr()
|
||||
c.Close()
|
||||
})
|
||||
t.Run("ConnectWithConn", func(t *testing.T) {
|
||||
ss, err := sockstest.NewServer(sockstest.NoAuthRequired, sockstest.NoProxyRequired)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ss.Close()
|
||||
c, err := net.Dial(ss.Addr().Network(), ss.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
d := socks.NewDialer(ss.Addr().Network(), ss.Addr().String())
|
||||
d.AuthMethods = []socks.AuthMethod{
|
||||
socks.AuthMethodNotRequired,
|
||||
socks.AuthMethodUsernamePassword,
|
||||
}
|
||||
d.Authenticate = (&socks.UsernamePassword{
|
||||
Username: "username",
|
||||
Password: "password",
|
||||
}).Authenticate
|
||||
a, err := d.DialWithConn(context.Background(), c, ss.TargetAddr().Network(), ss.TargetAddr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := a.(*socks.Addr); !ok {
|
||||
t.Fatalf("got %+v; want socks.Addr", a)
|
||||
}
|
||||
})
|
||||
t.Run("Cancel", func(t *testing.T) {
|
||||
ss, err := sockstest.NewServer(sockstest.NoAuthRequired, blackholeCmdFunc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ss.Close()
|
||||
d := socks.NewDialer(ss.Addr().Network(), ss.Addr().String())
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
dialErr := make(chan error)
|
||||
go func() {
|
||||
c, err := d.DialContext(ctx, ss.TargetAddr().Network(), ss.TargetAddr().String())
|
||||
if err == nil {
|
||||
c.Close()
|
||||
}
|
||||
dialErr <- err
|
||||
}()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
cancel()
|
||||
err = <-dialErr
|
||||
if perr, nerr := parseDialError(err); perr != context.Canceled && nerr == nil {
|
||||
t.Fatalf("got %v; want context.Canceled or equivalent", err)
|
||||
}
|
||||
})
|
||||
t.Run("Deadline", func(t *testing.T) {
|
||||
ss, err := sockstest.NewServer(sockstest.NoAuthRequired, blackholeCmdFunc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ss.Close()
|
||||
d := socks.NewDialer(ss.Addr().Network(), ss.Addr().String())
|
||||
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(100*time.Millisecond))
|
||||
defer cancel()
|
||||
c, err := d.DialContext(ctx, ss.TargetAddr().Network(), ss.TargetAddr().String())
|
||||
if err == nil {
|
||||
c.Close()
|
||||
}
|
||||
if perr, nerr := parseDialError(err); perr != context.DeadlineExceeded && nerr == nil {
|
||||
t.Fatalf("got %v; want context.DeadlineExceeded or equivalent", err)
|
||||
}
|
||||
})
|
||||
t.Run("WithRogueServer", func(t *testing.T) {
|
||||
ss, err := sockstest.NewServer(sockstest.NoAuthRequired, rogueCmdFunc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ss.Close()
|
||||
d := socks.NewDialer(ss.Addr().Network(), ss.Addr().String())
|
||||
for i := 0; i < 2*len(rogueCmdList); i++ {
|
||||
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(100*time.Millisecond))
|
||||
defer cancel()
|
||||
c, err := d.DialContext(ctx, ss.TargetAddr().Network(), ss.TargetAddr().String())
|
||||
if err == nil {
|
||||
t.Log(c.(*socks.Conn).BoundAddr())
|
||||
c.Close()
|
||||
t.Error("should fail")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func blackholeCmdFunc(rw io.ReadWriter, b []byte) error {
|
||||
if _, err := sockstest.ParseCmdRequest(b); err != nil {
|
||||
return err
|
||||
}
|
||||
var bb [1]byte
|
||||
for {
|
||||
if _, err := rw.Read(bb[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func rogueCmdFunc(rw io.ReadWriter, b []byte) error {
|
||||
if _, err := sockstest.ParseCmdRequest(b); err != nil {
|
||||
return err
|
||||
}
|
||||
rw.Write(rogueCmdList[rand.Intn(len(rogueCmdList))])
|
||||
return nil
|
||||
}
|
||||
|
||||
var rogueCmdList = [][]byte{
|
||||
{0x05},
|
||||
{0x06, 0x00, 0x00, 0x01, 192, 0, 2, 1, 0x17, 0x4b},
|
||||
{0x05, 0x00, 0xff, 0x01, 192, 0, 2, 2, 0x17, 0x4b},
|
||||
{0x05, 0x00, 0x00, 0x01, 192, 0, 2, 3},
|
||||
{0x05, 0x00, 0x00, 0x03, 0x04, 'F', 'Q', 'D', 'N'},
|
||||
}
|
||||
|
||||
func parseDialError(err error) (perr, nerr error) {
|
||||
if e, ok := err.(*net.OpError); ok {
|
||||
err = e.Err
|
||||
nerr = e
|
||||
}
|
||||
if e, ok := err.(*os.SyscallError); ok {
|
||||
err = e.Err
|
||||
}
|
||||
perr = err
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
// Copyright 2018 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package socks provides a SOCKS version 5 client implementation.
|
||||
//
|
||||
// SOCKS protocol version 5 is defined in RFC 1928.
|
||||
// Username/Password authentication for SOCKS version 5 is defined in
|
||||
// RFC 1929.
|
||||
package socks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// A Command represents a SOCKS command.
|
||||
type Command int
|
||||
|
||||
func (cmd Command) String() string {
|
||||
switch cmd {
|
||||
case CmdConnect:
|
||||
return "socks connect"
|
||||
case cmdBind:
|
||||
return "socks bind"
|
||||
default:
|
||||
return "socks " + strconv.Itoa(int(cmd))
|
||||
}
|
||||
}
|
||||
|
||||
// An AuthMethod represents a SOCKS authentication method.
|
||||
type AuthMethod int
|
||||
|
||||
// A Reply represents a SOCKS command reply code.
|
||||
type Reply int
|
||||
|
||||
func (code Reply) String() string {
|
||||
switch code {
|
||||
case StatusSucceeded:
|
||||
return "succeeded"
|
||||
case 0x01:
|
||||
return "general SOCKS server failure"
|
||||
case 0x02:
|
||||
return "connection not allowed by ruleset"
|
||||
case 0x03:
|
||||
return "network unreachable"
|
||||
case 0x04:
|
||||
return "host unreachable"
|
||||
case 0x05:
|
||||
return "connection refused"
|
||||
case 0x06:
|
||||
return "TTL expired"
|
||||
case 0x07:
|
||||
return "command not supported"
|
||||
case 0x08:
|
||||
return "address type not supported"
|
||||
default:
|
||||
return "unknown code: " + strconv.Itoa(int(code))
|
||||
}
|
||||
}
|
||||
|
||||
// Wire protocol constants.
|
||||
const (
|
||||
Version5 = 0x05
|
||||
|
||||
AddrTypeIPv4 = 0x01
|
||||
AddrTypeFQDN = 0x03
|
||||
AddrTypeIPv6 = 0x04
|
||||
|
||||
CmdConnect Command = 0x01 // establishes an active-open forward proxy connection
|
||||
cmdBind Command = 0x02 // establishes a passive-open forward proxy connection
|
||||
|
||||
AuthMethodNotRequired AuthMethod = 0x00 // no authentication required
|
||||
AuthMethodUsernamePassword AuthMethod = 0x02 // use username/password
|
||||
AuthMethodNoAcceptableMethods AuthMethod = 0xff // no acceptable authentication methods
|
||||
|
||||
StatusSucceeded Reply = 0x00
|
||||
)
|
||||
|
||||
// An Addr represents a SOCKS-specific address.
|
||||
// Either Name or IP is used exclusively.
|
||||
type Addr struct {
|
||||
Name string // fully-qualified domain name
|
||||
IP net.IP
|
||||
Port int
|
||||
}
|
||||
|
||||
func (a *Addr) Network() string { return "socks" }
|
||||
|
||||
func (a *Addr) String() string {
|
||||
if a == nil {
|
||||
return "<nil>"
|
||||
}
|
||||
port := strconv.Itoa(a.Port)
|
||||
if a.IP == nil {
|
||||
return net.JoinHostPort(a.Name, port)
|
||||
}
|
||||
return net.JoinHostPort(a.IP.String(), port)
|
||||
}
|
||||
|
||||
// A Conn represents a forward proxy connection.
|
||||
type Conn struct {
|
||||
net.Conn
|
||||
|
||||
boundAddr net.Addr
|
||||
}
|
||||
|
||||
// BoundAddr returns the address assigned by the proxy server for
|
||||
// connecting to the command target address from the proxy server.
|
||||
func (c *Conn) BoundAddr() net.Addr {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
return c.boundAddr
|
||||
}
|
||||
|
||||
// A Dialer holds SOCKS-specific options.
|
||||
type Dialer struct {
|
||||
cmd Command // either CmdConnect or cmdBind
|
||||
proxyNetwork string // network between a proxy server and a client
|
||||
proxyAddress string // proxy server address
|
||||
|
||||
// ProxyDial specifies the optional dial function for
|
||||
// establishing the transport connection.
|
||||
ProxyDial func(context.Context, string, string) (net.Conn, error)
|
||||
|
||||
// AuthMethods specifies the list of request authention
|
||||
// methods.
|
||||
// If empty, SOCKS client requests only AuthMethodNotRequired.
|
||||
AuthMethods []AuthMethod
|
||||
|
||||
// Authenticate specifies the optional authentication
|
||||
// function. It must be non-nil when AuthMethods is not empty.
|
||||
// It must return an error when the authentication is failed.
|
||||
Authenticate func(context.Context, io.ReadWriter, AuthMethod) error
|
||||
}
|
||||
|
||||
// DialContext connects to the provided address on the provided
|
||||
// network.
|
||||
//
|
||||
// The returned error value may be a net.OpError. When the Op field of
|
||||
// net.OpError contains "socks", the Source field contains a proxy
|
||||
// server address and the Addr field contains a command target
|
||||
// address.
|
||||
//
|
||||
// See func Dial of the net package of standard library for a
|
||||
// description of the network and address parameters.
|
||||
func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
if err := d.validateTarget(network, address); err != nil {
|
||||
proxy, dst, _ := d.pathAddrs(address)
|
||||
return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err}
|
||||
}
|
||||
if ctx == nil {
|
||||
proxy, dst, _ := d.pathAddrs(address)
|
||||
return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: errors.New("nil context")}
|
||||
}
|
||||
var err error
|
||||
var c net.Conn
|
||||
if d.ProxyDial != nil {
|
||||
c, err = d.ProxyDial(ctx, d.proxyNetwork, d.proxyAddress)
|
||||
} else {
|
||||
var dd net.Dialer
|
||||
c, err = dd.DialContext(ctx, d.proxyNetwork, d.proxyAddress)
|
||||
}
|
||||
if err != nil {
|
||||
proxy, dst, _ := d.pathAddrs(address)
|
||||
return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err}
|
||||
}
|
||||
a, err := d.connect(ctx, c, address)
|
||||
if err != nil {
|
||||
c.Close()
|
||||
proxy, dst, _ := d.pathAddrs(address)
|
||||
return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err}
|
||||
}
|
||||
return &Conn{Conn: c, boundAddr: a}, nil
|
||||
}
|
||||
|
||||
// DialWithConn initiates a connection from SOCKS server to the target
|
||||
// network and address using the connection c that is already
|
||||
// connected to the SOCKS server.
|
||||
//
|
||||
// It returns the connection's local address assigned by the SOCKS
|
||||
// server.
|
||||
func (d *Dialer) DialWithConn(ctx context.Context, c net.Conn, network, address string) (net.Addr, error) {
|
||||
if err := d.validateTarget(network, address); err != nil {
|
||||
proxy, dst, _ := d.pathAddrs(address)
|
||||
return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err}
|
||||
}
|
||||
if ctx == nil {
|
||||
proxy, dst, _ := d.pathAddrs(address)
|
||||
return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: errors.New("nil context")}
|
||||
}
|
||||
a, err := d.connect(ctx, c, address)
|
||||
if err != nil {
|
||||
proxy, dst, _ := d.pathAddrs(address)
|
||||
return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err}
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// Dial connects to the provided address on the provided network.
|
||||
//
|
||||
// Unlike DialContext, it returns a raw transport connection instead
|
||||
// of a forward proxy connection.
|
||||
//
|
||||
// Deprecated: Use DialContext or DialWithConn instead.
|
||||
func (d *Dialer) Dial(network, address string) (net.Conn, error) {
|
||||
if err := d.validateTarget(network, address); err != nil {
|
||||
proxy, dst, _ := d.pathAddrs(address)
|
||||
return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err}
|
||||
}
|
||||
var err error
|
||||
var c net.Conn
|
||||
if d.ProxyDial != nil {
|
||||
c, err = d.ProxyDial(context.Background(), d.proxyNetwork, d.proxyAddress)
|
||||
} else {
|
||||
c, err = net.Dial(d.proxyNetwork, d.proxyAddress)
|
||||
}
|
||||
if err != nil {
|
||||
proxy, dst, _ := d.pathAddrs(address)
|
||||
return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err}
|
||||
}
|
||||
if _, err := d.DialWithConn(context.Background(), c, network, address); err != nil {
|
||||
c.Close()
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (d *Dialer) validateTarget(network, address string) error {
|
||||
switch network {
|
||||
case "tcp", "tcp6", "tcp4":
|
||||
default:
|
||||
return errors.New("network not implemented")
|
||||
}
|
||||
switch d.cmd {
|
||||
case CmdConnect, cmdBind:
|
||||
default:
|
||||
return errors.New("command not implemented")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Dialer) pathAddrs(address string) (proxy, dst net.Addr, err error) {
|
||||
for i, s := range []string{d.proxyAddress, address} {
|
||||
host, port, err := splitHostPort(s)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
a := &Addr{Port: port}
|
||||
a.IP = net.ParseIP(host)
|
||||
if a.IP == nil {
|
||||
a.Name = host
|
||||
}
|
||||
if i == 0 {
|
||||
proxy = a
|
||||
} else {
|
||||
dst = a
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// NewDialer returns a new Dialer that dials through the provided
|
||||
// proxy server's network and address.
|
||||
func NewDialer(network, address string) *Dialer {
|
||||
return &Dialer{proxyNetwork: network, proxyAddress: address, cmd: CmdConnect}
|
||||
}
|
||||
|
||||
const (
|
||||
authUsernamePasswordVersion = 0x01
|
||||
authStatusSucceeded = 0x00
|
||||
)
|
||||
|
||||
// UsernamePassword are the credentials for the username/password
|
||||
// authentication method.
|
||||
type UsernamePassword struct {
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
// Authenticate authenticates a pair of username and password with the
|
||||
// proxy server.
|
||||
func (up *UsernamePassword) Authenticate(ctx context.Context, rw io.ReadWriter, auth AuthMethod) error {
|
||||
switch auth {
|
||||
case AuthMethodNotRequired:
|
||||
return nil
|
||||
case AuthMethodUsernamePassword:
|
||||
if len(up.Username) == 0 || len(up.Username) > 255 || len(up.Password) == 0 || len(up.Password) > 255 {
|
||||
return errors.New("invalid username/password")
|
||||
}
|
||||
b := []byte{authUsernamePasswordVersion}
|
||||
b = append(b, byte(len(up.Username)))
|
||||
b = append(b, up.Username...)
|
||||
b = append(b, byte(len(up.Password)))
|
||||
b = append(b, up.Password...)
|
||||
// TODO(mikio): handle IO deadlines and cancelation if
|
||||
// necessary
|
||||
if _, err := rw.Write(b); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := io.ReadFull(rw, b[:2]); err != nil {
|
||||
return err
|
||||
}
|
||||
if b[0] != authUsernamePasswordVersion {
|
||||
return errors.New("invalid username/password version")
|
||||
}
|
||||
if b[1] != authStatusSucceeded {
|
||||
return errors.New("username/password authentication failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return errors.New("unsupported authentication method " + strconv.Itoa(int(auth)))
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"net"
|
||||
)
|
||||
|
||||
type direct struct{}
|
||||
|
||||
// Direct is a direct proxy: one that makes network connections directly.
|
||||
var Direct = direct{}
|
||||
|
||||
func (direct) Dial(network, addr string) (net.Conn, error) {
|
||||
return net.Dial(network, addr)
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A PerHost directs connections to a default Dialer unless the host name
|
||||
// requested matches one of a number of exceptions.
|
||||
type PerHost struct {
|
||||
def, bypass Dialer
|
||||
|
||||
bypassNetworks []*net.IPNet
|
||||
bypassIPs []net.IP
|
||||
bypassZones []string
|
||||
bypassHosts []string
|
||||
}
|
||||
|
||||
// NewPerHost returns a PerHost Dialer that directs connections to either
|
||||
// defaultDialer or bypass, depending on whether the connection matches one of
|
||||
// the configured rules.
|
||||
func NewPerHost(defaultDialer, bypass Dialer) *PerHost {
|
||||
return &PerHost{
|
||||
def: defaultDialer,
|
||||
bypass: bypass,
|
||||
}
|
||||
}
|
||||
|
||||
// Dial connects to the address addr on the given network through either
|
||||
// defaultDialer or bypass.
|
||||
func (p *PerHost) Dial(network, addr string) (c net.Conn, err error) {
|
||||
host, _, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return p.dialerForRequest(host).Dial(network, addr)
|
||||
}
|
||||
|
||||
func (p *PerHost) dialerForRequest(host string) Dialer {
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
for _, net := range p.bypassNetworks {
|
||||
if net.Contains(ip) {
|
||||
return p.bypass
|
||||
}
|
||||
}
|
||||
for _, bypassIP := range p.bypassIPs {
|
||||
if bypassIP.Equal(ip) {
|
||||
return p.bypass
|
||||
}
|
||||
}
|
||||
return p.def
|
||||
}
|
||||
|
||||
for _, zone := range p.bypassZones {
|
||||
if strings.HasSuffix(host, zone) {
|
||||
return p.bypass
|
||||
}
|
||||
if host == zone[1:] {
|
||||
// For a zone ".example.com", we match "example.com"
|
||||
// too.
|
||||
return p.bypass
|
||||
}
|
||||
}
|
||||
for _, bypassHost := range p.bypassHosts {
|
||||
if bypassHost == host {
|
||||
return p.bypass
|
||||
}
|
||||
}
|
||||
return p.def
|
||||
}
|
||||
|
||||
// AddFromString parses a string that contains comma-separated values
|
||||
// specifying hosts that should use the bypass proxy. Each value is either an
|
||||
// IP address, a CIDR range, a zone (*.example.com) or a host name
|
||||
// (localhost). A best effort is made to parse the string and errors are
|
||||
// ignored.
|
||||
func (p *PerHost) AddFromString(s string) {
|
||||
hosts := strings.Split(s, ",")
|
||||
for _, host := range hosts {
|
||||
host = strings.TrimSpace(host)
|
||||
if len(host) == 0 {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(host, "/") {
|
||||
// We assume that it's a CIDR address like 127.0.0.0/8
|
||||
if _, net, err := net.ParseCIDR(host); err == nil {
|
||||
p.AddNetwork(net)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
p.AddIP(ip)
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(host, "*.") {
|
||||
p.AddZone(host[1:])
|
||||
continue
|
||||
}
|
||||
p.AddHost(host)
|
||||
}
|
||||
}
|
||||
|
||||
// AddIP specifies an IP address that will use the bypass proxy. Note that
|
||||
// this will only take effect if a literal IP address is dialed. A connection
|
||||
// to a named host will never match an IP.
|
||||
func (p *PerHost) AddIP(ip net.IP) {
|
||||
p.bypassIPs = append(p.bypassIPs, ip)
|
||||
}
|
||||
|
||||
// AddNetwork specifies an IP range that will use the bypass proxy. Note that
|
||||
// this will only take effect if a literal IP address is dialed. A connection
|
||||
// to a named host will never match.
|
||||
func (p *PerHost) AddNetwork(net *net.IPNet) {
|
||||
p.bypassNetworks = append(p.bypassNetworks, net)
|
||||
}
|
||||
|
||||
// AddZone specifies a DNS suffix that will use the bypass proxy. A zone of
|
||||
// "example.com" matches "example.com" and all of its subdomains.
|
||||
func (p *PerHost) AddZone(zone string) {
|
||||
if strings.HasSuffix(zone, ".") {
|
||||
zone = zone[:len(zone)-1]
|
||||
}
|
||||
if !strings.HasPrefix(zone, ".") {
|
||||
zone = "." + zone
|
||||
}
|
||||
p.bypassZones = append(p.bypassZones, zone)
|
||||
}
|
||||
|
||||
// AddHost specifies a host name that will use the bypass proxy.
|
||||
func (p *PerHost) AddHost(host string) {
|
||||
if strings.HasSuffix(host, ".") {
|
||||
host = host[:len(host)-1]
|
||||
}
|
||||
p.bypassHosts = append(p.bypassHosts, host)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type recordingProxy struct {
|
||||
addrs []string
|
||||
}
|
||||
|
||||
func (r *recordingProxy) Dial(network, addr string) (net.Conn, error) {
|
||||
r.addrs = append(r.addrs, addr)
|
||||
return nil, errors.New("recordingProxy")
|
||||
}
|
||||
|
||||
func TestPerHost(t *testing.T) {
|
||||
var def, bypass recordingProxy
|
||||
perHost := NewPerHost(&def, &bypass)
|
||||
perHost.AddFromString("localhost,*.zone,127.0.0.1,10.0.0.1/8,1000::/16")
|
||||
|
||||
expectedDef := []string{
|
||||
"example.com:123",
|
||||
"1.2.3.4:123",
|
||||
"[1001::]:123",
|
||||
}
|
||||
expectedBypass := []string{
|
||||
"localhost:123",
|
||||
"zone:123",
|
||||
"foo.zone:123",
|
||||
"127.0.0.1:123",
|
||||
"10.1.2.3:123",
|
||||
"[1000::]:123",
|
||||
}
|
||||
|
||||
for _, addr := range expectedDef {
|
||||
perHost.Dial("tcp", addr)
|
||||
}
|
||||
for _, addr := range expectedBypass {
|
||||
perHost.Dial("tcp", addr)
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(expectedDef, def.addrs) {
|
||||
t.Errorf("Hosts which went to the default proxy didn't match. Got %v, want %v", def.addrs, expectedDef)
|
||||
}
|
||||
if !reflect.DeepEqual(expectedBypass, bypass.addrs) {
|
||||
t.Errorf("Hosts which went to the bypass proxy didn't match. Got %v, want %v", bypass.addrs, expectedBypass)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package proxy provides support for a variety of protocols to proxy network
|
||||
// data.
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// A Dialer is a means to establish a connection.
|
||||
type Dialer interface {
|
||||
// Dial connects to the given address via the proxy.
|
||||
Dial(network, addr string) (c net.Conn, err error)
|
||||
}
|
||||
|
||||
// Auth contains authentication parameters that specific Dialers may require.
|
||||
type Auth struct {
|
||||
User, Password string
|
||||
}
|
||||
|
||||
// FromEnvironment returns the dialer specified by the proxy related variables in
|
||||
// the environment.
|
||||
func FromEnvironment() Dialer {
|
||||
allProxy := allProxyEnv.Get()
|
||||
if len(allProxy) == 0 {
|
||||
return Direct
|
||||
}
|
||||
|
||||
proxyURL, err := url.Parse(allProxy)
|
||||
if err != nil {
|
||||
return Direct
|
||||
}
|
||||
proxy, err := FromURL(proxyURL, Direct)
|
||||
if err != nil {
|
||||
return Direct
|
||||
}
|
||||
|
||||
noProxy := noProxyEnv.Get()
|
||||
if len(noProxy) == 0 {
|
||||
return proxy
|
||||
}
|
||||
|
||||
perHost := NewPerHost(proxy, Direct)
|
||||
perHost.AddFromString(noProxy)
|
||||
return perHost
|
||||
}
|
||||
|
||||
// proxySchemes is a map from URL schemes to a function that creates a Dialer
|
||||
// from a URL with such a scheme.
|
||||
var proxySchemes map[string]func(*url.URL, Dialer) (Dialer, error)
|
||||
|
||||
// RegisterDialerType takes a URL scheme and a function to generate Dialers from
|
||||
// a URL with that scheme and a forwarding Dialer. Registered schemes are used
|
||||
// by FromURL.
|
||||
func RegisterDialerType(scheme string, f func(*url.URL, Dialer) (Dialer, error)) {
|
||||
if proxySchemes == nil {
|
||||
proxySchemes = make(map[string]func(*url.URL, Dialer) (Dialer, error))
|
||||
}
|
||||
proxySchemes[scheme] = f
|
||||
}
|
||||
|
||||
// FromURL returns a Dialer given a URL specification and an underlying
|
||||
// Dialer for it to make network requests.
|
||||
func FromURL(u *url.URL, forward Dialer) (Dialer, error) {
|
||||
var auth *Auth
|
||||
if u.User != nil {
|
||||
auth = new(Auth)
|
||||
auth.User = u.User.Username()
|
||||
if p, ok := u.User.Password(); ok {
|
||||
auth.Password = p
|
||||
}
|
||||
}
|
||||
|
||||
switch u.Scheme {
|
||||
case "socks5":
|
||||
return SOCKS5("tcp", u.Host, auth, forward)
|
||||
}
|
||||
|
||||
// If the scheme doesn't match any of the built-in schemes, see if it
|
||||
// was registered by another package.
|
||||
if proxySchemes != nil {
|
||||
if f, ok := proxySchemes[u.Scheme]; ok {
|
||||
return f(u, forward)
|
||||
}
|
||||
}
|
||||
|
||||
return nil, errors.New("proxy: unknown scheme: " + u.Scheme)
|
||||
}
|
||||
|
||||
var (
|
||||
allProxyEnv = &envOnce{
|
||||
names: []string{"ALL_PROXY", "all_proxy"},
|
||||
}
|
||||
noProxyEnv = &envOnce{
|
||||
names: []string{"NO_PROXY", "no_proxy"},
|
||||
}
|
||||
)
|
||||
|
||||
// envOnce looks up an environment variable (optionally by multiple
|
||||
// names) once. It mitigates expensive lookups on some platforms
|
||||
// (e.g. Windows).
|
||||
// (Borrowed from net/http/transport.go)
|
||||
type envOnce struct {
|
||||
names []string
|
||||
once sync.Once
|
||||
val string
|
||||
}
|
||||
|
||||
func (e *envOnce) Get() string {
|
||||
e.once.Do(e.init)
|
||||
return e.val
|
||||
}
|
||||
|
||||
func (e *envOnce) init() {
|
||||
for _, n := range e.names {
|
||||
e.val = os.Getenv(n)
|
||||
if e.val != "" {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// reset is used by tests
|
||||
func (e *envOnce) reset() {
|
||||
e.once = sync.Once{}
|
||||
e.val = ""
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/net/internal/sockstest"
|
||||
)
|
||||
|
||||
type proxyFromEnvTest struct {
|
||||
allProxyEnv string
|
||||
noProxyEnv string
|
||||
wantTypeOf Dialer
|
||||
}
|
||||
|
||||
func (t proxyFromEnvTest) String() string {
|
||||
var buf bytes.Buffer
|
||||
space := func() {
|
||||
if buf.Len() > 0 {
|
||||
buf.WriteByte(' ')
|
||||
}
|
||||
}
|
||||
if t.allProxyEnv != "" {
|
||||
fmt.Fprintf(&buf, "all_proxy=%q", t.allProxyEnv)
|
||||
}
|
||||
if t.noProxyEnv != "" {
|
||||
space()
|
||||
fmt.Fprintf(&buf, "no_proxy=%q", t.noProxyEnv)
|
||||
}
|
||||
return strings.TrimSpace(buf.String())
|
||||
}
|
||||
|
||||
func TestFromEnvironment(t *testing.T) {
|
||||
ResetProxyEnv()
|
||||
|
||||
type dummyDialer struct {
|
||||
direct
|
||||
}
|
||||
|
||||
RegisterDialerType("irc", func(_ *url.URL, _ Dialer) (Dialer, error) {
|
||||
return dummyDialer{}, nil
|
||||
})
|
||||
|
||||
proxyFromEnvTests := []proxyFromEnvTest{
|
||||
{allProxyEnv: "127.0.0.1:8080", noProxyEnv: "localhost, 127.0.0.1", wantTypeOf: direct{}},
|
||||
{allProxyEnv: "ftp://example.com:8000", noProxyEnv: "localhost, 127.0.0.1", wantTypeOf: direct{}},
|
||||
{allProxyEnv: "socks5://example.com:8080", noProxyEnv: "localhost, 127.0.0.1", wantTypeOf: &PerHost{}},
|
||||
{allProxyEnv: "irc://example.com:8000", wantTypeOf: dummyDialer{}},
|
||||
{noProxyEnv: "localhost, 127.0.0.1", wantTypeOf: direct{}},
|
||||
{wantTypeOf: direct{}},
|
||||
}
|
||||
|
||||
for _, tt := range proxyFromEnvTests {
|
||||
os.Setenv("ALL_PROXY", tt.allProxyEnv)
|
||||
os.Setenv("NO_PROXY", tt.noProxyEnv)
|
||||
ResetCachedEnvironment()
|
||||
|
||||
d := FromEnvironment()
|
||||
if got, want := fmt.Sprintf("%T", d), fmt.Sprintf("%T", tt.wantTypeOf); got != want {
|
||||
t.Errorf("%v: got type = %T, want %T", tt, d, tt.wantTypeOf)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromURL(t *testing.T) {
|
||||
ss, err := sockstest.NewServer(sockstest.NoAuthRequired, sockstest.NoProxyRequired)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ss.Close()
|
||||
url, err := url.Parse("socks5://user:password@" + ss.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
proxy, err := FromURL(url, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, err := proxy.Dial("tcp", "fqdn.doesnotexist:5963")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.Close()
|
||||
}
|
||||
|
||||
func TestSOCKS5(t *testing.T) {
|
||||
ss, err := sockstest.NewServer(sockstest.NoAuthRequired, sockstest.NoProxyRequired)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ss.Close()
|
||||
proxy, err := SOCKS5("tcp", ss.Addr().String(), nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, err := proxy.Dial("tcp", ss.TargetAddr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.Close()
|
||||
}
|
||||
|
||||
func ResetProxyEnv() {
|
||||
for _, env := range []*envOnce{allProxyEnv, noProxyEnv} {
|
||||
for _, v := range env.names {
|
||||
os.Setenv(v, "")
|
||||
}
|
||||
}
|
||||
ResetCachedEnvironment()
|
||||
}
|
||||
|
||||
func ResetCachedEnvironment() {
|
||||
allProxyEnv.reset()
|
||||
noProxyEnv.reset()
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
|
||||
"github.com/cnlh/nps/vender/golang.org/x/net/internal/socks"
|
||||
)
|
||||
|
||||
// SOCKS5 returns a Dialer that makes SOCKSv5 connections to the given
|
||||
// address with an optional username and password.
|
||||
// See RFC 1928 and RFC 1929.
|
||||
func SOCKS5(network, address string, auth *Auth, forward Dialer) (Dialer, error) {
|
||||
d := socks.NewDialer(network, address)
|
||||
if forward != nil {
|
||||
d.ProxyDial = func(_ context.Context, network string, address string) (net.Conn, error) {
|
||||
return forward.Dial(network, address)
|
||||
}
|
||||
}
|
||||
if auth != nil {
|
||||
up := socks.UsernamePassword{
|
||||
Username: auth.User,
|
||||
Password: auth.Password,
|
||||
}
|
||||
d.AuthMethods = []socks.AuthMethod{
|
||||
socks.AuthMethodNotRequired,
|
||||
socks.AuthMethodUsernamePassword,
|
||||
}
|
||||
d.Authenticate = up.Authenticate
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
)
|
||||
|
||||
type AuthController struct {
|
||||
beego.Controller
|
||||
}
|
||||
|
||||
func (s *AuthController) GetAuthKey() {
|
||||
m := make(map[string]interface{})
|
||||
defer func() {
|
||||
s.Data["json"] = m
|
||||
s.ServeJSON()
|
||||
}()
|
||||
if cryptKey := beego.AppConfig.String("auth_crypt_key"); len(cryptKey) != 16 {
|
||||
m["status"] = 0
|
||||
return
|
||||
} else {
|
||||
b, err := crypt.AesEncrypt([]byte(beego.AppConfig.String("auth_key")), []byte(cryptKey))
|
||||
if err != nil {
|
||||
m["status"] = 0
|
||||
return
|
||||
}
|
||||
m["status"] = 1
|
||||
m["crypt_auth_key"] = string(b)
|
||||
m["crypt_type"] = "aes cbc"
|
||||
return
|
||||
}
|
||||
}
|
||||
+18
-15
@@ -1,11 +1,13 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/beego"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/server"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type BaseController struct {
|
||||
@@ -19,8 +21,13 @@ func (s *BaseController) Prepare() {
|
||||
controllerName, actionName := s.GetControllerAndAction()
|
||||
s.controllerName = strings.ToLower(controllerName[0 : len(controllerName)-10])
|
||||
s.actionName = strings.ToLower(actionName)
|
||||
arr := strings.Split(s.Ctx.Request.RemoteAddr, ":")
|
||||
if len(arr) > 0 && arr[0] != beego.AppConfig.String("authip") {
|
||||
// web api verify
|
||||
// param 1 is md5(authKey+Current timestamp)
|
||||
// param 2 is timestamp (It's limited to 20 seconds.)
|
||||
md5Key := s.GetString("auth_key")
|
||||
timestamp := s.GetIntNoErr("timestamp")
|
||||
configKey := beego.AppConfig.String("auth_key")
|
||||
if !(time.Now().Unix()-int64(timestamp) <= 20 && time.Now().Unix()-int64(timestamp) >= 0 && crypt.Md5(configKey+strconv.Itoa(timestamp)) == md5Key) {
|
||||
if s.GetSession("auth") != true {
|
||||
s.Redirect("/login/index", 302)
|
||||
}
|
||||
@@ -39,9 +46,10 @@ func (s *BaseController) display(tpl ...string) {
|
||||
tplname = s.controllerName + "/" + s.actionName + ".html"
|
||||
}
|
||||
ip := s.Ctx.Request.Host
|
||||
if strings.LastIndex(ip, ":") > 0 {
|
||||
arr := strings.Split(common.GetHostByName(ip), ":")
|
||||
s.Data["ip"] = arr[0]
|
||||
s.Data["ip"] = common.GetIpByAddr(ip)
|
||||
s.Data["bridgeType"] = beego.AppConfig.String("bridge_type")
|
||||
if common.IsWindows() {
|
||||
s.Data["win"] = ".exe"
|
||||
}
|
||||
s.Data["p"] = server.Bridge.TunnelPort
|
||||
s.Data["proxyPort"] = beego.AppConfig.String("hostPort")
|
||||
@@ -90,7 +98,7 @@ func (s *BaseController) AjaxErr(str string) {
|
||||
}
|
||||
|
||||
//组装ajax
|
||||
func ajax(str string, status int) (map[string]interface{}) {
|
||||
func ajax(str string, status int) map[string]interface{} {
|
||||
json := make(map[string]interface{})
|
||||
json["status"] = status
|
||||
json["msg"] = str
|
||||
@@ -100,11 +108,8 @@ func ajax(str string, status int) (map[string]interface{}) {
|
||||
//ajax table返回
|
||||
func (s *BaseController) AjaxTable(list interface{}, cnt int, recordsTotal int) {
|
||||
json := make(map[string]interface{})
|
||||
json["data"] = list
|
||||
json["draw"] = s.GetIntNoErr("draw")
|
||||
json["err"] = ""
|
||||
json["recordsTotal"] = recordsTotal
|
||||
json["recordsFiltered"] = cnt
|
||||
json["rows"] = list
|
||||
json["total"] = recordsTotal
|
||||
s.Data["json"] = json
|
||||
s.ServeJSON()
|
||||
s.StopRun()
|
||||
@@ -112,9 +117,7 @@ func (s *BaseController) AjaxTable(list interface{}, cnt int, recordsTotal int)
|
||||
|
||||
//ajax table参数
|
||||
func (s *BaseController) GetAjaxParams() (start, limit int) {
|
||||
s.Ctx.Input.Bind(&start, "start")
|
||||
s.Ctx.Input.Bind(&limit, "length")
|
||||
return
|
||||
return s.GetIntNoErr("offset"), s.GetIntNoErr("limit")
|
||||
}
|
||||
|
||||
func (s *BaseController) SetInfo(name string) {
|
||||
|
||||
+23
-15
@@ -1,7 +1,7 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
"github.com/cnlh/nps/server"
|
||||
@@ -14,7 +14,7 @@ type ClientController struct {
|
||||
func (s *ClientController) List() {
|
||||
if s.Ctx.Request.Method == "GET" {
|
||||
s.Data["menu"] = "client"
|
||||
s.SetInfo("客户端管理")
|
||||
s.SetInfo("client")
|
||||
s.display("client/list")
|
||||
return
|
||||
}
|
||||
@@ -27,21 +27,22 @@ func (s *ClientController) List() {
|
||||
func (s *ClientController) Add() {
|
||||
if s.Ctx.Request.Method == "GET" {
|
||||
s.Data["menu"] = "client"
|
||||
s.SetInfo("新增")
|
||||
s.SetInfo("add client")
|
||||
s.display()
|
||||
} else {
|
||||
t := &file.Client{
|
||||
VerifyKey: crypt.GetRandomString(16),
|
||||
VerifyKey: s.GetString("vkey"),
|
||||
Id: file.GetCsvDb().GetClientId(),
|
||||
Status: true,
|
||||
Remark: s.GetString("remark"),
|
||||
Cnf: &file.Config{
|
||||
U: s.GetString("u"),
|
||||
P: s.GetString("p"),
|
||||
Compress: s.GetString("compress"),
|
||||
Compress: common.GetBoolByStr(s.GetString("compress")),
|
||||
Crypt: s.GetBoolNoErr("crypt"),
|
||||
},
|
||||
RateLimit: s.GetIntNoErr("rate_limit"),
|
||||
MaxConn: s.GetIntNoErr("max_conn"),
|
||||
Flow: &file.Flow{
|
||||
ExportFlow: 0,
|
||||
InletFlow: 0,
|
||||
@@ -52,8 +53,10 @@ func (s *ClientController) Add() {
|
||||
t.Rate = rate.NewRate(int64(t.RateLimit * 1024))
|
||||
t.Rate.Start()
|
||||
}
|
||||
file.GetCsvDb().NewClient(t)
|
||||
s.AjaxOk("添加成功")
|
||||
if err := file.GetCsvDb().NewClient(t); err != nil {
|
||||
s.AjaxErr(err.Error())
|
||||
}
|
||||
s.AjaxOk("add success")
|
||||
}
|
||||
}
|
||||
func (s *ClientController) GetClient() {
|
||||
@@ -81,19 +84,24 @@ func (s *ClientController) Edit() {
|
||||
} else {
|
||||
s.Data["c"] = c
|
||||
}
|
||||
s.SetInfo("修改")
|
||||
s.SetInfo("edit client")
|
||||
s.display()
|
||||
} else {
|
||||
if c, err := file.GetCsvDb().GetClient(id); err != nil {
|
||||
s.error()
|
||||
} else {
|
||||
if !file.GetCsvDb().VerifyVkey(s.GetString("vkey"), c.Id) {
|
||||
s.AjaxErr("Vkey duplicate, please reset")
|
||||
}
|
||||
c.VerifyKey = s.GetString("vkey")
|
||||
c.Remark = s.GetString("remark")
|
||||
c.Cnf.U = s.GetString("u")
|
||||
c.Cnf.P = s.GetString("p")
|
||||
c.Cnf.Compress = s.GetString("compress")
|
||||
c.Cnf.Compress = common.GetBoolByStr(s.GetString("compress"))
|
||||
c.Cnf.Crypt = s.GetBoolNoErr("crypt")
|
||||
c.Flow.FlowLimit = int64(s.GetIntNoErr("flow_limit"))
|
||||
c.RateLimit = s.GetIntNoErr("rate_limit")
|
||||
c.MaxConn = s.GetIntNoErr("max_conn")
|
||||
if c.Rate != nil {
|
||||
c.Rate.Stop()
|
||||
}
|
||||
@@ -103,9 +111,9 @@ func (s *ClientController) Edit() {
|
||||
} else {
|
||||
c.Rate = nil
|
||||
}
|
||||
file.GetCsvDb().UpdateClient(c)
|
||||
file.GetCsvDb().StoreClientsToCsv()
|
||||
}
|
||||
s.AjaxOk("修改成功")
|
||||
s.AjaxOk("save success")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,18 +125,18 @@ func (s *ClientController) ChangeStatus() {
|
||||
if client.Status == false {
|
||||
server.DelClientConnect(client.Id)
|
||||
}
|
||||
s.AjaxOk("修改成功")
|
||||
s.AjaxOk("modified success")
|
||||
}
|
||||
s.AjaxErr("修改失败")
|
||||
s.AjaxErr("modified fail")
|
||||
}
|
||||
|
||||
//删除客户端
|
||||
func (s *ClientController) Del() {
|
||||
id := s.GetIntNoErr("id")
|
||||
if err := file.GetCsvDb().DelClient(id); err != nil {
|
||||
s.AjaxErr("删除失败")
|
||||
s.AjaxErr("delete error")
|
||||
}
|
||||
server.DelTunnelAndHostByClientId(id)
|
||||
server.DelClientConnect(id)
|
||||
s.AjaxOk("删除成功")
|
||||
s.AjaxOk("delete success")
|
||||
}
|
||||
|
||||
+85
-61
@@ -3,6 +3,7 @@ package controllers
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/server"
|
||||
"github.com/cnlh/nps/server/tool"
|
||||
)
|
||||
|
||||
type IndexController struct {
|
||||
@@ -15,36 +16,52 @@ func (s *IndexController) Index() {
|
||||
s.display("index/index")
|
||||
}
|
||||
func (s *IndexController) Help() {
|
||||
s.SetInfo("使用说明")
|
||||
s.SetInfo("about")
|
||||
s.display("index/help")
|
||||
}
|
||||
|
||||
func (s *IndexController) Tcp() {
|
||||
s.SetInfo("tcp隧道管理")
|
||||
s.SetType("tunnelServer")
|
||||
s.SetInfo("tcp")
|
||||
s.SetType("tcp")
|
||||
s.display("index/list")
|
||||
}
|
||||
|
||||
func (s *IndexController) Udp() {
|
||||
s.SetInfo("udp隧道管理")
|
||||
s.SetType("udpServer")
|
||||
s.SetInfo("udp")
|
||||
s.SetType("udp")
|
||||
s.display("index/list")
|
||||
}
|
||||
|
||||
func (s *IndexController) Socks5() {
|
||||
s.SetInfo("socks5管理")
|
||||
s.SetType("socks5Server")
|
||||
s.SetInfo("socks5")
|
||||
s.SetType("socks5")
|
||||
s.display("index/list")
|
||||
}
|
||||
|
||||
func (s *IndexController) Http() {
|
||||
s.SetInfo("http代理管理")
|
||||
s.SetType("httpProxyServer")
|
||||
s.SetInfo("http proxy")
|
||||
s.SetType("httpProxy")
|
||||
s.display("index/list")
|
||||
}
|
||||
func (s *IndexController) File() {
|
||||
s.SetInfo("file server")
|
||||
s.SetType("file")
|
||||
s.display("index/list")
|
||||
}
|
||||
|
||||
func (s *IndexController) Secret() {
|
||||
s.SetInfo("secret")
|
||||
s.SetType("secret")
|
||||
s.display("index/list")
|
||||
}
|
||||
func (s *IndexController) P2p() {
|
||||
s.SetInfo("p2p")
|
||||
s.SetType("p2p")
|
||||
s.display("index/list")
|
||||
}
|
||||
|
||||
func (s *IndexController) Host() {
|
||||
s.SetInfo("host模式管理")
|
||||
s.SetInfo("host")
|
||||
s.SetType("hostServer")
|
||||
s.display("index/list")
|
||||
}
|
||||
@@ -53,7 +70,7 @@ func (s *IndexController) All() {
|
||||
s.Data["menu"] = "client"
|
||||
clientId := s.GetString("client_id")
|
||||
s.Data["client_id"] = clientId
|
||||
s.SetInfo("客户端" + clientId + "的所有隧道")
|
||||
s.SetInfo("client id:" + clientId)
|
||||
s.display("index/list")
|
||||
}
|
||||
|
||||
@@ -69,34 +86,35 @@ func (s *IndexController) Add() {
|
||||
if s.Ctx.Request.Method == "GET" {
|
||||
s.Data["type"] = s.GetString("type")
|
||||
s.Data["client_id"] = s.GetString("client_id")
|
||||
s.SetInfo("新增")
|
||||
s.SetInfo("add tunnel")
|
||||
s.display()
|
||||
} else {
|
||||
t := &file.Tunnel{
|
||||
TcpPort: s.GetIntNoErr("port"),
|
||||
Mode: s.GetString("type"),
|
||||
Target: s.GetString("target"),
|
||||
Config: &file.Config{
|
||||
U: s.GetString("u"),
|
||||
P: s.GetString("p"),
|
||||
Compress: s.GetString("compress"),
|
||||
Crypt: s.GetBoolNoErr("crypt"),
|
||||
},
|
||||
Id: file.GetCsvDb().GetTaskId(),
|
||||
UseClientCnf: s.GetBoolNoErr("use_client"),
|
||||
Status: true,
|
||||
Remark: s.GetString("remark"),
|
||||
Flow: &file.Flow{},
|
||||
Port: s.GetIntNoErr("port"),
|
||||
Mode: s.GetString("type"),
|
||||
Target: s.GetString("target"),
|
||||
Id: file.GetCsvDb().GetTaskId(),
|
||||
Status: true,
|
||||
Remark: s.GetString("remark"),
|
||||
Password: s.GetString("password"),
|
||||
LocalPath: s.GetString("local_path"),
|
||||
StripPre: s.GetString("strip_pre"),
|
||||
Flow: &file.Flow{},
|
||||
}
|
||||
if !tool.TestServerPort(t.Port, t.Mode) {
|
||||
s.AjaxErr("The port cannot be opened because it may has been occupied or is no longer allowed.")
|
||||
}
|
||||
var err error
|
||||
if t.Client, err = file.GetCsvDb().GetClient(s.GetIntNoErr("client_id")); err != nil {
|
||||
s.AjaxErr(err.Error())
|
||||
}
|
||||
file.GetCsvDb().NewTask(t)
|
||||
if err := file.GetCsvDb().NewTask(t); err != nil {
|
||||
s.AjaxErr(err.Error())
|
||||
}
|
||||
if err := server.AddTask(t); err != nil {
|
||||
s.AjaxErr(err.Error())
|
||||
} else {
|
||||
s.AjaxOk("添加成功")
|
||||
s.AjaxOk("add success")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,61 +138,60 @@ func (s *IndexController) Edit() {
|
||||
} else {
|
||||
s.Data["t"] = t
|
||||
}
|
||||
s.SetInfo("修改")
|
||||
s.SetInfo("edit tunnel")
|
||||
s.display()
|
||||
} else {
|
||||
if t, err := file.GetCsvDb().GetTask(id); err != nil {
|
||||
s.error()
|
||||
} else {
|
||||
t.TcpPort = s.GetIntNoErr("port")
|
||||
t.Port = s.GetIntNoErr("port")
|
||||
t.Mode = s.GetString("type")
|
||||
t.Target = s.GetString("target")
|
||||
t.Password = s.GetString("password")
|
||||
t.Id = id
|
||||
t.Client.Id = s.GetIntNoErr("client_id")
|
||||
t.Config.U = s.GetString("u")
|
||||
t.Config.P = s.GetString("p")
|
||||
t.Config.Compress = s.GetString("compress")
|
||||
t.Config.Crypt = s.GetBoolNoErr("crypt")
|
||||
t.UseClientCnf = s.GetBoolNoErr("use_client")
|
||||
t.LocalPath = s.GetString("local_path")
|
||||
t.StripPre = s.GetString("strip_pre")
|
||||
t.Remark = s.GetString("remark")
|
||||
if t.Client, err = file.GetCsvDb().GetClient(s.GetIntNoErr("client_id")); err != nil {
|
||||
s.AjaxErr("修改失败")
|
||||
s.AjaxErr("modified error")
|
||||
}
|
||||
file.GetCsvDb().UpdateTask(t)
|
||||
server.StopServer(t.Id)
|
||||
server.StartTask(t.Id)
|
||||
}
|
||||
s.AjaxOk("修改成功")
|
||||
s.AjaxOk("modified success")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *IndexController) Stop() {
|
||||
id := s.GetIntNoErr("id")
|
||||
if err := server.StopServer(id); err != nil {
|
||||
s.AjaxErr("停止失败")
|
||||
s.AjaxErr("stop error")
|
||||
}
|
||||
s.AjaxOk("停止成功")
|
||||
s.AjaxOk("stop success")
|
||||
}
|
||||
|
||||
func (s *IndexController) Del() {
|
||||
id := s.GetIntNoErr("id")
|
||||
if err := server.DelTask(id); err != nil {
|
||||
s.AjaxErr("删除失败")
|
||||
s.AjaxErr("delete error")
|
||||
}
|
||||
s.AjaxOk("删除成功")
|
||||
s.AjaxOk("delete success")
|
||||
}
|
||||
|
||||
func (s *IndexController) Start() {
|
||||
id := s.GetIntNoErr("id")
|
||||
if err := server.StartTask(id); err != nil {
|
||||
s.AjaxErr("开启失败")
|
||||
s.AjaxErr("start error")
|
||||
}
|
||||
s.AjaxOk("开启成功")
|
||||
s.AjaxOk("start success")
|
||||
}
|
||||
|
||||
func (s *IndexController) HostList() {
|
||||
if s.Ctx.Request.Method == "GET" {
|
||||
s.Data["client_id"] = s.GetString("client_id")
|
||||
s.Data["menu"] = "host"
|
||||
s.SetInfo("域名列表")
|
||||
s.SetInfo("host list")
|
||||
s.display("index/hlist")
|
||||
} else {
|
||||
start, length := s.GetAjaxParams()
|
||||
@@ -187,7 +204,7 @@ func (s *IndexController) HostList() {
|
||||
func (s *IndexController) GetHost() {
|
||||
if s.Ctx.Request.Method == "POST" {
|
||||
data := make(map[string]interface{})
|
||||
if h, err := server.GetInfoByHost(s.GetString("host")); err != nil {
|
||||
if h, err := file.GetCsvDb().GetHostById(s.GetIntNoErr("id")); err != nil {
|
||||
data["code"] = 0
|
||||
} else {
|
||||
data["data"] = h
|
||||
@@ -199,64 +216,71 @@ func (s *IndexController) GetHost() {
|
||||
}
|
||||
|
||||
func (s *IndexController) DelHost() {
|
||||
host := s.GetString("host")
|
||||
if err := file.GetCsvDb().DelHost(host); err != nil {
|
||||
s.AjaxErr("删除失败")
|
||||
id := s.GetIntNoErr("id")
|
||||
if err := file.GetCsvDb().DelHost(id); err != nil {
|
||||
s.AjaxErr("delete error")
|
||||
}
|
||||
s.AjaxOk("删除成功")
|
||||
s.AjaxOk("delete success")
|
||||
}
|
||||
|
||||
func (s *IndexController) AddHost() {
|
||||
if s.Ctx.Request.Method == "GET" {
|
||||
s.Data["client_id"] = s.GetString("client_id")
|
||||
s.Data["menu"] = "host"
|
||||
s.SetInfo("新增")
|
||||
s.SetInfo("add host")
|
||||
s.display("index/hadd")
|
||||
} else {
|
||||
h := &file.Host{
|
||||
Id: file.GetCsvDb().GetHostId(),
|
||||
Host: s.GetString("host"),
|
||||
Target: s.GetString("target"),
|
||||
HeaderChange: s.GetString("header"),
|
||||
HostChange: s.GetString("hostchange"),
|
||||
Remark: s.GetString("remark"),
|
||||
Location: s.GetString("location"),
|
||||
Flow: &file.Flow{},
|
||||
Scheme: s.GetString("scheme"),
|
||||
}
|
||||
var err error
|
||||
if h.Client, err = file.GetCsvDb().GetClient(s.GetIntNoErr("client_id")); err != nil {
|
||||
s.AjaxErr("添加失败")
|
||||
s.AjaxErr("add error")
|
||||
}
|
||||
file.GetCsvDb().NewHost(h)
|
||||
s.AjaxOk("添加成功")
|
||||
if err := file.GetCsvDb().NewHost(h); err != nil {
|
||||
s.AjaxErr("add fail" + err.Error())
|
||||
}
|
||||
s.AjaxOk("add success")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *IndexController) EditHost() {
|
||||
host := s.GetString("host")
|
||||
id := s.GetIntNoErr("id")
|
||||
if s.Ctx.Request.Method == "GET" {
|
||||
s.Data["menu"] = "host"
|
||||
if h, err := server.GetInfoByHost(host); err != nil {
|
||||
if h, err := file.GetCsvDb().GetHostById(id); err != nil {
|
||||
s.error()
|
||||
} else {
|
||||
s.Data["h"] = h
|
||||
}
|
||||
s.SetInfo("修改")
|
||||
s.SetInfo("edit")
|
||||
s.display("index/hedit")
|
||||
} else {
|
||||
if h, err := server.GetInfoByHost(host); err != nil {
|
||||
if h, err := file.GetCsvDb().GetHostById(id); err != nil {
|
||||
s.error()
|
||||
} else {
|
||||
h.Host = s.GetString("nhost")
|
||||
h.Host = s.GetString("host")
|
||||
h.Target = s.GetString("target")
|
||||
h.HeaderChange = s.GetString("header")
|
||||
h.HostChange = s.GetString("hostchange")
|
||||
h.Remark = s.GetString("remark")
|
||||
h.TargetArr = nil
|
||||
h.Location = s.GetString("location")
|
||||
h.Scheme = s.GetString("scheme")
|
||||
file.GetCsvDb().UpdateHost(h)
|
||||
var err error
|
||||
if h.Client, err = file.GetCsvDb().GetClient(s.GetIntNoErr("client_id")); err != nil {
|
||||
s.AjaxErr("修改失败")
|
||||
s.AjaxErr("modified error")
|
||||
}
|
||||
}
|
||||
s.AjaxOk("修改成功")
|
||||
s.AjaxOk("modified success")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/beego"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
)
|
||||
|
||||
type LoginController struct {
|
||||
@@ -12,12 +12,12 @@ func (self *LoginController) Index() {
|
||||
self.TplName = "login/index.html"
|
||||
}
|
||||
func (self *LoginController) Verify() {
|
||||
if self.GetString("psd") == beego.AppConfig.String("password") {
|
||||
if self.GetString("password") == beego.AppConfig.String("web_password") && self.GetString("username") == beego.AppConfig.String("web_username") {
|
||||
self.SetSession("auth", true)
|
||||
self.Data["json"] = map[string]interface{}{"status": 1, "msg": "验证成功"}
|
||||
self.Data["json"] = map[string]interface{}{"status": 1, "msg": "login success"}
|
||||
self.ServeJSON()
|
||||
} else {
|
||||
self.Data["json"] = map[string]interface{}{"status": 0, "msg": "验证失败"}
|
||||
self.Data["json"] = map[string]interface{}{"status": 0, "msg": "username or password incorrect"}
|
||||
self.ServeJSON()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package routers
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/beego"
|
||||
"github.com/cnlh/nps/vender/github.com/astaxie/beego"
|
||||
"github.com/cnlh/nps/web/controllers"
|
||||
)
|
||||
|
||||
@@ -10,4 +10,5 @@ func init() {
|
||||
beego.AutoRouter(&controllers.IndexController{})
|
||||
beego.AutoRouter(&controllers.LoginController{})
|
||||
beego.AutoRouter(&controllers.ClientController{})
|
||||
beego.AutoRouter(&controllers.AuthController{})
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user