base.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package proxy
  2. import (
  3. "errors"
  4. "github.com/cnlh/nps/bridge"
  5. "github.com/cnlh/nps/lib/common"
  6. "github.com/cnlh/nps/lib/conn"
  7. "github.com/cnlh/nps/lib/file"
  8. "github.com/cnlh/nps/vender/github.com/astaxie/beego/logs"
  9. "net"
  10. "net/http"
  11. "sync"
  12. )
  13. type Service interface {
  14. Start() error
  15. Close() error
  16. }
  17. //Server BaseServer struct
  18. type BaseServer struct {
  19. id int
  20. bridge *bridge.Bridge
  21. task *file.Tunnel
  22. errorContent []byte
  23. sync.Mutex
  24. }
  25. func NewBaseServer(bridge *bridge.Bridge, task *file.Tunnel) *BaseServer {
  26. return &BaseServer{
  27. bridge: bridge,
  28. task: task,
  29. errorContent: nil,
  30. Mutex: sync.Mutex{},
  31. }
  32. }
  33. func (s *BaseServer) FlowAdd(in, out int64) {
  34. s.Lock()
  35. defer s.Unlock()
  36. s.task.Flow.ExportFlow += out
  37. s.task.Flow.InletFlow += in
  38. }
  39. func (s *BaseServer) FlowAddHost(host *file.Host, in, out int64) {
  40. s.Lock()
  41. defer s.Unlock()
  42. host.Flow.ExportFlow += out
  43. host.Flow.InletFlow += in
  44. }
  45. func (s *BaseServer) writeConnFail(c net.Conn) {
  46. c.Write([]byte(common.ConnectionFailBytes))
  47. c.Write(s.errorContent)
  48. }
  49. //权限认证
  50. func (s *BaseServer) auth(r *http.Request, c *conn.Conn, u, p string) error {
  51. if u != "" && p != "" && !common.CheckAuth(r, u, p) {
  52. c.Write([]byte(common.UnauthorizedBytes))
  53. c.Close()
  54. return errors.New("401 Unauthorized")
  55. }
  56. return nil
  57. }
  58. func (s *BaseServer) CheckFlowAndConnNum(client *file.Client) error {
  59. if client.Flow.FlowLimit > 0 && (client.Flow.FlowLimit<<20) < (client.Flow.ExportFlow+client.Flow.InletFlow) {
  60. return errors.New("Traffic exceeded")
  61. }
  62. if !client.GetConn() {
  63. return errors.New("Connections exceed the current client limit")
  64. }
  65. return nil
  66. }
  67. //与客户端建立通道
  68. func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string, rb []byte, tp string, f func(), flow *file.Flow) error {
  69. link := conn.NewLink(tp, addr, client.Cnf.Crypt, client.Cnf.Compress, c.Conn.RemoteAddr().String())
  70. if target, err := s.bridge.SendLinkInfo(client.Id, link, c.Conn.RemoteAddr().String(), s.task); err != nil {
  71. logs.Warn("task id %d get connection from client id %d error %s", s.task.Id, client.Id, err.Error())
  72. c.Close()
  73. return err
  74. } else {
  75. if f != nil {
  76. f()
  77. }
  78. conn.CopyWaitGroup(target, c.Conn, link.Crypt, link.Compress, client.Rate, flow, true, rb)
  79. }
  80. return nil
  81. }