base.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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) checkFlow() error {
  59. if s.task.Client.Flow.FlowLimit > 0 && (s.task.Client.Flow.FlowLimit<<20) < (s.task.Client.Flow.ExportFlow+s.task.Client.Flow.InletFlow) {
  60. return errors.New("Traffic exceeded")
  61. }
  62. return nil
  63. }
  64. //与客户端建立通道
  65. func (s *BaseServer) DealClient(c *conn.Conn, addr string, rb []byte, tp string) error {
  66. link := conn.NewLink(tp, addr, s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, c.Conn.RemoteAddr().String())
  67. if target, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, c.Conn.RemoteAddr().String(), s.task); err != nil {
  68. logs.Warn("task id %d get connection from client id %d error %s", s.task.Id, s.task.Client.Id, err.Error())
  69. c.Close()
  70. return err
  71. } else {
  72. if rb != nil {
  73. //HTTP proxy crypt or compress
  74. conn.GetConn(target, link.Crypt, link.Compress, s.task.Client.Rate, true).Write(rb)
  75. }
  76. conn.CopyWaitGroup(target, c.Conn, link.Crypt, link.Compress, s.task.Client.Rate, s.task.Flow, true)
  77. }
  78. s.task.Client.AddConn()
  79. return nil
  80. }