tcp.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package proxy
  2. import (
  3. "log"
  4. "net"
  5. "runtime/debug"
  6. "strconv"
  7. )
  8. var _ TCP = (*tcp)(nil)
  9. type TCPArgs struct {
  10. Local string //监听地址
  11. Parent string //被代理地址
  12. Timeout int //拨号超时(毫秒)
  13. PoolSize int //代理池数
  14. CheckParentInterval int //检查被代理连接间隔(秒)
  15. OutCallback func() bool //回调 //是否允许代理
  16. }
  17. type TCP interface {
  18. Start() (err error)
  19. Close()
  20. clean()
  21. callback(inConn net.Conn)
  22. outToTCP(inConn *net.Conn) (err error)
  23. initOutConnPool()
  24. }
  25. type tcp struct {
  26. inConn *net.Conn
  27. outPool OutPool
  28. cfg TCPArgs
  29. }
  30. func (s *tcp) Start() (err error) {
  31. s.initOutConnPool()
  32. host, port, _ := net.SplitHostPort(s.cfg.Local)
  33. p, _ := strconv.Atoi(port)
  34. sc := NewServerChannel(host, p)
  35. err = sc.ListenTCP(s.callback)
  36. if err != nil {
  37. return
  38. }
  39. return
  40. }
  41. func (s *tcp) Close() {
  42. if s.inConn != nil {
  43. CloseConn(s.inConn)
  44. s.clean()
  45. }
  46. }
  47. func (s *tcp) clean() {
  48. if s.outPool.Pool != nil {
  49. s.outPool.Pool.ReleaseAll()
  50. }
  51. }
  52. func (s *tcp) callback(inConn net.Conn) {
  53. defer func() {
  54. if err := recover(); err != nil {
  55. log.Printf("conn handler crashed with err : %s \nstack: %s", err, string(debug.Stack()))
  56. }
  57. }()
  58. if s.cfg.OutCallback != nil {
  59. if !s.cfg.OutCallback() {
  60. CloseConn(&inConn)
  61. return
  62. }
  63. }
  64. err := s.outToTCP(&inConn)
  65. if err != nil {
  66. CloseConn(&inConn)
  67. }
  68. s.inConn = &inConn
  69. }
  70. func (s *tcp) outToTCP(inConn *net.Conn) (err error) {
  71. var outConn net.Conn
  72. var _outConn interface{}
  73. _outConn, err = s.outPool.Pool.Get()
  74. if err == nil {
  75. outConn = _outConn.(net.Conn)
  76. }
  77. if err != nil {
  78. CloseConn(inConn)
  79. return
  80. }
  81. inAddr := (*inConn).RemoteAddr().String()
  82. inLocalAddr := (*inConn).LocalAddr().String()
  83. outAddr := outConn.RemoteAddr().String()
  84. outLocalAddr := outConn.LocalAddr().String()
  85. IoBind(*inConn, outConn, func(isSrcErr bool, err error) {
  86. log.Printf("conn %s - %s - %s -%s released", inAddr, inLocalAddr, outLocalAddr, outAddr)
  87. CloseConn(inConn)
  88. CloseConn(&outConn)
  89. }, func(n int, d bool) {}, 0)
  90. log.Printf("conn %s - %s - %s -%s connected", inAddr, inLocalAddr, outLocalAddr, outAddr)
  91. return
  92. }
  93. func (s *tcp) initOutConnPool() {
  94. s.outPool = NewOutPool(s.cfg.CheckParentInterval, s.cfg.Parent, s.cfg.Timeout, s.cfg.PoolSize, s.cfg.PoolSize*2)
  95. }