Compare commits

..
5 Commits
Author SHA1 Message Date
刘河 2330935b90 Vender add 2019-04-08 18:23:12 +08:00
刘河 7ea9001aa4 cache 2019-04-08 18:02:54 +08:00
刘河 694ebc5477 useranme 2019-04-08 17:07:59 +08:00
刘河 824b12a2f8 Modular 、Functional enhancement 2019-04-08 17:01:08 +08:00
刘河 0c87b4119a extension 2019-04-04 17:46:06 +08:00
58 changed files with 2397 additions and 250 deletions
+7 -3
View File
@@ -152,7 +152,6 @@ func (s *Bridge) GetHealthFromClient(id int, c *conn.Conn) {
//验证失败,返回错误验证flag,并且关闭连接
func (s *Bridge) verifyError(c *conn.Conn) {
c.Write([]byte(common.VERIFY_EER))
c.Conn.Close()
}
func (s *Bridge) verifySuccess(c *conn.Conn) {
@@ -291,11 +290,16 @@ func (s *Bridge) register(c *conn.Conn) {
}
}
func (s *Bridge) SendLinkInfo(clientId int, link *conn.Link, linkAddr string, t *file.Tunnel) (target net.Conn, err error) {
func (s *Bridge) SendLinkInfo(clientId int, link *conn.Link, t *file.Tunnel) (target net.Conn, err error) {
//if the proxy type is local
if link.LocalProxy {
target, err = net.Dial(link.ConnType, link.Host)
return
}
if v, ok := s.Client.Load(clientId); ok {
//If ip is restricted to do ip verification
if s.ipVerify {
ip := common.GetIpByAddr(linkAddr)
ip := common.GetIpByAddr(link.RemoteAddr)
if v, ok := s.Register.Load(ip); !ok {
return nil, errors.New(fmt.Sprintf("The ip %s is not in the validation list", ip))
} else {
+27 -86
View File
@@ -8,7 +8,6 @@ import (
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
"net"
"os"
"time"
)
@@ -43,106 +42,47 @@ retry:
time.Sleep(time.Second * 5)
goto retry
}
logs.Info("Successful connection with server %s", s.svrAddr)
//monitor the connection
go s.ping()
s.processor(c)
}
//处理
func (s *TRPClient) processor(c *conn.Conn) {
s.signal = c
go s.dealChan()
//start a channel connection
go s.newChan()
//start health check if the it's open
if s.cnf != nil && len(s.cnf.Healths) > 0 {
go heathCheck(s.cnf.Healths, s.signal)
}
//msg connection, eg udp
s.handleMain()
}
//handle main connection
func (s *TRPClient) handleMain() {
for {
flags, err := c.ReadFlag()
flags, err := s.signal.ReadFlag()
if err != nil {
logs.Error("Accept server data error %s, end this service", err.Error())
break
}
switch flags {
case common.VERIFY_EER:
logs.Error("VKey:%s is incorrect, the server refuses to connect, please check", s.vKey)
os.Exit(0)
case common.RES_CLOSE:
logs.Error("The authentication key is connected by another client or the server closes the client.")
os.Exit(0)
case common.RES_MSG:
logs.Error("Server-side return error")
break
case common.NEW_UDP_CONN:
//读取服务端地址、密钥 继续做处理
if lAddr, err := c.GetShortLenContent(); err != nil {
//read server udp addr and password
if lAddr, err := s.signal.GetShortLenContent(); err != nil {
logs.Warn(err)
return
} else if pwd, err := c.GetShortLenContent(); err == nil {
} else if pwd, err := s.signal.GetShortLenContent(); err == nil {
go s.newUdpConn(string(lAddr), string(pwd))
}
default:
logs.Warn("The error could not be resolved")
break
}
}
c.Close()
s.Close()
}
func (s *TRPClient) newUdpConn(rAddr string, md5Password string) {
tmpConn, err := common.GetLocalUdpAddr()
if err != nil {
logs.Error(err)
return
}
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 {
var localConn net.PacketConn
var err error
var remoteAddress string
if remoteAddress, localConn, err = handleP2PUdp(rAddr, md5Password, common.WORK_P2P_PROVIDER); err != nil {
logs.Error(err)
return
}
@@ -151,6 +91,7 @@ func (s *TRPClient) newUdpConn(rAddr string, md5Password string) {
logs.Error(err)
return
}
logs.Trace("start local p2p udp listen, local address", localConn.LocalAddr().String())
//接收新的监听,得到conn,
for {
udpTunnel, err := l.AcceptKCP()
@@ -159,23 +100,24 @@ func (s *TRPClient) newUdpConn(rAddr string, md5Password string) {
l.Close()
return
}
if udpTunnel.RemoteAddr().String() == string(b) {
if udpTunnel.RemoteAddr().String() == string(remoteAddress) {
conn.SetUdpSession(udpTunnel)
//读取link,设置msgCh 设置msgConn消息回传响应机制
logs.Trace("successful connection with client ,address %s", udpTunnel.RemoteAddr().String())
//read link info from remote
l := mux.NewMux(udpTunnel, s.bridgeConnType)
for {
connMux, err := l.Accept()
if err != nil {
continue
}
go s.srcProcess(connMux)
go s.handleChan(connMux)
}
}
}
}
//mux tunnel
func (s *TRPClient) dealChan() {
func (s *TRPClient) newChan() {
tunnel, err := NewConn(s.bridgeConnType, s.vKey, s.svrAddr, common.WORK_CHAN, s.proxyUrl)
if err != nil {
logs.Error("connect to ", s.svrAddr, "error:", err)
@@ -189,11 +131,11 @@ func (s *TRPClient) dealChan() {
s.Close()
break
}
go s.srcProcess(src)
go s.handleChan(src)
}
}
func (s *TRPClient) srcProcess(src net.Conn) {
func (s *TRPClient) handleChan(src net.Conn) {
lk, err := conn.NewConn(src).GetLinkInfo()
if err != nil {
src.Close()
@@ -218,9 +160,8 @@ loop:
for {
select {
case <-s.ticker.C:
if s.tunnel.IsClose {
if s.tunnel != nil && s.tunnel.IsClose {
s.Close()
s.ticker.Stop()
break loop
}
}
+139 -1
View File
@@ -10,6 +10,7 @@ import (
"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/ccding/go-stun/stun"
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
"github.com/cnlh/nps/vender/golang.org/x/net/proxy"
"io/ioutil"
@@ -162,7 +163,7 @@ re:
//create local server secret or p2p
for _, v := range cnf.LocalServer {
go StartLocalServer(v, cnf.CommonConfig)
go startLocalServer(v, cnf.CommonConfig)
}
c.Close()
@@ -238,6 +239,7 @@ func NewConn(tp string, vkey string, server string, connType string, proxyUrl st
return c, nil
}
//http proxy connection
func NewHttpProxyConn(url *url.URL, remoteAddr string) (net.Conn, error) {
req := &http.Request{
Method: "CONNECT",
@@ -266,7 +268,143 @@ func NewHttpProxyConn(url *url.URL, remoteAddr string) (net.Conn, error) {
return proxyConn, nil
}
//get a basic auth string
func basicAuth(username, password string) string {
auth := username + ":" + password
return base64.StdEncoding.EncodeToString([]byte(auth))
}
func handleP2PUdp(rAddr, md5Password, role string) (remoteAddress string, c net.PacketConn, err error) {
tmpConn, err := common.GetLocalUdpAddr()
if err != nil {
logs.Error(err)
return
}
localConn, err := newUdpConnByAddr(tmpConn.LocalAddr().String())
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)
//get local nat type
//localNatType, host, err := stun.NewClient().Discover()
//if err != nil || host == nil {
// err = errors.New("get nat type error")
// return
//}
localNatType := stun.NATRestricted
//write password
if _, err = localToolConn.Write([]byte(md5Password)); err != nil {
return
}
//write role
if _, err = localToolConn.Write([]byte(role)); err != nil {
return
}
if err = binary.Write(localToolConn, binary.LittleEndian, int32(localNatType)); err != nil {
return
}
//get another type address and nat type from server
var remoteAddr []byte
var remoteNatType int32
if remoteAddr, err = localToolConn.GetShortLenContent(); err != nil {
return
}
if err = binary.Read(localToolConn, binary.LittleEndian, &remoteNatType); err != nil {
return
}
localConn.Close()
//logs.Trace("remote nat type %d,local nat type %s", remoteNatType, localNatType)
if remoteAddress, err = sendP2PTestMsg(string(remoteAddr), tmpConn.LocalAddr().String()); err != nil {
return
}
c, err = newUdpConnByAddr(tmpConn.LocalAddr().String())
return
}
func handleP2P(natType1, natType2 int, addr1, addr2 string, role string) (string, error) {
switch natType1 {
case int(stun.NATFull):
return sendP2PTestMsg(addr2, addr1)
case int(stun.NATRestricted):
switch natType2 {
case int(stun.NATFull), int(stun.NATRestricted), int(stun.NATPortRestricted), int(stun.NATSymetric):
return sendP2PTestMsg(addr2, addr1)
}
case int(stun.NATPortRestricted):
switch natType2 {
case int(stun.NATFull), int(stun.NATRestricted), int(stun.NATPortRestricted):
return sendP2PTestMsg(addr2, addr1)
}
case int(stun.NATSymetric):
switch natType2 {
case int(stun.NATFull), int(stun.NATRestricted):
return sendP2PTestMsg(addr2, addr1)
}
}
return "", errors.New("not support p2p")
}
func sendP2PTestMsg(remoteAddr string, localAddr string) (string, error) {
remoteUdpAddr, err := net.ResolveUDPAddr("udp", remoteAddr)
if err != nil {
return "", err
}
localConn, err := newUdpConnByAddr(localAddr)
defer localConn.Close()
if err != nil {
return "", err
}
buf := make([]byte, 10)
for i := 20; i > 0; i-- {
logs.Trace("try send test packet to target %s", remoteAddr)
if _, err := localConn.WriteTo([]byte(common.WORK_P2P_CONNECT), remoteUdpAddr); err != nil {
return "", err
}
localConn.SetReadDeadline(time.Now().Add(time.Millisecond * 500))
n, addr, err := localConn.ReadFromUDP(buf)
localConn.SetReadDeadline(time.Time{})
switch string(buf[:n]) {
case common.WORK_P2P_SUCCESS:
for i := 20; i > 0; i-- {
if _, err = localConn.WriteTo([]byte(common.WORK_P2P_END), addr); err != nil {
return "", err
}
}
return addr.String(), nil
case common.WORK_P2P_END:
logs.Trace("Remotely Address %s Reply Packet Successfully Received", addr.String())
return addr.String(), nil
case common.WORK_P2P_CONNECT:
go func() {
for i := 20; i > 0; i-- {
logs.Trace("try send receive success packet to target %s", remoteAddr)
if _, err = localConn.WriteTo([]byte(common.WORK_P2P_SUCCESS), addr); err != nil {
return
}
time.Sleep(time.Second)
}
}()
}
}
localConn.Close()
return "", errors.New("connect to the target failed, maybe the nat type is not support p2p")
}
func newUdpConnByAddr(addr string) (*net.UDPConn, error) {
udpAddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
return nil, err
}
udpConn, err := net.ListenUDP("udp", udpAddr)
if err != nil {
return nil, err
}
return udpConn, nil
}
+34 -54
View File
@@ -11,12 +11,16 @@ import (
"github.com/cnlh/nps/vender/github.com/xtaci/kcp"
"net"
"net/http"
"sync"
)
var LocalServer []*net.TCPListener
var udpConn net.Conn
var muxSession *mux.Mux
var fileServer []*http.Server
var (
LocalServer []*net.TCPListener
udpConn net.Conn
muxSession *mux.Mux
fileServer []*http.Server
lock sync.Mutex
)
func CloseLocalServer() {
for _, v := range LocalServer {
@@ -39,10 +43,10 @@ func startLocalFileServer(config *config.CommonConfig, t *file.Tunnel, vkey stri
logs.Info("start local file system, local path %s, strip prefix %s ,remote port %s ", t.LocalPath, t.StripPre, t.Ports)
fileServer = append(fileServer, srv)
listener := mux.NewMux(remoteConn.Conn, common.CONN_TCP)
logs.Warn(srv.Serve(listener))
logs.Error(srv.Serve(listener))
}
func StartLocalServer(l *config.LocalServer, config *config.CommonConfig) error {
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())
@@ -52,15 +56,15 @@ func StartLocalServer(l *config.LocalServer, config *config.CommonConfig) error
logs.Info("successful start-up of local monitoring, port", l.Port)
conn.Accept(listener, func(c net.Conn) {
if l.Type == "secret" {
processSecret(c, config, l)
handleSecret(c, config, l)
} else {
processP2P(c, config, l)
handleP2PVisitor(c, config, l)
}
})
return nil
}
func processSecret(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
func handleSecret(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())
@@ -73,21 +77,28 @@ func processSecret(localTcpConn net.Conn, config *config.CommonConfig, l *config
conn.CopyWaitGroup(remoteConn.Conn, localTcpConn, false, false, nil, nil, false, nil)
}
func processP2P(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
func handleP2PVisitor(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
restart:
lock.Lock()
if udpConn == nil {
newUdpConn(config, l)
if udpConn == nil {
lock.Unlock()
return
}
muxSession = mux.NewMux(udpConn, "kcp")
}
lock.Unlock()
logs.Trace("start trying to connect with the server")
nowConn, err := muxSession.NewConn()
if err != nil {
logs.Error(err)
udpConn = nil
logs.Error(err, "reconnect......")
goto restart
return
}
//TODO just support compress now because there is not tls file in client packages
link := conn.NewLink(common.CONN_TCP, l.Target, false, config.Client.Cnf.Compress, localTcpConn.LocalAddr().String())
link := conn.NewLink(common.CONN_TCP, l.Target, false, config.Client.Cnf.Compress, localTcpConn.LocalAddr().String(), false)
if _, err := conn.NewConn(nowConn).SendInfo(link, ""); err != nil {
logs.Error(err)
return
@@ -111,49 +122,18 @@ func newUdpConn(config *config.CommonConfig, l *config.LocalServer) {
logs.Error(err)
return
}
//与服务端udp建立连接
tmpConn, err := common.GetLocalUdpAddr()
if err != nil {
var localConn net.PacketConn
var remoteAddress string
if remoteAddress, localConn, err = handleP2PUdp(string(rAddr), crypt.Md5(l.Password), common.WORK_P2P_VISITOR); err != nil {
logs.Error(err)
return
}
udpTunnel, err := kcp.NewConn(remoteAddress, nil, 150, 3, localConn)
if err != nil || udpTunnel == 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)
if err != nil {
logs.Error(err)
return
}
conn.SetUdpSession(localKcpConn)
//写入密钥、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
}
logs.Trace("successful create a connection with server", remoteAddress)
conn.SetUdpSession(udpTunnel)
udpConn = udpTunnel
}
+40 -5
View File
@@ -2,11 +2,15 @@ package main
import (
"flag"
"fmt"
"github.com/cnlh/nps/client"
"github.com/cnlh/nps/lib/common"
"github.com/cnlh/nps/lib/config"
"github.com/cnlh/nps/lib/daemon"
"github.com/cnlh/nps/lib/file"
"github.com/cnlh/nps/lib/version"
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
"github.com/cnlh/nps/vender/github.com/ccding/go-stun/stun"
"os"
"strings"
"time"
@@ -21,18 +25,33 @@ var (
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")
localPort = flag.Int("local_port", 2000, "p2p local port")
password = flag.String("password", "", "p2p password flag")
target = flag.String("target", "", "p2p target")
localType = flag.String("local_type", "p2p", "p2p target")
logPath = flag.String("log_path", "npc.log", "npc log path")
)
func main() {
flag.Parse()
if len(os.Args) > 2 {
if len(os.Args) >= 2 {
switch os.Args[1] {
case "status":
path := strings.Replace(os.Args[2], "-config=", "", -1)
client.GetTaskStatus(path)
if len(os.Args) > 2 {
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)
case "nat":
nat, host, err := stun.NewClient().Discover()
if err != nil || host == nil {
logs.Error("get nat type error", err)
return
}
fmt.Printf("nat type: %s \npublic address: %s\n", nat.String(), host.String())
os.Exit(0)
}
}
daemon.InitDaemon("npc", common.GetRunPath(), common.GetTmpPath())
@@ -41,7 +60,23 @@ func main() {
if *logType == "stdout" {
logs.SetLogger(logs.AdapterConsole, `{"level":`+*logLevel+`,"color":true}`)
} else {
logs.SetLogger(logs.AdapterFile, `{"level":`+*logLevel+`,"filename":"npc_log.log","daily":false,"color":true}`)
logs.SetLogger(logs.AdapterFile, `{"level":`+*logLevel+`,"filename":"`+*logPath+`","daily":false,"color":true}`)
}
//p2p or secret command
if *password != "" {
commonConfig := new(config.CommonConfig)
commonConfig.Server = *serverAddr
commonConfig.VKey = *verifyKey
commonConfig.Tp = *connType
localServer := new(config.LocalServer)
localServer.Type = *localType
localServer.Password = *password
localServer.Target = *target
localServer.Port = *localPort
commonConfig.Client = new(file.Client)
commonConfig.Client.Cnf = new(file.Config)
client.StartLocalServer(localServer, commonConfig)
return
}
env := common.GetEnvMap()
if *serverAddr == "" {
@@ -50,7 +85,7 @@ func main() {
if *verifyKey == "" {
*verifyKey, _ = env["NPC_SERVER_VKEY"]
}
logs.Info("the version of client is %s", version.VERSION)
logs.Info("the version of client is %s, the core version of client is %s", version.VERSION, version.GetVersion())
if *verifyKey != "" && *serverAddr != "" && *configPath == "" {
for {
client.NewRPClient(*serverAddr, *verifyKey, *connType, *proxyUrl, nil).Start()
+3 -2
View File
@@ -50,7 +50,7 @@ func main() {
if *logType == "stdout" {
logs.SetLogger(logs.AdapterConsole, `{"level":`+level+`,"color":true}`)
} else {
logs.SetLogger(logs.AdapterFile, `{"level":`+level+`,"filename":"nps_log.log","daily":false,"color":true}`)
logs.SetLogger(logs.AdapterFile, `{"level":`+level+`,"filename":"`+beego.AppConfig.String("log_path")+`","daily":false,"color":true}`)
}
task := &file.Tunnel{
Mode: "webServer",
@@ -62,7 +62,8 @@ func main() {
}
logs.Info("the version of server is %s ,allow client version to be %s", version.VERSION, version.GetVersion())
connection.InitConnectionService()
crypt.InitTls(filepath.Join(beego.AppPath, "conf", "server.pem"), filepath.Join(beego.AppPath, "conf", "server.key"))
crypt.InitTls(filepath.Join(common.GetRunPath(), "conf", "server.pem"), filepath.Join(common.GetRunPath(), "conf", "server.key"))
tool.InitAllowPort()
tool.StartSystemInfo()
server.StartNewServer(bridgePort, task, beego.AppConfig.String("bridge_type"))
}
+1 -1
View File
@@ -44,7 +44,7 @@ server_port=19009
[file]
mode=file
server_port=19008
local_path=./
local_path=/Users/liuhe/Downloads
strip_pre=/web/
[http]
+23 -4
View File
@@ -1,6 +1,6 @@
appname = nps
#Boot mode(dev|pro)
runmode = pro
runmode = dev
#HTTP(S) proxy port, no startup if empty
http_proxy_ip=0.0.0.0
@@ -26,13 +26,14 @@ public_vkey=123
# log level LevelEmergency->0 LevelAlert->1 LevelCritical->2 LevelError->3 LevelWarning->4 LevelNotice->5 LevelInformational->6 LevelDebug->7
log_level=7
log_path=nps.log
#Whether to restrict IP access, true or false or ignore
#ip_limit=true
#p2p
#p2p_ip=127.0.0.1
#p2p_port=6000
p2p_ip=127.0.0.1
p2p_port=6000
#web
web_host=a.o.com
@@ -48,4 +49,22 @@ auth_crypt_key =1234567812345678
#allow_ports=9001-9009,10001,11000-12000
#Web management multi-user login
#allow_user_login=true
allow_user_login=false
allow_user_register=false
allow_user_change_username=false
#extension
allow_flow_limit=false
allow_rate_limit=false
allow_tunnel_num_limit=false
allow_local_proxy=false
allow_connection_num_limit=false
allow_multi_ip=false
system_info_display=false
#cache
http_cache=false
http_cache_length=100
+102
View File
@@ -0,0 +1,102 @@
package cache
import (
"container/list"
"sync"
)
// Cache is an LRU cache. It is safe for concurrent access.
type Cache struct {
// MaxEntries is the maximum number of cache entries before
// an item is evicted. Zero means no limit.
MaxEntries int
//Execute this callback function when an element is culled
OnEvicted func(key Key, value interface{})
ll *list.List //list
cache sync.Map
}
// A Key may be any value that is comparable. See http://golang.org/ref/spec#Comparison_operators
type Key interface{}
type entry struct {
key Key
value interface{}
}
// New creates a new Cache.
// If maxEntries is 0, the cache has no length limit.
// that eviction is done by the caller.
func New(maxEntries int) *Cache {
return &Cache{
MaxEntries: maxEntries,
ll: list.New(),
//cache: make(map[interface{}]*list.Element),
}
}
// If the key value already exists, move the key to the front
func (c *Cache) Add(key Key, value interface{}) {
if ee, ok := c.cache.Load(key); ok {
c.ll.MoveToFront(ee.(*list.Element)) // move to the front
ee.(*list.Element).Value.(*entry).value = value
return
}
ele := c.ll.PushFront(&entry{key, value})
c.cache.Store(key, ele)
if c.MaxEntries != 0 && c.ll.Len() > c.MaxEntries { // Remove the oldest element if the limit is exceeded
c.RemoveOldest()
}
}
// Get looks up a key's value from the cache.
func (c *Cache) Get(key Key) (value interface{}, ok bool) {
if ele, hit := c.cache.Load(key); hit {
c.ll.MoveToFront(ele.(*list.Element))
return ele.(*list.Element).Value.(*entry).value, true
}
return
}
// Remove removes the provided key from the cache.
func (c *Cache) Remove(key Key) {
if ele, hit := c.cache.Load(key); hit {
c.removeElement(ele.(*list.Element))
}
}
// RemoveOldest removes the oldest item from the cache.
func (c *Cache) RemoveOldest() {
ele := c.ll.Back()
if ele != nil {
c.removeElement(ele)
}
}
func (c *Cache) removeElement(e *list.Element) {
c.ll.Remove(e)
kv := e.Value.(*entry)
c.cache.Delete(kv.key)
if c.OnEvicted != nil {
c.OnEvicted(kv.key, kv.value)
}
}
// Len returns the number of items in the cache.
func (c *Cache) Len() int {
return c.ll.Len()
}
// Clear purges all stored items from the cache.
func (c *Cache) Clear() {
if c.OnEvicted != nil {
c.cache.Range(func(key, value interface{}) bool {
kv := value.(*list.Element).Value.(*entry)
c.OnEvicted(kv.key, kv.value)
return true
})
}
c.ll = nil
}
+4
View File
@@ -13,6 +13,10 @@ const (
WORK_P2P = "p2pm"
WORK_P2P_VISITOR = "p2pv"
WORK_P2P_PROVIDER = "p2pp"
WORK_P2P_CONNECT = "p2pc"
WORK_P2P_SUCCESS = "p2ps"
WORK_P2P_END = "p2pe"
WORK_P2P_LAST = "p2pl"
WORK_STATUS = "stus"
RES_MSG = "msg0"
RES_CLOSE = "clse"
+18
View File
@@ -218,6 +218,7 @@ func GetPorts(p string) []int {
return ps
}
//is the string a port
func IsPort(p string) bool {
pi, err := strconv.Atoi(p)
if err != nil {
@@ -229,6 +230,7 @@ func IsPort(p string) bool {
return true
}
//if the s is just a port,return 127.0.0.1:s
func FormatAddress(s string) string {
if strings.Contains(s, ":") {
return s
@@ -236,6 +238,7 @@ func FormatAddress(s string) string {
return "127.0.0.1:" + s
}
//get address from the complete address
func GetIpByAddr(addr string) string {
arr := strings.Split(addr, ":")
return arr[0]
@@ -279,6 +282,7 @@ func GetLocalUdpAddr() (net.Conn, error) {
return tmpConn, tmpConn.Close()
}
//parse template
func ParseStr(str string) (string, error) {
tmp := template.New("npc")
var err error
@@ -305,6 +309,7 @@ func GetEnvMap() map[string]string {
return m
}
//throw the empty element of the string array
func TrimArr(arr []string) []string {
newArr := make([]string, 0)
for _, v := range arr {
@@ -315,6 +320,7 @@ func TrimArr(arr []string) []string {
return newArr
}
//
func IsArrContains(arr []string, val string) bool {
if arr == nil {
return false
@@ -327,6 +333,7 @@ func IsArrContains(arr []string, val string) bool {
return false
}
//remove value from string array
func RemoveArrVal(arr []string, val string) []string {
for k, v := range arr {
if v == val {
@@ -337,6 +344,7 @@ func RemoveArrVal(arr []string, val string) []string {
return arr
}
//convert bytes to num
func BytesToNum(b []byte) int {
var str string
for i := 0; i < len(b); i++ {
@@ -346,6 +354,7 @@ func BytesToNum(b []byte) int {
return int(x)
}
//get the length of the sync map
func GeSynctMapLen(m sync.Map) int {
var c int
m.Range(func(key, value interface{}) bool {
@@ -354,3 +363,12 @@ func GeSynctMapLen(m sync.Map) int {
})
return c
}
func GetExtFromPath(path string) string {
s := strings.Split(path, ".")
re, err := regexp.Compile(`(\w+)`)
if err != nil {
return ""
}
return string(re.Find([]byte(s[0])))
}
+3 -1
View File
@@ -17,15 +17,17 @@ type Link struct {
Host string //目标
Crypt bool //加密
Compress bool
LocalProxy bool
RemoteAddr string
}
func NewLink(connType string, host string, crypt bool, compress bool, remoteAddr string) *Link {
func NewLink(connType string, host string, crypt bool, compress bool, remoteAddr string, localProxy bool) *Link {
return &Link{
RemoteAddr: remoteAddr,
ConnType: connType,
Host: host,
Crypt: crypt,
Compress: compress,
LocalProxy: localProxy,
}
}
+16 -3
View File
@@ -48,6 +48,7 @@ type Client struct {
WebUserName string //the username of web login
WebPassword string //the password of web login
ConfigConnAllow bool //is allow connected by config file
MaxTunnelNum int
sync.RWMutex
}
@@ -97,6 +98,17 @@ func (s *Client) HasTunnel(t *Tunnel) (exist bool) {
return
}
func (s *Client) GetTunnelNum() (num int) {
GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
v := value.(*Tunnel)
if v.Client.Id == s.Id {
num++
}
return true
})
return
}
func (s *Client) HasHost(h *Host) bool {
var has bool
GetDb().JsonDb.Hosts.Range(func(key, value interface{}) bool {
@@ -164,9 +176,10 @@ type Host struct {
}
type Target struct {
nowIndex int
TargetStr string
TargetArr []string
nowIndex int
TargetStr string
TargetArr []string
LocalProxy bool
sync.RWMutex
}
+1 -1
View File
@@ -1,6 +1,6 @@
package version
const VERSION = "0.21.2"
const VERSION = "0.22.0"
// Compulsory minimum version, Minimum downward compatibility to this version
func GetVersion() string {
+10 -6
View File
@@ -17,7 +17,7 @@ type Service interface {
Close() error
}
//Server BaseServer struct
//BaseServer struct
type BaseServer struct {
id int
bridge *bridge.Bridge
@@ -35,6 +35,7 @@ func NewBaseServer(bridge *bridge.Bridge, task *file.Tunnel) *BaseServer {
}
}
//add the flow
func (s *BaseServer) FlowAdd(in, out int64) {
s.Lock()
defer s.Unlock()
@@ -42,6 +43,7 @@ func (s *BaseServer) FlowAdd(in, out int64) {
s.task.Flow.InletFlow += in
}
//change the flow
func (s *BaseServer) FlowAddHost(host *file.Host, in, out int64) {
s.Lock()
defer s.Unlock()
@@ -49,12 +51,13 @@ func (s *BaseServer) FlowAddHost(host *file.Host, in, out int64) {
host.Flow.InletFlow += in
}
//write fail bytes to the connection
func (s *BaseServer) writeConnFail(c net.Conn) {
c.Write([]byte(common.ConnectionFailBytes))
c.Write(s.errorContent)
}
//权限认证
//auth check
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))
@@ -64,6 +67,7 @@ func (s *BaseServer) auth(r *http.Request, c *conn.Conn, u, p string) error {
return nil
}
//check flow limit of the client ,and decrease the allow num of client
func (s *BaseServer) CheckFlowAndConnNum(client *file.Client) error {
if client.Flow.FlowLimit > 0 && (client.Flow.FlowLimit<<20) < (client.Flow.ExportFlow+client.Flow.InletFlow) {
return errors.New("Traffic exceeded")
@@ -74,10 +78,10 @@ func (s *BaseServer) CheckFlowAndConnNum(client *file.Client) error {
return nil
}
//与客户端建立通道
func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string, rb []byte, tp string, f func(), flow *file.Flow) 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 {
//create a new connection and start bytes copying
func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string, rb []byte, tp string, f func(), flow *file.Flow, localProxy bool) error {
link := conn.NewLink(tp, addr, client.Cnf.Crypt, client.Cnf.Compress, c.Conn.RemoteAddr().String(), localProxy)
if target, err := s.bridge.SendLinkInfo(client.Id, link, s.task); err != nil {
logs.Warn("get connection from client id %d error %s", client.Id, err.Error())
c.Close()
return err
+77 -23
View File
@@ -4,11 +4,11 @@ import (
"bufio"
"crypto/tls"
"github.com/cnlh/nps/bridge"
"github.com/cnlh/nps/lib/cache"
"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"
@@ -17,6 +17,7 @@ import (
"os"
"path/filepath"
"strconv"
"strings"
"sync"
)
@@ -27,12 +28,13 @@ type httpServer struct {
httpServer *http.Server
httpsServer *http.Server
httpsListener net.Listener
useCache bool
cache *cache.Cache
cacheLen int
}
func NewHttp(bridge *bridge.Bridge, c *file.Tunnel) *httpServer {
httpPort, _ := beego.AppConfig.Int("http_proxy_port")
httpsPort, _ := beego.AppConfig.Int("https_proxy_port")
return &httpServer{
func NewHttp(bridge *bridge.Bridge, c *file.Tunnel, httpPort, httpsPort int, useCache bool, cacheLen int) *httpServer {
httpServer := &httpServer{
BaseServer: BaseServer{
task: c,
bridge: bridge,
@@ -40,7 +42,13 @@ func NewHttp(bridge *bridge.Bridge, c *file.Tunnel) *httpServer {
},
httpPort: httpPort,
httpsPort: httpsPort,
useCache: useCache,
cacheLen: cacheLen,
}
if useCache {
httpServer.cache = cache.New(cacheLen)
}
return httpServer
}
func (s *httpServer) Start() error {
@@ -71,7 +79,7 @@ func (s *httpServer) Start() error {
logs.Error(err)
os.Exit(0)
}
logs.Error(NewHttpsServer(s.httpsListener, s.bridge).Start())
logs.Error(NewHttpsServer(s.httpsListener, s.bridge, s.useCache, s.cacheLen).Start())
}()
}
return nil
@@ -100,12 +108,12 @@ func (s *httpServer) handleTunneling(w http.ResponseWriter, r *http.Request) {
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
s.process(conn.NewConn(c), r)
s.httpHandle(conn.NewConn(c), r)
}
func (s *httpServer) process(c *conn.Conn, r *http.Request) {
func (s *httpServer) httpHandle(c *conn.Conn, r *http.Request) {
var (
isConn = true
isConn = false
host *file.Host
target net.Conn
lastHost *file.Host
@@ -114,7 +122,8 @@ func (s *httpServer) process(c *conn.Conn, r *http.Request) {
scheme = r.URL.Scheme
lk *conn.Link
targetAddr string
wg sync.WaitGroup
readReq bool
reqCh = make(chan *http.Request)
)
if host, err = file.GetDb().GetInfoByHost(r.Host, r); err != nil {
logs.Notice("the url %s %s %s can't be parsed!", r.URL.Scheme, r.Host, r.RequestURI)
@@ -126,7 +135,6 @@ func (s *httpServer) process(c *conn.Conn, r *http.Request) {
return
}
defer host.Client.AddConn()
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:
@@ -139,22 +147,46 @@ func (s *httpServer) process(c *conn.Conn, r *http.Request) {
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 {
lk = conn.NewLink(common.CONN_TCP, targetAddr, host.Client.Cnf.Crypt, host.Client.Cnf.Compress, r.RemoteAddr, host.Target.LocalProxy)
if target, err = s.bridge.SendLinkInfo(host.Client.Id, lk, 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()
defer connClient.Close()
defer c.Close()
for {
r := <-reqCh
if resp, err := http.ReadResponse(bufio.NewReader(connClient), r); err != nil {
return
} else {
//if the cache is start and the response is in the extension,store the response to the cache list
if s.useCache && strings.Contains(r.URL.Path, ".") {
b, err := httputil.DumpResponse(resp, true)
if err != nil {
return
}
c.Write(b)
host.Flow.Add(0, int64(len(b)))
s.cache.Add(filepath.Join(host.Host, r.URL.Path), b)
} else {
b, err := httputil.DumpResponse(resp, false)
if err != nil {
return
}
c.Write(b)
if bodyLen, err := common.CopyBuffer(c, resp.Body); err != nil {
return
} else {
host.Flow.Add(0, int64(len(b))+bodyLen)
}
}
}
}
}()
} else {
} else if readReq {
r, err = http.ReadRequest(bufio.NewReader(c))
if err != nil {
break
@@ -167,7 +199,6 @@ func (s *httpServer) process(c *conn.Conn, r *http.Request) {
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.GetDb().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
@@ -178,13 +209,36 @@ func (s *httpServer) process(c *conn.Conn, r *http.Request) {
goto start
}
}
//if the cache start and the request is in the cache list, return the cache
if s.useCache {
if v, ok := s.cache.Get(filepath.Join(host.Host, r.URL.Path)); ok {
n, err := c.Write(v.([]byte))
if err != nil {
break
}
logs.Trace("%s request, method %s, host %s, url %s, remote address %s, return cache", r.URL.Scheme, r.Method, r.Host, r.URL.Path, c.RemoteAddr().String())
host.Flow.Add(0, int64(n))
//if return cache and does not create a new conn with client and Connection is not set or close, close the connection.
if connClient == nil && (strings.ToLower(r.Header.Get("Connection")) == "close" || strings.ToLower(r.Header.Get("Connection")) == "") {
c.Close()
break
}
readReq = true
goto start
}
}
if connClient == nil {
isConn = true
goto start
}
readReq = true
//change the host and header and set proxy setting
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)
logs.Trace("%s request, method %s, host %s, url %s, remote address %s, target %s", r.URL.Scheme, r.Method, r.Host, r.URL.Path, c.RemoteAddr().String(), lk.Host)
//write
connClient.Write(b)
if bodyLen, err := common.CopyBuffer(connClient, r.Body); err != nil {
@@ -192,6 +246,7 @@ func (s *httpServer) process(c *conn.Conn, r *http.Request) {
} else {
host.Flow.Add(int64(len(b))+bodyLen, 0)
}
reqCh <- r
}
end:
if isConn {
@@ -201,7 +256,6 @@ end:
if target != nil {
target.Close()
}
wg.Wait()
}
func (s *httpServer) NewServer(port int, scheme string) *http.Server {
+17 -2
View File
@@ -2,6 +2,7 @@ package proxy
import (
"github.com/cnlh/nps/bridge"
"github.com/cnlh/nps/lib/cache"
"github.com/cnlh/nps/lib/common"
"github.com/cnlh/nps/lib/conn"
"github.com/cnlh/nps/lib/crypt"
@@ -21,12 +22,17 @@ type HttpsServer struct {
httpsListenerMap sync.Map
}
func NewHttpsServer(l net.Listener, bridge *bridge.Bridge) *HttpsServer {
func NewHttpsServer(l net.Listener, bridge *bridge.Bridge, useCache bool, cacheLen int) *HttpsServer {
https := &HttpsServer{listener: l}
https.bridge = bridge
https.useCache = useCache
if useCache {
https.cache = cache.New(cacheLen)
}
return https
}
//start https server
func (https *HttpsServer) Start() error {
if b, err := beego.AppConfig.Bool("https_just_proxy"); err == nil && b {
conn.Accept(https.listener, func(c net.Conn) {
@@ -81,16 +87,19 @@ func (https *HttpsServer) Start() error {
return nil
}
// close
func (https *HttpsServer) Close() error {
return https.listener.Close()
}
// new https server by cert and key file
func (https *HttpsServer) NewHttps(l net.Listener, certFile string, keyFile string) {
go func() {
logs.Error(https.NewServer(0, "https").ServeTLS(l, certFile, keyFile))
}()
}
//handle the https which is just proxy to other client
func (https *HttpsServer) handleHttps(c net.Conn) {
hostName, rb := GetServerNameFromClientHello(c)
var targetAddr string
@@ -116,7 +125,7 @@ func (https *HttpsServer) handleHttps(c net.Conn) {
logs.Warn(err.Error())
}
logs.Trace("new https connection,clientId %d,host %s,remote address %s", host.Client.Id, r.Host, c.RemoteAddr().String())
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Flow)
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Flow, host.Target.LocalProxy)
}
type HttpsListener struct {
@@ -124,10 +133,12 @@ type HttpsListener struct {
parentListener net.Listener
}
// https listener
func NewHttpsListener(l net.Listener) *HttpsListener {
return &HttpsListener{parentListener: l, acceptConn: make(chan *conn.Conn)}
}
// accept
func (httpsListener *HttpsListener) Accept() (net.Conn, error) {
httpsConn := <-httpsListener.acceptConn
if httpsConn == nil {
@@ -136,14 +147,17 @@ func (httpsListener *HttpsListener) Accept() (net.Conn, error) {
return httpsConn, nil
}
// close
func (httpsListener *HttpsListener) Close() error {
return nil
}
// addr
func (httpsListener *HttpsListener) Addr() net.Addr {
return httpsListener.parentListener.Addr()
}
// get server name from connection by read client hello bytes
func GetServerNameFromClientHello(c net.Conn) (string, []byte) {
buf := make([]byte, 4096)
data := make([]byte, 4096)
@@ -157,6 +171,7 @@ func GetServerNameFromClientHello(c net.Conn) (string, []byte) {
return clientHello.GetServerName(), buf[:n]
}
// build https request
func buildHttpsRequest(hostName string) *http.Request {
r := new(http.Request)
r.RequestURI = "/"
+33 -21
View File
@@ -1,8 +1,10 @@
package proxy
import (
"encoding/binary"
"github.com/cnlh/nps/lib/common"
"github.com/cnlh/nps/lib/conn"
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
"net"
"strconv"
"time"
@@ -15,10 +17,12 @@ type P2PServer struct {
}
type p2p struct {
provider *conn.Conn
visitor *conn.Conn
visitorAddr string
providerAddr string
provider *conn.Conn
visitor *conn.Conn
visitorAddr string
providerAddr string
providerNatType int32
visitorNatType int32
}
func NewP2PServer(p2pPort int) *P2PServer {
@@ -35,49 +39,57 @@ func (s *P2PServer) Start() error {
}
func (s *P2PServer) p2pProcess(c *conn.Conn) {
//获取密钥
var (
f string
b []byte
err error
v *p2p
ok bool
f string
b []byte
err error
v *p2p
ok bool
natType int32
)
if b, err = c.GetShortContent(32); err != nil {
return
}
//获取角色
//get role
if f, err = c.ReadFlag(); err != nil {
return
}
//get nat type
if err := binary.Read(c, binary.LittleEndian, &natType); err != nil {
return
}
if v, ok = s.p2p[string(b)]; !ok {
v = new(p2p)
s.p2p[string(b)] = v
}
logs.Trace("new p2p connection ,role %s , password %s, nat type %s ,local address %s", f, string(b), strconv.Itoa(int(natType)), c.RemoteAddr().String())
//存储
if f == common.WORK_P2P_VISITOR {
logs.Warn("try visitor")
v.visitorAddr = c.Conn.RemoteAddr().String()
v.visitorNatType = natType
v.visitor = c
for {
time.Sleep(time.Second)
for i := 20; i > 0; i-- {
if v.provider != nil {
v.provider.WriteLenContent([]byte(v.visitorAddr))
binary.Write(v.provider, binary.LittleEndian, v.visitorNatType)
break
}
time.Sleep(time.Second)
}
if _, err := v.provider.ReadFlag(); err == nil {
v.visitor.WriteLenContent([]byte(v.providerAddr))
delete(s.p2p, string(b))
} else {
}
v.provider = nil
} else {
v.providerAddr = c.Conn.RemoteAddr().String()
v.providerNatType = natType
v.provider = c
for {
time.Sleep(time.Second)
for i := 20; i > 0; i-- {
if v.visitor != nil {
v.provider.WriteLenContent([]byte(v.visitorAddr))
v.visitor.WriteLenContent([]byte(v.providerAddr))
binary.Write(v.visitor, binary.LittleEndian, v.providerNatType)
break
}
time.Sleep(time.Second)
}
v.visitor = nil
}
}
+1 -1
View File
@@ -142,7 +142,7 @@ func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
}
s.DealClient(conn.NewConn(c), s.task.Client, addr, nil, ltype, func() {
s.sendReply(c, succeeded)
}, s.task.Flow)
}, s.task.Flow, s.task.Target.LocalProxy)
return
}
+2 -2
View File
@@ -94,7 +94,7 @@ func ProcessTunnel(c *conn.Conn, s *TunnelModeServer) error {
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, nil, s.task.Flow)
return s.DealClient(c, s.task.Client, targetAddr, nil, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy)
}
//http proxy
@@ -112,5 +112,5 @@ func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error {
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, nil, s.task.Flow)
return s.DealClient(c, s.task.Client, addr, rb, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy)
}
+2 -2
View File
@@ -54,8 +54,8 @@ func (s *UdpModeServer) process(addr *net.UDPAddr, data []byte) {
return
}
defer s.task.Client.AddConn()
link := conn.NewLink(common.CONN_UDP, s.task.Target.TargetStr, s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, addr.String())
if target, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, addr.String(), s.task); err != nil {
link := conn.NewLink(common.CONN_UDP, s.task.Target.TargetStr, s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, addr.String(), s.task.Target.LocalProxy)
if target, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, s.task); err != nil {
return
} else {
s.task.Flow.Add(int64(len(data)), 0)
+6 -2
View File
@@ -70,7 +70,7 @@ func DealBridgeTask() {
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.TargetStr, nil, common.CONN_TCP, nil, t.Flow)
go proxy.NewBaseServer(Bridge, t).DealClient(s.Conn, t.Client, t.Target.TargetStr, nil, common.CONN_TCP, nil, t.Flow, t.Target.LocalProxy)
} else {
s.Conn.Close()
logs.Trace("This key %s cannot be processed,status is close", s.Password)
@@ -140,7 +140,11 @@ func NewMode(Bridge *bridge.Bridge, c *file.Tunnel) proxy.Service {
AddTask(t)
service = proxy.NewWebServer(Bridge)
case "httpHostServer":
service = proxy.NewHttp(Bridge, c)
httpPort, _ := beego.AppConfig.Int("http_proxy_port")
httpsPort, _ := beego.AppConfig.Int("https_proxy_port")
useCache, _ := beego.AppConfig.Bool("http_cache")
cacheLen, _ := beego.AppConfig.Int("http_cache_length")
service = proxy.NewHttp(Bridge, c, httpPort, httpsPort, useCache, cacheLen)
}
return service
}
+2 -2
View File
@@ -51,10 +51,10 @@ func TestServerConfig() {
if port, err := strconv.Atoi(p); err != nil {
log.Fatalln("get https port error", err)
} else {
if !common.FileExists(filepath.Join(beego.AppPath, beego.AppConfig.String("pemPath"))) {
if !common.FileExists(filepath.Join(common.GetRunPath(), beego.AppConfig.String("pemPath"))) {
log.Fatalf("ssl certFile %s is not exist", beego.AppConfig.String("pemPath"))
}
if !common.FileExists(filepath.Join(beego.AppPath, beego.AppConfig.String("ketPath"))) {
if !common.FileExists(filepath.Join(common.GetRunPath(), beego.AppConfig.String("ketPath"))) {
log.Fatalf("ssl keyFile %s is not exist", beego.AppConfig.String("pemPath"))
}
isInArr(&postTcpArr, port, "http port", "tcp")
+5 -5
View File
@@ -17,9 +17,11 @@ var (
ServerStatus []map[string]interface{}
)
func init() {
ServerStatus = make([]map[string]interface{}, 0, 1500)
go getSeverStatus()
func StartSystemInfo() {
if b, err := beego.AppConfig.Bool("system_info_display"); err == nil && b {
ServerStatus = make([]map[string]interface{}, 0, 1500)
go getSeverStatus()
}
}
func InitAllowPort() {
@@ -86,5 +88,3 @@ func getSeverStatus() {
ServerStatus = append(ServerStatus, m)
}
}
+25
View File
@@ -0,0 +1,25 @@
# Temporary files for running example
go-stun
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
+191
View File
@@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, "control" means (i) the power, direct or
indirect, to cause the direction or management of such entity, whether by
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising
permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
"Object" form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included
in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that
is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative Works
shall not include works that remain separable from, or merely link (or bind by
name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative Works
thereof, that is intentionally submitted to Licensor for inclusion in the Work
by the copyright owner or by an individual or Legal Entity authorized to submit
on behalf of the copyright owner. For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for
the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
2. Grant of Copyright License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
3. Grant of Patent License.
Subject to the terms and conditions of this License, each Contributor hereby
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
irrevocable (except as stated in this section) patent license to make, have
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
such license applies only to those patent claims licensable by such Contributor
that are necessarily infringed by their Contribution(s) alone or by combination
of their Contribution(s) with the Work to which such Contribution(s) was
submitted. If You institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
Contribution incorporated within the Work constitutes direct or contributory
patent infringement, then any patent licenses granted to You under this License
for that Work shall terminate as of the date such litigation is filed.
4. Redistribution.
You may reproduce and distribute copies of the Work or Derivative Works thereof
in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of
this License; and
You must cause any modified files to carry prominent notices stating that You
changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source form
of the Work, excluding those notices that do not pertain to any part of the
Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the
attribution notices contained within such NOTICE file, excluding those notices
that do not pertain to any part of the Derivative Works, in at least one of the
following places: within a NOTICE text file distributed as part of the
Derivative Works; within the Source form or documentation, if provided along
with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents of
the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works that
You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as
modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies
with the conditions stated in this License.
5. Submission of Contributions.
Unless You explicitly state otherwise, any Contribution intentionally submitted
for inclusion in the Work by You to the Licensor shall be under the terms and
conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of
any separate license agreement you may have executed with Licensor regarding
such Contributions.
6. Trademarks.
This License does not grant permission to use the trade names, trademarks,
service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty.
Unless required by applicable law or agreed to in writing, Licensor provides the
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE,
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
solely responsible for determining the appropriateness of using or
redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
8. Limitation of Liability.
In no event and under no legal theory, whether in tort (including negligence),
contract, or otherwise, unless required by applicable law (such as deliberate
and grossly negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special, incidental,
or consequential damages of any character arising as a result of this License or
out of the use or inability to use the Work (including but not limited to
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has
been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability.
While redistributing the Work or Derivative Works thereof, You may choose to
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
other liability obligations and/or rights consistent with this License. However,
in accepting such obligations, You may act only on Your own behalf and on Your
sole responsibility, not on behalf of any other Contributor, and only if You
agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same "printed page" as the copyright notice for easier identification within
third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+27
View File
@@ -0,0 +1,27 @@
{
"Vendor": true,
"DisableAll": true,
"Enable": [
"vet",
"safesql",
"errcheck",
"goconst",
"goimports",
"varcheck",
"gas",
"staticcheck",
"gosimple",
"lll",
"unconvert",
"misspell",
"unconvert"
],
"Aggregate": true,
"WarnUnmatchedNolint": true,
"LineLength": 240,
"Exclude": [
"stun/const.go"
],
"Deadline": "300s",
"Skip": []
}
+56
View File
@@ -0,0 +1,56 @@
// Copyright 2013, Cong Ding. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// author: Cong Ding <dinggnu@gmail.com>
package main
import (
"flag"
"fmt"
"github.com/ccding/go-stun/stun"
)
func main() {
var serverAddr = flag.String("s", stun.DefaultServerAddr, "STUN server address")
var v = flag.Bool("v", false, "verbose mode")
var vv = flag.Bool("vv", false, "double verbose mode (includes -v)")
var vvv = flag.Bool("vvv", false, "triple verbose mode (includes -v and -vv)")
flag.Parse()
// Creates a STUN client. NewClientWithConnection can also be used if
// you want to handle the UDP listener by yourself.
client := stun.NewClient()
// The default addr (stun.DefaultServerAddr) will be used unless we
// call SetServerAddr.
client.SetServerAddr(*serverAddr)
// Non verbose mode will be used by default unless we call
// SetVerbose(true) or SetVVerbose(true).
client.SetVerbose(*v || *vv || *vvv)
client.SetVVerbose(*vv || *vvv)
// Discover the NAT and return the result.
nat, host, err := client.Discover()
if err != nil {
fmt.Println(err)
return
}
fmt.Println("NAT Type:", nat)
if host != nil {
fmt.Println("External IP Family:", host.Family())
fmt.Println("External IP:", host.IP())
fmt.Println("External Port:", host.Port())
}
}
+106
View File
@@ -0,0 +1,106 @@
// Copyright 2013, Cong Ding. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Cong Ding <dinggnu@gmail.com>
package stun
import (
"encoding/binary"
"hash/crc32"
"net"
)
type attribute struct {
types uint16
length uint16
value []byte
}
func newAttribute(types uint16, value []byte) *attribute {
att := new(attribute)
att.types = types
att.value = padding(value)
att.length = uint16(len(att.value))
return att
}
func newFingerprintAttribute(packet *packet) *attribute {
crc := crc32.ChecksumIEEE(packet.bytes()) ^ fingerprint
buf := make([]byte, 4)
binary.BigEndian.PutUint32(buf, crc)
return newAttribute(attributeFingerprint, buf)
}
func newSoftwareAttribute(name string) *attribute {
return newAttribute(attributeSoftware, []byte(name))
}
func newChangeReqAttribute(changeIP bool, changePort bool) *attribute {
value := make([]byte, 4)
if changeIP {
value[3] |= 0x04
}
if changePort {
value[3] |= 0x02
}
return newAttribute(attributeChangeRequest, value)
}
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |x x x x x x x x| Family | X-Port |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | X-Address (Variable)
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
// Figure 6: Format of XOR-MAPPED-ADDRESS Attribute
func (v *attribute) xorAddr(transID []byte) *Host {
xorIP := make([]byte, 16)
for i := 0; i < len(v.value)-4; i++ {
xorIP[i] = v.value[i+4] ^ transID[i]
}
family := uint16(v.value[1])
port := binary.BigEndian.Uint16(v.value[2:4])
// Truncate if IPv4, otherwise net.IP sometimes renders it as an IPv6 address.
if family == attributeFamilyIPv4 {
xorIP = xorIP[:4]
}
x := binary.BigEndian.Uint16(transID[:2])
return &Host{family, net.IP(xorIP).String(), port ^ x}
}
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |0 0 0 0 0 0 0 0| Family | Port |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | |
// | Address (32 bits or 128 bits) |
// | |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
// Figure 5: Format of MAPPED-ADDRESS Attribute
func (v *attribute) rawAddr() *Host {
host := new(Host)
host.family = uint16(v.value[1])
host.port = binary.BigEndian.Uint16(v.value[2:4])
// Truncate if IPv4, otherwise net.IP sometimes renders it as an IPv6 address.
if host.family == attributeFamilyIPv4 {
v.value = v.value[:8]
}
host.ip = net.IP(v.value[4:]).String()
return host
}
+126
View File
@@ -0,0 +1,126 @@
// Copyright 2013, Cong Ding. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Cong Ding <dinggnu@gmail.com>
package stun
import (
"errors"
"net"
"strconv"
)
// Client is a STUN client, which can be set STUN server address and is used
// to discover NAT type.
type Client struct {
serverAddr string
softwareName string
conn net.PacketConn
logger *Logger
}
// NewClient returns a client without network connection. The network
// connection will be build when calling Discover function.
func NewClient() *Client {
c := new(Client)
c.SetSoftwareName(DefaultSoftwareName)
c.logger = NewLogger()
return c
}
// NewClientWithConnection returns a client which uses the given connection.
// Please note the connection should be acquired via net.Listen* method.
func NewClientWithConnection(conn net.PacketConn) *Client {
c := new(Client)
c.conn = conn
c.SetSoftwareName(DefaultSoftwareName)
c.logger = NewLogger()
return c
}
// SetVerbose sets the client to be in the verbose mode, which prints
// information in the discover process.
func (c *Client) SetVerbose(v bool) {
c.logger.SetDebug(v)
}
// SetVVerbose sets the client to be in the double verbose mode, which prints
// information and packet in the discover process.
func (c *Client) SetVVerbose(v bool) {
c.logger.SetInfo(v)
}
// SetServerHost allows user to set the STUN hostname and port.
func (c *Client) SetServerHost(host string, port int) {
c.serverAddr = net.JoinHostPort(host, strconv.Itoa(port))
}
// SetServerAddr allows user to set the transport layer STUN server address.
func (c *Client) SetServerAddr(address string) {
c.serverAddr = address
}
// SetSoftwareName allows user to set the name of the software, which is used
// for logging purpose (NOT used in the current implementation).
func (c *Client) SetSoftwareName(name string) {
c.softwareName = name
}
// Discover contacts the STUN server and gets the response of NAT type, host
// for UDP punching.
func (c *Client) Discover() (NATType, *Host, error) {
if c.serverAddr == "" {
c.SetServerAddr(DefaultServerAddr)
}
serverUDPAddr, err := net.ResolveUDPAddr("udp", c.serverAddr)
if err != nil {
return NATError, nil, err
}
// Use the connection passed to the client if it is not nil, otherwise
// create a connection and close it at the end.
conn := c.conn
if conn == nil {
conn, err = net.ListenUDP("udp", nil)
if err != nil {
return NATError, nil, err
}
defer conn.Close()
}
return c.discover(conn, serverUDPAddr)
}
// Keepalive sends and receives a bind request, which ensures the mapping stays open
// Only applicable when client was created with a connection.
func (c *Client) Keepalive() (*Host, error) {
if c.conn == nil {
return nil, errors.New("no connection available")
}
if c.serverAddr == "" {
c.SetServerAddr(DefaultServerAddr)
}
serverUDPAddr, err := net.ResolveUDPAddr("udp", c.serverAddr)
if err != nil {
return nil, err
}
resp, err := c.test1(c.conn, serverUDPAddr)
if err != nil {
return nil, err
}
if resp == nil || resp.packet == nil {
return nil, errors.New("failed to contact")
}
return resp.mappedAddr, nil
}
+178
View File
@@ -0,0 +1,178 @@
// Copyright 2013, Cong Ding. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Cong Ding <dinggnu@gmail.com>
package stun
// Default server address and client name.
const (
DefaultServerAddr = "stun.voiparound.com:3478"
DefaultSoftwareName = "StunClient"
)
const (
magicCookie = 0x2112A442
fingerprint = 0x5354554e
)
// NATType is the type of NAT described by int.
type NATType int
// NAT types.
const (
NATError NATType = iota
NATUnknown
NATNone
NATBlocked
NATFull
NATSymmetric
NATRestricted
NATPortRestricted
NATSymmetricUDPFirewall
// Deprecated spellings of these constants
NATSymetric = NATSymmetric
NATSymetricUDPFirewall = NATSymmetricUDPFirewall
)
var natStr map[NATType]string
func init() {
natStr = map[NATType]string{
NATError: "Test failed",
NATUnknown: "Unexpected response from the STUN server",
NATBlocked: "UDP is blocked",
NATFull: "Full cone NAT",
NATSymmetric: "Symmetric NAT",
NATRestricted: "Restricted NAT",
NATPortRestricted: "Port restricted NAT",
NATNone: "Not behind a NAT",
NATSymmetricUDPFirewall: "Symmetric UDP firewall",
}
}
func (nat NATType) String() string {
if s, ok := natStr[nat]; ok {
return s
}
return "Unknown"
}
const (
errorTryAlternate = 300
errorBadRequest = 400
errorUnauthorized = 401
errorUnassigned402 = 402
errorForbidden = 403
errorUnknownAttribute = 420
errorAllocationMismatch = 437
errorStaleNonce = 438
errorUnassigned439 = 439
errorAddressFamilyNotSupported = 440
errorWrongCredentials = 441
errorUnsupportedTransportProtocol = 442
errorPeerAddressFamilyMismatch = 443
errorConnectionAlreadyExists = 446
errorConnectionTimeoutOrFailure = 447
errorAllocationQuotaReached = 486
errorRoleConflict = 487
errorServerError = 500
errorInsufficientCapacity = 508
)
const (
attributeFamilyIPv4 = 0x01
attributeFamilyIPV6 = 0x02
)
const (
attributeMappedAddress = 0x0001
attributeResponseAddress = 0x0002
attributeChangeRequest = 0x0003
attributeSourceAddress = 0x0004
attributeChangedAddress = 0x0005
attributeUsername = 0x0006
attributePassword = 0x0007
attributeMessageIntegrity = 0x0008
attributeErrorCode = 0x0009
attributeUnknownAttributes = 0x000a
attributeReflectedFrom = 0x000b
attributeChannelNumber = 0x000c
attributeLifetime = 0x000d
attributeBandwidth = 0x0010
attributeXorPeerAddress = 0x0012
attributeData = 0x0013
attributeRealm = 0x0014
attributeNonce = 0x0015
attributeXorRelayedAddress = 0x0016
attributeRequestedAddressFamily = 0x0017
attributeEvenPort = 0x0018
attributeRequestedTransport = 0x0019
attributeDontFragment = 0x001a
attributeXorMappedAddress = 0x0020
attributeTimerVal = 0x0021
attributeReservationToken = 0x0022
attributePriority = 0x0024
attributeUseCandidate = 0x0025
attributePadding = 0x0026
attributeResponsePort = 0x0027
attributeConnectionID = 0x002a
attributeXorMappedAddressExp = 0x8020
attributeSoftware = 0x8022
attributeAlternateServer = 0x8023
attributeCacheTimeout = 0x8027
attributeFingerprint = 0x8028
attributeIceControlled = 0x8029
attributeIceControlling = 0x802a
attributeResponseOrigin = 0x802b
attributeOtherAddress = 0x802c
attributeEcnCheckStun = 0x802d
attributeCiscoFlowdata = 0xc000
)
const (
typeBindingRequest = 0x0001
typeBindingResponse = 0x0101
typeBindingErrorResponse = 0x0111
typeSharedSecretRequest = 0x0002
typeSharedSecretResponse = 0x0102
typeSharedErrorResponse = 0x0112
typeAllocate = 0x0003
typeAllocateResponse = 0x0103
typeAllocateErrorResponse = 0x0113
typeRefresh = 0x0004
typeRefreshResponse = 0x0104
typeRefreshErrorResponse = 0x0114
typeSend = 0x0006
typeSendResponse = 0x0106
typeSendErrorResponse = 0x0116
typeData = 0x0007
typeDataResponse = 0x0107
typeDataErrorResponse = 0x0117
typeCreatePermisiion = 0x0008
typeCreatePermisiionResponse = 0x0108
typeCreatePermisiionErrorResponse = 0x0118
typeChannelBinding = 0x0009
typeChannelBindingResponse = 0x0109
typeChannelBindingErrorResponse = 0x0119
typeConnect = 0x000a
typeConnectResponse = 0x010a
typeConnectErrorResponse = 0x011a
typeConnectionBind = 0x000b
typeConnectionBindResponse = 0x010b
typeConnectionBindErrorResponse = 0x011b
typeConnectionAttempt = 0x000c
typeConnectionAttemptResponse = 0x010c
typeConnectionAttemptErrorResponse = 0x011c
)
+168
View File
@@ -0,0 +1,168 @@
// Copyright 2013, Cong Ding. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Cong Ding <dinggnu@gmail.com>
package stun
import (
"errors"
"net"
)
// Follow RFC 3489 and RFC 5389.
// Figure 2: Flow for type discovery process (from RFC 3489).
// +--------+
// | Test |
// | I |
// +--------+
// |
// |
// V
// /\ /\
// N / \ Y / \ Y +--------+
// UDP <-------/Resp\--------->/ IP \------------->| Test |
// Blocked \ ? / \Same/ | II |
// \ / \? / +--------+
// \/ \/ |
// | N |
// | V
// V /\
// +--------+ Sym. N / \
// | Test | UDP <---/Resp\
// | II | Firewall \ ? /
// +--------+ \ /
// | \/
// V |Y
// /\ /\ |
// Symmetric N / \ +--------+ N / \ V
// NAT <--- / IP \<-----| Test |<--- /Resp\ Open
// \Same/ | I | \ ? / Internet
// \? / +--------+ \ /
// \/ \/
// |Y |Y
// | |
// | V
// | Full
// | Cone
// V /\
// +--------+ / \ Y
// | Test |------>/Resp\---->Restricted
// | III | \ ? /
// +--------+ \ /
// \/
// |N
// | Port
// +------>Restricted
func (c *Client) discover(conn net.PacketConn, addr *net.UDPAddr) (NATType, *Host, error) {
// Perform test1 to check if it is under NAT.
c.logger.Debugln("Do Test1")
c.logger.Debugln("Send To:", addr)
resp, err := c.test1(conn, addr)
if err != nil {
return NATError, nil, err
}
c.logger.Debugln("Received:", resp)
if resp == nil {
return NATBlocked, nil, nil
}
// identical used to check if it is open Internet or not.
identical := resp.identical
// changedAddr is used to perform second time test1 and test3.
changedAddr := resp.changedAddr
// mappedAddr is used as the return value, its IP is used for tests
mappedAddr := resp.mappedAddr
// Make sure IP and port are not changed.
if resp.serverAddr.IP() != addr.IP.String() ||
resp.serverAddr.Port() != uint16(addr.Port) {
return NATError, mappedAddr, errors.New("Server error: response IP/port")
}
// if changedAddr is not available, use otherAddr as changedAddr,
// which is updated in RFC 5780
if changedAddr == nil {
changedAddr = resp.otherAddr
}
// changedAddr shall not be nil
if changedAddr == nil {
return NATError, mappedAddr, errors.New("Server error: no changed address.")
}
// Perform test2 to see if the client can receive packet sent from
// another IP and port.
c.logger.Debugln("Do Test2")
c.logger.Debugln("Send To:", addr)
resp, err = c.test2(conn, addr)
if err != nil {
return NATError, mappedAddr, err
}
c.logger.Debugln("Received:", resp)
// Make sure IP and port are changed.
if resp != nil &&
(resp.serverAddr.IP() == addr.IP.String() ||
resp.serverAddr.Port() == uint16(addr.Port)) {
return NATError, mappedAddr, errors.New("Server error: response IP/port")
}
if identical {
if resp == nil {
return NATSymmetricUDPFirewall, mappedAddr, nil
}
return NATNone, mappedAddr, nil
}
if resp != nil {
return NATFull, mappedAddr, nil
}
// Perform test1 to another IP and port to see if the NAT use the same
// external IP.
c.logger.Debugln("Do Test1")
c.logger.Debugln("Send To:", changedAddr)
caddr, err := net.ResolveUDPAddr("udp", changedAddr.String())
if err != nil {
c.logger.Debugf("ResolveUDPAddr error: %v", err)
}
resp, err = c.test1(conn, caddr)
if err != nil {
return NATError, mappedAddr, err
}
c.logger.Debugln("Received:", resp)
if resp == nil {
// It should be NAT_BLOCKED, but will be detected in the first
// step. So this will never happen.
return NATUnknown, mappedAddr, nil
}
// Make sure IP/port is not changed.
if resp.serverAddr.IP() != caddr.IP.String() ||
resp.serverAddr.Port() != uint16(caddr.Port) {
return NATError, mappedAddr, errors.New("Server error: response IP/port")
}
if mappedAddr.IP() == resp.mappedAddr.IP() && mappedAddr.Port() == resp.mappedAddr.Port() {
// Perform test3 to see if the client can receive packet sent
// from another port.
c.logger.Debugln("Do Test3")
c.logger.Debugln("Send To:", caddr)
resp, err = c.test3(conn, caddr)
if err != nil {
return NATError, mappedAddr, err
}
c.logger.Debugln("Received:", resp)
if resp == nil {
return NATPortRestricted, mappedAddr, nil
}
// Make sure IP is not changed, and port is changed.
if resp.serverAddr.IP() != caddr.IP.String() ||
resp.serverAddr.Port() == uint16(caddr.Port) {
return NATError, mappedAddr, errors.New("Server error: response IP/port")
}
return NATRestricted, mappedAddr, nil
}
return NATSymmetric, mappedAddr, nil
}
+25
View File
@@ -0,0 +1,25 @@
// Copyright 2013, Cong Ding. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Cong Ding <dinggnu@gmail.com>
// Package stun is a STUN (RFC 3489 and RFC 5389) client implementation in
// golang.
//
// It is extremely easy to use -- just one line of code.
//
// nat, host, err := stun.NewClient().Discover()
//
// More details please go to `main.go`.
package stun
+70
View File
@@ -0,0 +1,70 @@
// Copyright 2013, Cong Ding. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Cong Ding <dinggnu@gmail.com>
package stun
import (
"net"
"strconv"
)
// Host defines the network address including address family, IP address and port.
type Host struct {
family uint16
ip string
port uint16
}
func newHostFromStr(s string) *Host {
udpAddr, err := net.ResolveUDPAddr("udp", s)
if err != nil {
return nil
}
host := new(Host)
if udpAddr.IP.To4() != nil {
host.family = attributeFamilyIPv4
} else {
host.family = attributeFamilyIPV6
}
host.ip = udpAddr.IP.String()
host.port = uint16(udpAddr.Port)
return host
}
// Family returns the family type of a host (IPv4 or IPv6).
func (h *Host) Family() uint16 {
return h.family
}
// IP returns the internet protocol address of the host.
func (h *Host) IP() string {
return h.ip
}
// Port returns the port number of the host.
func (h *Host) Port() uint16 {
return h.port
}
// TransportAddr returns the transport layer address of the host.
func (h *Host) TransportAddr() string {
return net.JoinHostPort(h.ip, strconv.Itoa(int(h.port)))
}
// String returns the string representation of the host address.
func (h *Host) String() string {
return h.TransportAddr()
}
+87
View File
@@ -0,0 +1,87 @@
// Copyright 2016, Cong Ding. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Cong Ding <dinggnu@gmail.com>
package stun
import (
"log"
"os"
)
// Logger is a simple logger specified for this STUN client.
type Logger struct {
log.Logger
debug bool
info bool
}
// NewLogger creates a default logger.
func NewLogger() *Logger {
logger := &Logger{*log.New(os.Stdout, "", log.LstdFlags), false, false}
return logger
}
// SetDebug sets the logger running in debug mode or not.
func (l *Logger) SetDebug(v bool) {
l.debug = v
}
// SetInfo sets the logger running in info mode or not.
func (l *Logger) SetInfo(v bool) {
l.info = v
}
// Debug outputs the log in the format of log.Print.
func (l *Logger) Debug(v ...interface{}) {
if l.debug {
l.Print(v...)
}
}
// Debugf outputs the log in the format of log.Printf.
func (l *Logger) Debugf(format string, v ...interface{}) {
if l.debug {
l.Printf(format, v...)
}
}
// Debugln outputs the log in the format of log.Println.
func (l *Logger) Debugln(v ...interface{}) {
if l.debug {
l.Println(v...)
}
}
// Info outputs the log in the format of log.Print.
func (l *Logger) Info(v ...interface{}) {
if l.info {
l.Print(v...)
}
}
// Infof outputs the log in the format of log.Printf.
func (l *Logger) Infof(format string, v ...interface{}) {
if l.info {
l.Printf(format, v...)
}
}
// Infoln outputs the log in the format of log.Println.
func (l *Logger) Infoln(v ...interface{}) {
if l.info {
l.Println(v...)
}
}
+106
View File
@@ -0,0 +1,106 @@
// Copyright 2016, Cong Ding. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Cong Ding <dinggnu@gmail.com>
package stun
import (
"bytes"
"encoding/hex"
"errors"
"net"
"time"
)
const (
numRetransmit = 9
defaultTimeout = 100
maxTimeout = 1600
maxPacketSize = 1024
)
func (c *Client) sendBindingReq(conn net.PacketConn, addr net.Addr, changeIP bool, changePort bool) (*response, error) {
// Construct packet.
pkt, err := newPacket()
if err != nil {
return nil, err
}
pkt.types = typeBindingRequest
attribute := newSoftwareAttribute(c.softwareName)
pkt.addAttribute(*attribute)
if changeIP || changePort {
attribute = newChangeReqAttribute(changeIP, changePort)
pkt.addAttribute(*attribute)
}
// length of fingerprint attribute must be included into crc,
// so we add it before calculating crc, then subtract it after calculating crc.
pkt.length += 8
attribute = newFingerprintAttribute(pkt)
pkt.length -= 8
pkt.addAttribute(*attribute)
// Send packet.
return c.send(pkt, conn, addr)
}
// RFC 3489: Clients SHOULD retransmit the request starting with an interval
// of 100ms, doubling every retransmit until the interval reaches 1.6s.
// Retransmissions continue with intervals of 1.6s until a response is
// received, or a total of 9 requests have been sent.
func (c *Client) send(pkt *packet, conn net.PacketConn, addr net.Addr) (*response, error) {
c.logger.Info("\n" + hex.Dump(pkt.bytes()))
timeout := defaultTimeout
packetBytes := make([]byte, maxPacketSize)
for i := 0; i < numRetransmit; i++ {
// Send packet to the server.
length, err := conn.WriteTo(pkt.bytes(), addr)
if err != nil {
return nil, err
}
if length != len(pkt.bytes()) {
return nil, errors.New("Error in sending data.")
}
err = conn.SetReadDeadline(time.Now().Add(time.Duration(timeout) * time.Millisecond))
if err != nil {
return nil, err
}
if timeout < maxTimeout {
timeout *= 2
}
for {
// Read from the port.
length, raddr, err := conn.ReadFrom(packetBytes)
if err != nil {
if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
break
}
return nil, err
}
p, err := newPacketFromBytes(packetBytes[0:length])
if err != nil {
return nil, err
}
// If transId mismatches, keep reading until get a
// matched packet or timeout.
if !bytes.Equal(pkt.transID, p.transID) {
continue
}
c.logger.Info("\n" + hex.Dump(packetBytes[0:length]))
resp := newResponse(p, conn)
resp.serverAddr = newHostFromStr(raddr.String())
return resp, err
}
}
return nil, nil
}
+129
View File
@@ -0,0 +1,129 @@
// Copyright 2013, Cong Ding. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Cong Ding <dinggnu@gmail.com>
package stun
import (
"crypto/rand"
"encoding/binary"
"errors"
)
type packet struct {
types uint16
length uint16
transID []byte // 4 bytes magic cookie + 12 bytes transaction id
attributes []attribute
}
func newPacket() (*packet, error) {
v := new(packet)
v.transID = make([]byte, 16)
binary.BigEndian.PutUint32(v.transID[:4], magicCookie)
_, err := rand.Read(v.transID[4:])
if err != nil {
return nil, err
}
v.attributes = make([]attribute, 0, 10)
v.length = 0
return v, nil
}
func newPacketFromBytes(packetBytes []byte) (*packet, error) {
if len(packetBytes) < 24 {
return nil, errors.New("Received data length too short.")
}
pkt := new(packet)
pkt.types = binary.BigEndian.Uint16(packetBytes[0:2])
pkt.length = binary.BigEndian.Uint16(packetBytes[2:4])
pkt.transID = packetBytes[4:20]
pkt.attributes = make([]attribute, 0, 10)
for pos := uint16(20); pos < uint16(len(packetBytes)); {
types := binary.BigEndian.Uint16(packetBytes[pos : pos+2])
length := binary.BigEndian.Uint16(packetBytes[pos+2 : pos+4])
if pos+4+length > uint16(len(packetBytes)) {
return nil, errors.New("Received data format mismatch.")
}
value := packetBytes[pos+4 : pos+4+length]
attribute := newAttribute(types, value)
pkt.addAttribute(*attribute)
pos += align(length) + 4
}
return pkt, nil
}
func (v *packet) addAttribute(a attribute) {
v.attributes = append(v.attributes, a)
v.length += align(a.length) + 4
}
func (v *packet) bytes() []byte {
packetBytes := make([]byte, 4)
binary.BigEndian.PutUint16(packetBytes[0:2], v.types)
binary.BigEndian.PutUint16(packetBytes[2:4], v.length)
packetBytes = append(packetBytes, v.transID...)
for _, a := range v.attributes {
buf := make([]byte, 2)
binary.BigEndian.PutUint16(buf, a.types)
packetBytes = append(packetBytes, buf...)
binary.BigEndian.PutUint16(buf, a.length)
packetBytes = append(packetBytes, buf...)
packetBytes = append(packetBytes, a.value...)
}
return packetBytes
}
func (v *packet) getSourceAddr() *Host {
return v.getRawAddr(attributeSourceAddress)
}
func (v *packet) getMappedAddr() *Host {
return v.getRawAddr(attributeMappedAddress)
}
func (v *packet) getChangedAddr() *Host {
return v.getRawAddr(attributeChangedAddress)
}
func (v *packet) getOtherAddr() *Host {
return v.getRawAddr(attributeOtherAddress)
}
func (v *packet) getRawAddr(attribute uint16) *Host {
for _, a := range v.attributes {
if a.types == attribute {
return a.rawAddr()
}
}
return nil
}
func (v *packet) getXorMappedAddr() *Host {
addr := v.getXorAddr(attributeXorMappedAddress)
if addr == nil {
addr = v.getXorAddr(attributeXorMappedAddressExp)
}
return addr
}
func (v *packet) getXorAddr(attribute uint16) *Host {
for _, a := range v.attributes {
if a.types == attribute {
return a.xorAddr(v.transID)
}
}
return nil
}
+61
View File
@@ -0,0 +1,61 @@
// Copyright 2016, Cong Ding. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Cong Ding <dinggnu@gmail.com>
package stun
import (
"testing"
)
func TestNewPacketFromBytes(t *testing.T) {
b := make([]byte, 23)
_, err := newPacketFromBytes(b)
if err == nil {
t.Errorf("newPacketFromBytes error")
}
b = make([]byte, 24)
_, err = newPacketFromBytes(b)
if err != nil {
t.Errorf("newPacketFromBytes error")
}
}
func TestNewPacket(t *testing.T) {
_, err := newPacket()
if err != nil {
t.Errorf("newPacket error")
}
}
func TestPacketAll(t *testing.T) {
p, err := newPacket()
if err != nil {
t.Errorf("newPacket error")
}
p.addAttribute(*newChangeReqAttribute(true, true))
p.addAttribute(*newSoftwareAttribute("aaa"))
p.addAttribute(*newFingerprintAttribute(p))
pkt, err := newPacketFromBytes(p.bytes())
if err != nil {
t.Errorf("newPacketFromBytes error")
}
if pkt.types != 0 {
t.Errorf("newPacketFromBytes error")
}
if pkt.length < 24 {
t.Errorf("newPacketFromBytes error")
}
}
+78
View File
@@ -0,0 +1,78 @@
// Copyright 2016, Cong Ding. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Cong Ding <dinggnu@gmail.com>
package stun
import (
"fmt"
"net"
)
type response struct {
packet *packet // the original packet from the server
serverAddr *Host // the address received packet
changedAddr *Host // parsed from packet
mappedAddr *Host // parsed from packet, external addr of client NAT
otherAddr *Host // parsed from packet, to replace changedAddr in RFC 5780
identical bool // if mappedAddr is in local addr list
}
func newResponse(pkt *packet, conn net.PacketConn) *response {
resp := &response{pkt, nil, nil, nil, nil, false}
if pkt == nil {
return resp
}
// RFC 3489 doesn't require the server return XOR mapped address.
mappedAddr := pkt.getXorMappedAddr()
if mappedAddr == nil {
mappedAddr = pkt.getMappedAddr()
}
resp.mappedAddr = mappedAddr
// compute identical
localAddrStr := conn.LocalAddr().String()
if mappedAddr != nil {
mappedAddrStr := mappedAddr.String()
resp.identical = isLocalAddress(localAddrStr, mappedAddrStr)
}
// compute changedAddr
changedAddr := pkt.getChangedAddr()
if changedAddr != nil {
changedAddrHost := newHostFromStr(changedAddr.String())
resp.changedAddr = changedAddrHost
}
// compute otherAddr
otherAddr := pkt.getOtherAddr()
if otherAddr != nil {
otherAddrHost := newHostFromStr(otherAddr.String())
resp.otherAddr = otherAddrHost
}
return resp
}
// String is only used for verbose mode output.
func (r *response) String() string {
if r == nil {
return "Nil"
}
return fmt.Sprintf("{packet nil: %v, local: %v, remote: %v, changed: %v, other: %v, identical: %v}",
r.packet == nil,
r.mappedAddr,
r.serverAddr,
r.changedAddr,
r.otherAddr,
r.identical)
}
+33
View File
@@ -0,0 +1,33 @@
// Copyright 2016, Cong Ding. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Cong Ding <dinggnu@gmail.com>
package stun
import (
"net"
)
func (c *Client) test1(conn net.PacketConn, addr net.Addr) (*response, error) {
return c.sendBindingReq(conn, addr, false, false)
}
func (c *Client) test2(conn net.PacketConn, addr net.Addr) (*response, error) {
return c.sendBindingReq(conn, addr, true, true)
}
func (c *Client) test3(conn net.PacketConn, addr net.Addr) (*response, error) {
return c.sendBindingReq(conn, addr, false, true)
}
+63
View File
@@ -0,0 +1,63 @@
// Copyright 2016, Cong Ding. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Cong Ding <dinggnu@gmail.com>
package stun
import (
"net"
)
// Padding the length of the byte slice to multiple of 4.
func padding(bytes []byte) []byte {
length := uint16(len(bytes))
return append(bytes, make([]byte, align(length)-length)...)
}
// Align the uint16 number to the smallest multiple of 4, which is larger than
// or equal to the uint16 number.
func align(n uint16) uint16 {
return (n + 3) & 0xfffc
}
// isLocalAddress check if localRemote is a local address.
func isLocalAddress(local, localRemote string) bool {
// Resolve the IP returned by the STUN server first.
localRemoteAddr, err := net.ResolveUDPAddr("udp", localRemote)
if err != nil {
return false
}
// Try comparing with the local address on the socket first, but only if
// it's actually specified.
addr, err := net.ResolveUDPAddr("udp", local)
if err == nil && addr.IP != nil && !addr.IP.IsUnspecified() {
return addr.IP.Equal(localRemoteAddr.IP)
}
// Fallback to checking IPs of all interfaces
addrs, err := net.InterfaceAddrs()
if err != nil {
return false
}
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
if ip.Equal(localRemoteAddr.IP) {
return true
}
}
return false
}
+69
View File
@@ -0,0 +1,69 @@
// Copyright 2015, Cong Ding. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Cong Ding <dinggnu@gmail.com>
package stun
import (
"testing"
)
func TestPadding(t *testing.T) {
b := []byte{1, 2}
expected := []byte{1, 2, 0, 0}
result := padding(b)
if len(result) != len(expected) {
t.Errorf("Padding error: result size wrong.\n")
}
for i := range expected {
if expected[i] != result[i] {
t.Errorf("Padding error: data wrong in bit %d.\n", i)
}
}
}
func TestAlign(t *testing.T) {
d := make(map[uint16]uint16)
d[1] = 4
d[4] = 4
d[5] = 8
d[6] = 8
d[7] = 8
d[8] = 8
d[65528] = 65528
d[65529] = 65532
d[65531] = 65532
d[65532] = 65532
for k, v := range d {
if align(k) != v {
t.Errorf("Align error: expected %d, get %d", align(k), v)
}
}
}
func TestIsLocalAddress(t *testing.T) {
if !isLocalAddress(":1234", "127.0.0.1:8888") {
t.Errorf("isLocal error")
}
if !isLocalAddress("192.168.0.1:1234", "192.168.0.1:8888") {
t.Errorf("isLocal error")
}
if !isLocalAddress("8.8.8.8:1234", "8.8.8.8:8888") {
t.Errorf("isLocal error")
}
if isLocalAddress(":1234", "8.8.8.8:8888") {
t.Errorf("isLocal error")
}
}
+9
View File
@@ -39,12 +39,21 @@ func (s *BaseController) Prepare() {
s.Ctx.Input.SetData("client_id", s.GetSession("clientId").(int))
s.Ctx.Input.SetParam("client_id", strconv.Itoa(s.GetSession("clientId").(int)))
s.Data["isAdmin"] = false
s.Data["username"] = s.GetSession("username")
s.CheckUserAuth()
} else {
s.Data["isAdmin"] = true
}
s.Data["https_just_proxy"], _ = beego.AppConfig.Bool("https_just_proxy")
s.Data["allow_user_login"], _ = beego.AppConfig.Bool("allow_user_login")
s.Data["allow_flow_limit"], _ = beego.AppConfig.Bool("allow_flow_limit")
s.Data["allow_rate_limit"], _ = beego.AppConfig.Bool("allow_rate_limit")
s.Data["allow_connection_num_limit"], _ = beego.AppConfig.Bool("allow_connection_num_limit")
s.Data["allow_multi_ip"], _ = beego.AppConfig.Bool("allow_multi_ip")
s.Data["system_info_display"], _ = beego.AppConfig.Bool("system_info_display")
s.Data["allow_tunnel_num_limit"], _ = beego.AppConfig.Bool("allow_tunnel_num_limit")
s.Data["allow_local_proxy"], _ = beego.AppConfig.Bool("allow_local_proxy")
s.Data["allow_user_change_username"], _ = beego.AppConfig.Bool("allow_user_change_username")
}
//加载模板
+6 -1
View File
@@ -54,6 +54,7 @@ func (s *ClientController) Add() {
MaxConn: s.GetIntNoErr("max_conn"),
WebUserName: s.GetString("web_username"),
WebPassword: s.GetString("web_password"),
MaxTunnelNum: s.GetIntNoErr("max_tunnel"),
Flow: &file.Flow{
ExportFlow: 0,
InletFlow: 0,
@@ -116,13 +117,17 @@ func (s *ClientController) Edit() {
c.Flow.FlowLimit = int64(s.GetIntNoErr("flow_limit"))
c.RateLimit = s.GetIntNoErr("rate_limit")
c.MaxConn = s.GetIntNoErr("max_conn")
c.MaxTunnelNum = s.GetIntNoErr("max_tunnel")
}
c.Remark = s.GetString("remark")
c.Cnf.U = s.GetString("u")
c.Cnf.P = s.GetString("p")
c.Cnf.Compress = common.GetBoolByStr(s.GetString("compress"))
c.Cnf.Crypt = s.GetBoolNoErr("crypt")
c.WebUserName = s.GetString("web_username")
b, err := beego.AppConfig.Bool("allow_user_change_username")
if s.GetSession("isAdmin").(bool) || (err == nil && b) {
c.WebUserName = s.GetString("web_username")
}
c.WebPassword = s.GetString("web_password")
c.ConfigConnAllow = s.GetBoolNoErr("config_conn_allow")
if c.Rate != nil {
+7 -2
View File
@@ -93,7 +93,7 @@ func (s *IndexController) Add() {
Port: s.GetIntNoErr("port"),
ServerIp: s.GetString("server_ip"),
Mode: s.GetString("type"),
Target: &file.Target{TargetStr: s.GetString("target")},
Target: &file.Target{TargetStr: s.GetString("target"), LocalProxy: s.GetBoolNoErr("local_proxy")},
Id: int(file.GetDb().JsonDb.GetTaskId()),
Status: true,
Remark: s.GetString("remark"),
@@ -109,6 +109,9 @@ func (s *IndexController) Add() {
if t.Client, err = file.GetDb().GetClient(s.GetIntNoErr("client_id")); err != nil {
s.AjaxErr(err.Error())
}
if t.Client.MaxTunnelNum != 0 && t.Client.GetTunnelNum() >= t.Client.MaxTunnelNum {
s.AjaxErr("The number of tunnels exceeds the limit")
}
if err := file.GetDb().NewTask(t); err != nil {
s.AjaxErr(err.Error())
}
@@ -166,6 +169,7 @@ func (s *IndexController) Edit() {
t.LocalPath = s.GetString("local_path")
t.StripPre = s.GetString("strip_pre")
t.Remark = s.GetString("remark")
t.Target.LocalProxy = s.GetBoolNoErr("local_proxy")
file.GetDb().UpdateTask(t)
server.StopServer(t.Id)
server.StartTask(t.Id)
@@ -244,7 +248,7 @@ func (s *IndexController) AddHost() {
h := &file.Host{
Id: int(file.GetDb().JsonDb.GetHostId()),
Host: s.GetString("host"),
Target: &file.Target{TargetStr: s.GetString("target")},
Target: &file.Target{TargetStr: s.GetString("target"), LocalProxy: s.GetBoolNoErr("local_proxy")},
HeaderChange: s.GetString("header"),
HostChange: s.GetString("hostchange"),
Remark: s.GetString("remark"),
@@ -304,6 +308,7 @@ func (s *IndexController) EditHost() {
h.Scheme = s.GetString("scheme")
h.KeyFilePath = s.GetString("key_file_path")
h.CertFilePath = s.GetString("cert_file_path")
h.Target.LocalProxy = s.GetBoolNoErr("local_proxy")
file.GetDb().JsonDb.StoreHostToJsonFile()
}
s.AjaxOk("modified success")
+33
View File
@@ -13,6 +13,7 @@ type LoginController struct {
}
func (self *LoginController) Index() {
self.Data["register_allow"], _ = beego.AppConfig.Bool("allow_user_register")
self.TplName = "login/index.html"
}
func (self *LoginController) Verify() {
@@ -42,6 +43,7 @@ func (self *LoginController) Verify() {
if auth {
self.SetSession("isAdmin", false)
self.SetSession("clientId", v.Id)
self.SetSession("username", v.WebUserName)
return false
}
return true
@@ -55,6 +57,37 @@ func (self *LoginController) Verify() {
}
self.ServeJSON()
}
func (self *LoginController) Register() {
if self.Ctx.Request.Method == "GET" {
self.TplName = "login/register.html"
} else {
if b, err := beego.AppConfig.Bool("allow_user_register"); err != nil || !b {
self.Data["json"] = map[string]interface{}{"status": 0, "msg": "register is not allow"}
self.ServeJSON()
return
}
if self.GetString("username") == "" || self.GetString("password") == "" || self.GetString("username") == beego.AppConfig.String("web_username") {
self.Data["json"] = map[string]interface{}{"status": 0, "msg": "please check your input"}
self.ServeJSON()
return
}
t := &file.Client{
Id: int(file.GetDb().JsonDb.GetClientId()),
Status: true,
Cnf: &file.Config{},
WebUserName: self.GetString("username"),
WebPassword: self.GetString("password"),
Flow: &file.Flow{},
}
if err := file.GetDb().NewClient(t); err != nil {
self.Data["json"] = map[string]interface{}{"status": 0, "msg": err.Error()}
} else {
self.Data["json"] = map[string]interface{}{"status": 1, "msg": "register success"}
}
self.ServeJSON()
}
}
func (self *LoginController) Out() {
self.SetSession("auth", false)
self.Redirect("/login/index", 302)
+15 -2
View File
@@ -11,7 +11,7 @@
placeholder="remark">
</div>
</div>
{{if eq true .allow_flow_limit}}
<div class="form-group" id="flow_limit">
<label class="col-sm-2 control-label" langtag="info-flow-limit">流量限制</label>
<div class="col-sm-10">
@@ -20,7 +20,8 @@
<span class="help-block m-b-none" langtag="info-flow-limit-unit">unit: M</span>
</div>
</div>
{{end}}
{{if eq true .allow_rate_limit}}
<div class="form-group" id="rate_limit">
<label class="control-label col-sm-2" langtag="info-bandwidth">带宽限制</label>
<div class="col-sm-10">
@@ -29,6 +30,8 @@
<span class="help-block m-b-none" langtag="info-bandwidth-unit">unit: KB/S</span>
</div>
</div>
{{end}}
{{if eq true .allow_connection_num_limit}}
<div class="form-group" id="max_conn">
<label class="control-label col-sm-2" langtag="info-max-conn-num">客户端最大连接数量</label>
<div class="col-sm-10">
@@ -36,6 +39,16 @@
placeholder="empty means to be unrestricted">
</div>
</div>
{{end}}
{{if eq true .allow_tunnel_num_limit}}
<div class="form-group" id="max_tunnel">
<label class="control-label col-sm-2" langtag="info-max-tunnel-num">客户端最大隧道数量</label>
<div class="col-sm-10">
<input class="form-control" type="text" name="max_tunnel"
placeholder="empty means to be unrestricted">
</div>
</div>
{{end}}
<div class="form-group" id="u">
<label class="control-label col-sm-2" langtag="info-web-auth-username">basic权限认证用户名</label>
<div class="col-sm-10">
+18
View File
@@ -13,6 +13,7 @@
</div>
</div>
{{if eq true .isAdmin}}
{{if eq true .allow_flow_limit}}
<div class="form-group" id="flow_limit">
<label class="col-sm-2 control-label" langtag="info-flow-limit">流量限制</label>
<div class="col-sm-10">
@@ -21,6 +22,8 @@
<span class="help-block m-b-none">unit: M</span>
</div>
</div>
{{end}}
{{if eq true .allow_rate_limit}}
<div class="form-group" id="rate_limit">
<label class="control-label col-sm-2" langtag="info-bandwidth">带宽限制</label>
@@ -30,6 +33,9 @@
<span class="help-block m-b-none">unit: KB/S</span>
</div>
</div>
{{end}}
{{if eq true .allow_connection_num_limit}}
<div class="form-group" id="max_conn">
<label class="control-label col-sm-2" langtag="info-max-conn-num">客户端最大连接数</label>
<div class="col-sm-10">
@@ -37,6 +43,16 @@
placeholder="empty means to be unrestricted">
</div>
</div>
{{end}}
{{if eq true .allow_tunnel_num_limit}}
<div class="form-group" id="max_tunnel">
<label class="control-label col-sm-2" langtag="info-max-tunnel-num">客户端最大隧道数量</label>
<div class="col-sm-10">
<input class="form-control" value="{{.c.MaxTunnelNum}}" type="text" name="max_tunnel"
placeholder="empty means to be unrestricted">
</div>
</div>
{{end}}
{{end}}
<div class="form-group" id="u">
<label class="control-label col-sm-2" langtag="info-web-auth-username">basic权限认证用户名</label>
@@ -65,6 +81,7 @@
</div>
{{end}}
{{if eq true .allow_user_login}}
{{if or (eq true .allow_user_change_username) (eq true .isAdmin)}}
<div class="form-group" id="web_username">
<label class="control-label col-sm-2" langtag="info-client-web-username">web登陆用户名</label>
<div class="col-sm-10">
@@ -72,6 +89,7 @@
placeholder="empty means to be unrestricted">
</div>
</div>
{{end}}
<div class="form-group" id="web_password">
<label class="control-label col-sm-2" langtag="info-client-web-password">web登陆密码</label>
<div class="col-sm-10">
+1
View File
@@ -127,6 +127,7 @@
+ '<b langtag="info-now-conn-num">当前连接数</b>:' + row.NowConn + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-flow-limit">流量限制</b>:' + row.Flow.FlowLimit + `m&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-rate-limit">带宽限制</b>:' + row.RateLimit + `kb/s&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-max-tunnel-num">隧道数限制</b>:' + row.MaxTunnelNum + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-client-web-username">web登陆用户名</b>:' + row.WebUserName + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-client-web-password">web登陆密码</b>:' + row.WebPassword + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp` + "<br/><br>"
+18 -6
View File
@@ -27,7 +27,7 @@
placeholder="empty means to be unrestricted">
</div>
</div>
{{if eq true .allow_multi_ip}}
<div class="form-group" id="server_ip">
<label class="col-sm-2 control-label" langtag="info-server-ip">服务端ip</label>
<div class="col-sm-10">
@@ -35,7 +35,7 @@
placeholder="such as 0.0.0.0">
</div>
</div>
{{end}}
<div class="form-group" id="port">
<label class="col-sm-2 control-label" langtag="info-server-port">服务端端口</label>
<div class="col-sm-10">
@@ -43,8 +43,20 @@
</div>
</div>
{{if eq true .allow_local_proxy}}
<div class="form-group" id="local_proxy">
<label class="control-label col-sm-2" langtag="info-local-proxy">是否代理为服务端本地</label>
<div class="col-sm-10">
<select class="form-control" name="local_proxy">
<option value="0">no</option>
<option value="1">yes</option>
</select>
</div>
</div>
{{end}}
<div class="form-group" id="target">
<label class="col-sm-2 control-label" langtag="info-target">内网目标(ip:端口)</label>
<label class="col-sm-2 control-label" langtag="info-target">目标(ip:端口)</label>
<div class="col-sm-10">
<textarea class="form-control" name="target" rows="4" placeholder="10.1.50.203:22
10.1.50.202:22"></textarea>
@@ -103,9 +115,9 @@
</div>
<script>
var arr = []
arr["all"] = ["type", "port", "compress", "u", "p", "target", "password", "strip_pre", "local_path"]
arr["tcp"] = ["type", "port", "target", "compress", "u", "p", "tcp隧道模式,提供一条tcp隧道,适用于ssh、远程桌面等,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,访问公网服务器的设定端口,则相当于访问内网目标地址的目标端口"]
arr["udp"] = ["type", "port", "target", "compress", "udp隧道模式,提供一条udp隧道,适用于dns、内网dns访问等,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,访问公网服务器的设定端口,则相当于访问内网目标地址的udp目标端口"]
arr["all"] = ["type", "port", "compress", "u", "p", "target", "password", "strip_pre", "local_path", "local_proxy"]
arr["tcp"] = ["type", "port", "target", "compress", "u", "p", "local_proxy", "tcp隧道模式,提供一条tcp隧道,适用于ssh、远程桌面等,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,访问公网服务器的设定端口,则相当于访问内网目标地址的目标端口"]
arr["udp"] = ["type", "port", "target", "compress", "local_proxy", "udp隧道模式,提供一条udp隧道,适用于dns、内网dns访问等,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,访问公网服务器的设定端口,则相当于访问内网目标地址的udp目标端口"]
arr["socks5"] = ["type", "port", "compress", "u", "p", "socks5代理模式,内网socks5代理,配合proxifer,可如同使用vpn一样访问内网设备或资源,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,在外网环境下本机配置socks5代理,即访问内网设备或者资源 "]
arr["httpProxy"] = ["type", "port", "compress", "u", "p", " http代理模式,内网http代理,可访问内网网站,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,在外网环境下本机配置http代理,即访问内网站点"]
arr["secret"] = ["type", "target", "compress", "password", "u", "p", " http代理模式,内网http代理,可访问内网网站,添加后会自动生成一个客户端验证key<br>在内网机器执行<span style='color: red'>./easyProxy -vkey=生成的key -server=公网服务器ip:下面设定的端口</span><br>建立成功后,在外网环境下本机配置http代理,即访问内网站点"]
+16 -3
View File
@@ -28,6 +28,7 @@
placeholder="empty means to be unrestricted">
</div>
</div>
{{if eq true .allow_multi_ip}}
<div class="form-group" id="server_ip">
<label class="col-sm-2 control-label" langtag="info-server-ip">服务端ip</label>
<div class="col-sm-10">
@@ -35,6 +36,7 @@
placeholder="such as 0.0.0.0">
</div>
</div>
{{end}}
<div class="form-group" id="port">
<label class="col-sm-2 control-label" langtag="info-server-port">服务端端口</label>
<div class="col-sm-10">
@@ -42,6 +44,17 @@
placeholder="such as 8024">
</div>
</div>
{{if eq true .allow_local_proxy}}
<div class="form-group" id="local_proxy">
<label class="control-label col-sm-2" langtag="info-local-proxy">是否代理为服务端本地</label>
<div class="col-sm-10">
<select class="form-control" name="local_proxy">
<option {{if eq false .t.Target.LocalProxy}}selected{{end}} value="0">no</option>
<option {{if eq true .t.Target.LocalProxy}}selected{{end}} value="1">yes</option>
</select>
</div>
</div>
{{end}}
<div class="form-group" id="target">
<label class="col-sm-2 control-label" langtag="info-target">内网目标(ip:端口)</label>
<div class="col-sm-10">
@@ -101,9 +114,9 @@
</div>
<script>
var arr = []
arr["all"] = ["type", "port", "compress", "u", "p", "target", "password", "local_path", "strip_pre"]
arr["tcp"] = ["type", "port", "target", "u", "p", "compress"]
arr["udp"] = ["type", "port", "target", "compress"]
arr["all"] = ["type", "port", "compress", "u", "p", "target", "password", "local_path", "strip_pre", "local_proxy"]
arr["tcp"] = ["type", "port", "target", "u", "p", "compress", "local_proxy"]
arr["udp"] = ["type", "port", "target", "compress", "local_proxy"]
arr["socks5"] = ["type", "port", "compress", "u", "p"]
arr["httpProxy"] = ["type", "port", "compress", "u", "p"]
arr["secret"] = ["type", "target", "compress", "u", "p", "password"]
+11
View File
@@ -56,6 +56,17 @@
placeholder="client id">
</div>
</div>
{{if eq true .allow_local_proxy}}
<div class="form-group" id="local_proxy">
<label class="control-label col-sm-2" langtag="info-local-proxy">是否代理为服务端本地</label>
<div class="col-sm-10">
<select class="form-control" name="local_proxy">
<option value="0">no</option>
<option value="1">yes</option>
</select>
</div>
</div>
{{end}}
<div class="form-group">
<label class="col-sm-2 control-label" langtag="info-target">内网目标(ip:端口)</label>
<div class="col-sm-10">
+11
View File
@@ -59,6 +59,17 @@
placeholder="client id">
</div>
</div>
{{if eq true .allow_local_proxy}}
<div class="form-group" id="local_proxy">
<label class="control-label col-sm-2" langtag="info-local-proxy">是否代理为服务端本地</label>
<div class="col-sm-10">
<select class="form-control" name="local_proxy">
<option {{if eq false .h.Target.LocalProxy}}selected{{end}} value="0">no</option>
<option {{if eq true .h.Target.LocalProxy}}selected{{end}} value="1">yes</option>
</select>
</div>
</div>
{{end}}
<div class="form-group">
<label class="col-sm-2 control-label" langtag="info-target">内网目标(ip:端口)</label>
<div class="col-sm-10">
+2 -1
View File
@@ -242,7 +242,7 @@
</div>
</div>
{{if eq true .system_info_display}}
<div class="row">
<div class="col-lg-6">
<div class="ibox float-e-margins">
@@ -340,6 +340,7 @@
</div>
</div>
</div>
{{end}}
<div class="row">
<div class="col-lg-6">
+14 -7
View File
@@ -63,12 +63,19 @@
detailView: true,
smartDisplay: true, // 智能显示 pagination 和 cardview 等
detailFormatter: function (index, row, element) {
return '<b langtag="info-export-flow">出口流量</b>:' + change(row.Flow.ExportFlow) + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-inlet-flow">入口流量</b>:' + change(row.Flow.InletFlow) + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp` + "<br/><br>"
tmp = '<b langtag="info-export-flow">出口流量</b>:' + change(row.Flow.ExportFlow) + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-inlet-flow">入口流量</b>:' + change(row.Flow.InletFlow) + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-crypt">加密</b>:' + row.Client.Cnf.Crypt + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-compress">压缩</b>:' + row.Client.Cnf.Compress + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-web-auth-username">basic权限认证用户名</b>:' + row.Client.Cnf.U + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
+ '<b langtag="info-web-auth-password">basic权限认证密码</b>:' + row.Client.Cnf.P + `&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp`
if (row.Mode == "p2p") {
return tmp + "<br/><br>" + '<b langtag="info-command">访问端命令</b>:' + "<code>./npc{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey + " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -target=your target" + "</code>"
}
if (row.Mode = "secret") {
return tmp + "<br/><br>" + '<b langtag="info-command">访问端命令</b>:' + "<code>./npc{{.win}} -server={{.ip}}:{{.p}} -vkey=" + row.Client.VerifyKey + " -type=" +{{.bridgeType}} +" -password=" + row.Password + " -local_type=secret" + "</code>"
}
return tmp
},
//表格的列
columns: [
@@ -112,13 +119,13 @@
field: 'Password',//域值
title: 'secret',//标题
visible: true,//false表示不显示
},
{
field: 'Status',//域值
title: 'setting',//内容
visible: true,//false表示不显示
formatter: function (value, row, index) {
if (value) {
return '<span class="badge badge-primary">open</span>'
@@ -131,7 +138,7 @@
field: 'RunStatus',//域值
title: 'run',//内容
visible: true,//false表示不显示
formatter: function (value, row, index) {
if (value) {
return '<span class="badge badge-primary">open</span>'
@@ -144,7 +151,7 @@
field: '',//域值
title: 'client',//内容
visible: true,//false表示不显示
formatter: function (value, row, index) {
if (row.Client.IsConnect) {
return '<span class="badge badge-primary">online</span>'
@@ -157,7 +164,7 @@
field: 'option',//域值
title: 'option',//内容
visible: true,//false表示不显示
formatter: function (value, row, index) {
btn_group = '<div class="btn-group">'
btn = `<button onclick="del(` + row.Id + `)" class="btn-danger"><i class="fa fa-trash"></i></button><button onclick="edit(` + row.Id + `)" class="btn-primary"><i class="fa fa-edit"></i></button></div>`
+3
View File
@@ -48,6 +48,9 @@
<input name="password" type="password" class="form-control" placeholder="password" required="">
</div>
<button onclick="login()" class="btn btn-primary block full-width m-b">login</button>
{{if eq true .register_allow}}
<a class="btn btn-sm btn-white btn-block" href="/login/register">register</a>
{{end}}
</form>
</div>
</div>
+61
View File
@@ -0,0 +1,61 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>nps register</title>
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/font-awesome/css/font-awesome.css" rel="stylesheet">
<link href="/static/css/style.css" rel="stylesheet">
</head>
<body class="gray-bg">
<div class="middle-box text-center loginscreen animated fadeInDown">
<div>
<div>
<h1 class="logo-name">NPS</h1>
</div>
<h3>register NPS</h3>
<form class="m-t" role="form" onsubmit="return false">
<div class="form-group">
<input type="text" class="form-control" placeholder="username" name="username" required="">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="password" name="password" required="">
</div>
<button onclick="register()" type="submit" class="btn btn-primary block full-width m-b">register</button>
<a class="btn btn-sm btn-white btn-block" href="/login/index">login</a>
</form>
</div>
</div>
<script src="/static/js/jquery-2.1.1.js"></script>
<script>
function register() {
$.ajax({
type: "POST",
url: "/login/register",
data: $("form").serializeArray(),
success: function (res) {
alert(res.msg)
if (res.status) {
window.location.href = "/login/index"
}
}
})
return false
}
</script>
</body>
</html>
+1 -1
View File
@@ -42,7 +42,7 @@
{{if eq true .isAdmin}}
admin
{{else}}
user
{{.username}}
{{end}}
</strong>
</span> <span class="text-muted text-xs block">system </span> </span>