conn.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package tcpprox
  2. import (
  3. "errors"
  4. "io"
  5. "log"
  6. "net"
  7. "strconv"
  8. "sync"
  9. "time"
  10. )
  11. func isValidIP(ip string) bool {
  12. parsedIP := net.ParseIP(ip)
  13. return parsedIP != nil
  14. }
  15. func isValidPort(port string) bool {
  16. portInt, err := strconv.Atoi(port)
  17. if err != nil {
  18. return false
  19. }
  20. if portInt < 1 || portInt > 65535 {
  21. return false
  22. }
  23. return true
  24. }
  25. func isReachable(target string) bool {
  26. timeout := time.Duration(2 * time.Second) // Set the timeout value as per your requirement
  27. conn, err := net.DialTimeout("tcp", target, timeout)
  28. if err != nil {
  29. return false
  30. }
  31. defer conn.Close()
  32. return true
  33. }
  34. func connCopy(conn1 net.Conn, conn2 net.Conn, wg *sync.WaitGroup, accumulator *int64) {
  35. io.Copy(conn1, conn2)
  36. conn1.Close()
  37. log.Println("[←]", "close the connect at local:["+conn1.LocalAddr().String()+"] and remote:["+conn1.RemoteAddr().String()+"]")
  38. //conn2.Close()
  39. //log.Println("[←]", "close the connect at local:["+conn2.LocalAddr().String()+"] and remote:["+conn2.RemoteAddr().String()+"]")
  40. wg.Done()
  41. }
  42. func forward(conn1 net.Conn, conn2 net.Conn, aTob *int64, bToa *int64) {
  43. log.Printf("[+] start transmit. [%s],[%s] <-> [%s],[%s] \n", conn1.LocalAddr().String(), conn1.RemoteAddr().String(), conn2.LocalAddr().String(), conn2.RemoteAddr().String())
  44. var wg sync.WaitGroup
  45. // wait tow goroutines
  46. wg.Add(2)
  47. go connCopy(conn1, conn2, &wg, aTob)
  48. go connCopy(conn2, conn1, &wg, bToa)
  49. //blocking when the wg is locked
  50. wg.Wait()
  51. }
  52. func accept(listener net.Listener) (net.Conn, error) {
  53. conn, err := listener.Accept()
  54. if err != nil {
  55. return nil, err
  56. }
  57. log.Println("[√]", "accept a new client. remote address:["+conn.RemoteAddr().String()+"], local address:["+conn.LocalAddr().String()+"]")
  58. return conn, err
  59. }
  60. func startListener(address string) (net.Listener, error) {
  61. log.Println("[+]", "try to start server on:["+address+"]")
  62. server, err := net.Listen("tcp", address)
  63. if err != nil {
  64. return nil, errors.New("listen address [" + address + "] faild")
  65. }
  66. log.Println("[√]", "start listen at address:["+address+"]")
  67. return server, nil
  68. }
  69. /*
  70. Config Functions
  71. */
  72. // Config validator
  73. func (c *ProxyRelayConfig) ValidateConfigs() error {
  74. if c.Mode == ProxyMode_Transport {
  75. //Port2Host: PortA int, PortB string
  76. if !isValidPort(c.PortA) {
  77. return errors.New("first address must be a valid port number")
  78. }
  79. if !isReachable(c.PortB) {
  80. return errors.New("second address is unreachable")
  81. }
  82. return nil
  83. } else if c.Mode == ProxyMode_Listen {
  84. //Port2Port: Both port are port number
  85. if !isValidPort(c.PortA) {
  86. return errors.New("first address is not a valid port number")
  87. }
  88. if !isValidPort(c.PortB) {
  89. return errors.New("second address is not a valid port number")
  90. }
  91. return nil
  92. } else if c.Mode == ProxyMode_Starter {
  93. //Host2Host: Both have to be hosts
  94. if !isReachable(c.PortA) {
  95. return errors.New("first address is unreachable")
  96. }
  97. if !isReachable(c.PortB) {
  98. return errors.New("second address is unreachable")
  99. }
  100. return nil
  101. } else {
  102. return errors.New("invalid mode given")
  103. }
  104. }
  105. // Start a proxy if stopped
  106. func (c *ProxyRelayConfig) Start() error {
  107. if c.Running {
  108. return errors.New("proxy already running")
  109. }
  110. // Create a stopChan to control the loop
  111. stopChan := make(chan bool)
  112. c.stopChan = stopChan
  113. //Validate configs
  114. err := c.ValidateConfigs()
  115. if err != nil {
  116. return err
  117. }
  118. //Start the proxy service
  119. go func() {
  120. c.Running = true
  121. if c.Mode == ProxyMode_Transport {
  122. err = c.Port2host(c.PortA, c.PortB, stopChan)
  123. } else if c.Mode == ProxyMode_Listen {
  124. err = c.Port2port(c.PortA, c.PortB, stopChan)
  125. } else if c.Mode == ProxyMode_Starter {
  126. err = c.Host2host(c.PortA, c.PortB, stopChan)
  127. }
  128. if err != nil {
  129. c.Running = false
  130. log.Println("Error starting proxy service " + c.Name + "(" + c.UUID + "): " + err.Error())
  131. }
  132. }()
  133. //Successfully spawned off the proxy routine
  134. return nil
  135. }
  136. // Stop a running proxy if running
  137. func (c *ProxyRelayConfig) IsRunning() bool {
  138. return c.Running || c.stopChan != nil
  139. }
  140. // Stop a running proxy if running
  141. func (c *ProxyRelayConfig) Stop() {
  142. if c.Running || c.stopChan != nil {
  143. c.stopChan <- true
  144. time.Sleep(300 * time.Millisecond)
  145. c.stopChan = nil
  146. c.Running = false
  147. }
  148. }
  149. /*
  150. Forwarder Functions
  151. */
  152. /*
  153. portA -> server
  154. portB -> server
  155. */
  156. func (c *ProxyRelayConfig) Port2port(port1 string, port2 string, stopChan chan bool) error {
  157. //Trim the Prefix of : if exists
  158. listen1, err := startListener("0.0.0.0:" + port1)
  159. if err != nil {
  160. return err
  161. }
  162. listen2, err := startListener("0.0.0.0:" + port2)
  163. if err != nil {
  164. return err
  165. }
  166. log.Println("[√]", "listen port:", port1, "and", port2, "success. waiting for client...")
  167. c.Running = true
  168. go func() {
  169. <-stopChan
  170. log.Println("[x]", "Received stop signal. Exiting Port to Port forwarder")
  171. c.Running = false
  172. listen1.Close()
  173. listen2.Close()
  174. }()
  175. for {
  176. conn1, err := accept(listen1)
  177. if err != nil {
  178. if !c.Running {
  179. return nil
  180. }
  181. continue
  182. }
  183. conn2, err := accept(listen2)
  184. if err != nil {
  185. if !c.Running {
  186. return nil
  187. }
  188. continue
  189. }
  190. if conn1 == nil || conn2 == nil {
  191. log.Println("[x]", "accept client faild. retry in ", c.Timeout, " seconds. ")
  192. time.Sleep(time.Duration(c.Timeout) * time.Second)
  193. continue
  194. }
  195. go forward(conn1, conn2, &c.aTobAccumulatedByteTransfer, &c.bToaAccumulatedByteTransfer)
  196. }
  197. }
  198. /*
  199. portA -> server
  200. server -> portB
  201. */
  202. func (c *ProxyRelayConfig) Port2host(allowPort string, targetAddress string, stopChan chan bool) error {
  203. server, err := startListener("0.0.0.0:" + allowPort)
  204. if err != nil {
  205. return err
  206. }
  207. //Start stop handler
  208. go func() {
  209. <-stopChan
  210. log.Println("[x]", "Received stop signal. Exiting Port to Host forwarder")
  211. c.Running = false
  212. server.Close()
  213. }()
  214. //Start blocking loop for accepting connections
  215. for {
  216. conn, err := accept(server)
  217. if conn == nil || err != nil {
  218. if !c.Running {
  219. //Terminate by stop chan. Exit listener loop
  220. return nil
  221. }
  222. //Connection error. Retry
  223. continue
  224. }
  225. go func(targetAddress string) {
  226. log.Println("[+]", "start connect host:["+targetAddress+"]")
  227. target, err := net.Dial("tcp", targetAddress)
  228. if err != nil {
  229. // temporarily unavailable, don't use fatal.
  230. log.Println("[x]", "connect target address ["+targetAddress+"] faild. retry in ", c.Timeout, "seconds. ")
  231. conn.Close()
  232. log.Println("[←]", "close the connect at local:["+conn.LocalAddr().String()+"] and remote:["+conn.RemoteAddr().String()+"]")
  233. time.Sleep(time.Duration(c.Timeout) * time.Second)
  234. return
  235. }
  236. log.Println("[→]", "connect target address ["+targetAddress+"] success.")
  237. forward(target, conn, &c.aTobAccumulatedByteTransfer, &c.bToaAccumulatedByteTransfer)
  238. }(targetAddress)
  239. }
  240. }
  241. /*
  242. server -> portA
  243. server -> portB
  244. */
  245. func (c *ProxyRelayConfig) Host2host(address1, address2 string, stopChan chan bool) error {
  246. c.Running = true
  247. go func() {
  248. <-stopChan
  249. log.Println("[x]", "Received stop signal. Exiting Host to Host forwarder")
  250. c.Running = false
  251. }()
  252. for c.Running {
  253. log.Println("[+]", "try to connect host:["+address1+"] and ["+address2+"]")
  254. var host1, host2 net.Conn
  255. var err error
  256. for {
  257. d := net.Dialer{Timeout: time.Duration(c.Timeout)}
  258. host1, err = d.Dial("tcp", address1)
  259. if err == nil {
  260. log.Println("[→]", "connect ["+address1+"] success.")
  261. break
  262. } else {
  263. log.Println("[x]", "connect target address ["+address1+"] faild. retry in ", c.Timeout, " seconds. ")
  264. time.Sleep(time.Duration(c.Timeout) * time.Second)
  265. }
  266. if !c.Running {
  267. return nil
  268. }
  269. }
  270. for {
  271. d := net.Dialer{Timeout: time.Duration(c.Timeout)}
  272. host2, err = d.Dial("tcp", address2)
  273. if err == nil {
  274. log.Println("[→]", "connect ["+address2+"] success.")
  275. break
  276. } else {
  277. log.Println("[x]", "connect target address ["+address2+"] faild. retry in ", c.Timeout, " seconds. ")
  278. time.Sleep(time.Duration(c.Timeout) * time.Second)
  279. }
  280. if !c.Running {
  281. return nil
  282. }
  283. }
  284. go forward(host1, host2, &c.aTobAccumulatedByteTransfer, &c.bToaAccumulatedByteTransfer)
  285. }
  286. return nil
  287. }