nps/server/proxy/base.go

92 lines
2.2 KiB
Go
Raw Normal View History

2019-02-12 19:54:00 +00:00
package proxy
import (
"errors"
2019-02-03 04:40:43 +00:00
"github.com/cnlh/nps/bridge"
2019-02-09 09:07:47 +00:00
"github.com/cnlh/nps/lib/common"
"github.com/cnlh/nps/lib/conn"
"github.com/cnlh/nps/lib/file"
2019-03-02 09:43:21 +00:00
"github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
"net"
"net/http"
"sync"
)
2019-02-17 17:05:05 +00:00
type Service interface {
Start() error
Close() error
}
2019-02-23 15:29:48 +00:00
//Server BaseServer struct
type BaseServer struct {
id int
bridge *bridge.Bridge
2019-02-09 09:07:47 +00:00
task *file.Tunnel
errorContent []byte
sync.Mutex
}
2019-02-23 15:29:48 +00:00
func NewBaseServer(bridge *bridge.Bridge, task *file.Tunnel) *BaseServer {
return &BaseServer{
bridge: bridge,
task: task,
errorContent: nil,
Mutex: sync.Mutex{},
}
}
func (s *BaseServer) FlowAdd(in, out int64) {
s.Lock()
defer s.Unlock()
2019-01-26 09:27:28 +00:00
s.task.Flow.ExportFlow += out
s.task.Flow.InletFlow += in
}
2019-02-23 15:29:48 +00:00
func (s *BaseServer) FlowAddHost(host *file.Host, in, out int64) {
s.Lock()
defer s.Unlock()
host.Flow.ExportFlow += out
host.Flow.InletFlow += in
}
2019-02-23 15:29:48 +00:00
func (s *BaseServer) writeConnFail(c net.Conn) {
2019-02-09 09:07:47 +00:00
c.Write([]byte(common.ConnectionFailBytes))
c.Write(s.errorContent)
}
//权限认证
2019-02-23 15:29:48 +00:00
func (s *BaseServer) auth(r *http.Request, c *conn.Conn, u, p string) error {
2019-02-09 09:07:47 +00:00
if u != "" && p != "" && !common.CheckAuth(r, u, p) {
c.Write([]byte(common.UnauthorizedBytes))
c.Close()
return errors.New("401 Unauthorized")
}
return nil
}
2019-02-12 19:54:00 +00:00
2019-02-23 15:29:48 +00:00
func (s *BaseServer) checkFlow() error {
2019-02-12 19:54:00 +00:00
if s.task.Client.Flow.FlowLimit > 0 && (s.task.Client.Flow.FlowLimit<<20) < (s.task.Client.Flow.ExportFlow+s.task.Client.Flow.InletFlow) {
return errors.New("Traffic exceeded")
}
return nil
}
2019-02-23 15:29:48 +00:00
//与客户端建立通道
func (s *BaseServer) DealClient(c *conn.Conn, addr string, rb []byte, tp string) error {
link := conn.NewLink(tp, addr, s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, c.Conn.RemoteAddr().String())
2019-02-23 15:29:48 +00:00
2019-03-02 09:43:21 +00:00
if target, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, c.Conn.RemoteAddr().String(), s.task); err != nil {
logs.Warn("task id %d get connection from client id %d error %s", s.task.Id, s.task.Client.Id, err.Error())
2019-02-23 15:29:48 +00:00
c.Close()
return err
} else {
2019-03-02 09:43:21 +00:00
if rb != nil {
target.Write(rb)
}
conn.CopyWaitGroup(target, c, link.Crypt, link.Compress, s.task.Client.Rate, s.task.Client.Flow)
2019-02-23 15:29:48 +00:00
}
2019-03-02 09:43:21 +00:00
s.task.Client.AddConn()
2019-02-23 15:29:48 +00:00
return nil
}