tcp.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package proxy
  2. import (
  3. "net"
  4. "strconv"
  5. )
  6. var _ TCP = (*tcp)(nil)
  7. type TCPArgs struct {
  8. Local string //监听地址
  9. Parent string //被代理地址
  10. Timeout int //拨号超时(毫秒)
  11. OutCallback func() bool //回调 //是否允许代理
  12. }
  13. type TCP interface {
  14. Start() (err error)
  15. Close()
  16. callback(inConn net.Conn)
  17. outToTCP(inConn net.Conn) (err error)
  18. }
  19. type tcp struct {
  20. inConn net.Conn
  21. outConn net.Conn
  22. listen Listener
  23. cfg TCPArgs
  24. }
  25. func (s *tcp) Start() (err error) {
  26. host, port, _ := net.SplitHostPort(s.cfg.Local)
  27. p, _ := strconv.Atoi(port)
  28. s.listen = NewListener(host, p)
  29. err = s.listen.ListenTCP(s.callback)
  30. if err != nil {
  31. return
  32. }
  33. return
  34. }
  35. func (s *tcp) Close() {
  36. if s.inConn != nil {
  37. CloseConn(s.inConn)
  38. }
  39. if s.outConn != nil {
  40. CloseConn(s.outConn)
  41. }
  42. _ = s.listen.CloseListen()
  43. }
  44. func (s *tcp) callback(inConn net.Conn) {
  45. defer func() {
  46. if err := recover(); err != nil {
  47. logger.Sugar().Infof("conn handler crashed with err : %s", err)
  48. }
  49. }()
  50. if s.cfg.OutCallback != nil {
  51. if !s.cfg.OutCallback() {
  52. CloseConn(inConn)
  53. return
  54. }
  55. }
  56. err := s.outToTCP(inConn)
  57. if err != nil {
  58. CloseConn(inConn)
  59. }
  60. s.inConn = inConn
  61. }
  62. func (s *tcp) outToTCP(inConn net.Conn) error {
  63. outConn, err := ConnectHost(s.cfg.Parent, s.cfg.Timeout)
  64. if err != nil {
  65. return err
  66. }
  67. inAddr := inConn.RemoteAddr().String()
  68. inLocalAddr := inConn.LocalAddr().String()
  69. outAddr := outConn.RemoteAddr().String()
  70. outLocalAddr := outConn.LocalAddr().String()
  71. IoBind(inConn, outConn, func(isSrcErr bool, err error) {
  72. CloseConn(inConn)
  73. CloseConn(outConn)
  74. logger.Sugar().Infof("conn %s - %s - %s -%s released", inAddr, inLocalAddr, outLocalAddr, outAddr)
  75. }, func(n int, d bool) {}, 0)
  76. logger.Sugar().Infof("conn %s - %s - %s -%s connected", inAddr, inLocalAddr, outLocalAddr, outAddr)
  77. return nil
  78. }