conn.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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) Stop() {
  138. if c.Running || c.stopChan != nil {
  139. c.stopChan <- true
  140. time.Sleep(300 * time.Millisecond)
  141. c.stopChan = nil
  142. c.Running = false
  143. }
  144. }
  145. /*
  146. Forwarder Functions
  147. */
  148. /*
  149. portA -> server
  150. portB -> server
  151. */
  152. func (c *ProxyRelayConfig) Port2port(port1 string, port2 string, stopChan chan bool) error {
  153. //Trim the Prefix of : if exists
  154. listen1, err := startListener("0.0.0.0:" + port1)
  155. if err != nil {
  156. return err
  157. }
  158. listen2, err := startListener("0.0.0.0:" + port2)
  159. if err != nil {
  160. return err
  161. }
  162. log.Println("[√]", "listen port:", port1, "and", port2, "success. waiting for client...")
  163. c.Running = true
  164. go func() {
  165. <-stopChan
  166. log.Println("[x]", "Received stop signal. Exiting Port to Port forwarder")
  167. c.Running = false
  168. listen1.Close()
  169. listen2.Close()
  170. }()
  171. for {
  172. conn1, err := accept(listen1)
  173. if err != nil {
  174. if !c.Running {
  175. return nil
  176. }
  177. continue
  178. }
  179. conn2, err := accept(listen2)
  180. if err != nil {
  181. if !c.Running {
  182. return nil
  183. }
  184. continue
  185. }
  186. if conn1 == nil || conn2 == nil {
  187. log.Println("[x]", "accept client faild. retry in ", c.Timeout, " seconds. ")
  188. time.Sleep(time.Duration(c.Timeout) * time.Second)
  189. continue
  190. }
  191. forward(conn1, conn2, &c.aTobAccumulatedByteTransfer, &c.bToaAccumulatedByteTransfer)
  192. }
  193. }
  194. /*
  195. portA -> server
  196. server -> portB
  197. */
  198. func (c *ProxyRelayConfig) Port2host(allowPort string, targetAddress string, stopChan chan bool) error {
  199. server, err := startListener("0.0.0.0:" + allowPort)
  200. if err != nil {
  201. return err
  202. }
  203. //Start stop handler
  204. go func() {
  205. <-stopChan
  206. log.Println("[x]", "Received stop signal. Exiting Port to Host forwarder")
  207. c.Running = false
  208. server.Close()
  209. }()
  210. //Start blocking loop for accepting connections
  211. for {
  212. conn, err := accept(server)
  213. if conn == nil || err != nil {
  214. if !c.Running {
  215. //Terminate by stop chan. Exit listener loop
  216. return nil
  217. }
  218. //Connection error. Retry
  219. continue
  220. }
  221. go func(targetAddress string) {
  222. log.Println("[+]", "start connect host:["+targetAddress+"]")
  223. target, err := net.Dial("tcp", targetAddress)
  224. if err != nil {
  225. // temporarily unavailable, don't use fatal.
  226. log.Println("[x]", "connect target address ["+targetAddress+"] faild. retry in ", c.Timeout, "seconds. ")
  227. conn.Close()
  228. log.Println("[←]", "close the connect at local:["+conn.LocalAddr().String()+"] and remote:["+conn.RemoteAddr().String()+"]")
  229. time.Sleep(time.Duration(c.Timeout) * time.Second)
  230. return
  231. }
  232. log.Println("[→]", "connect target address ["+targetAddress+"] success.")
  233. forward(target, conn, &c.aTobAccumulatedByteTransfer, &c.bToaAccumulatedByteTransfer)
  234. }(targetAddress)
  235. }
  236. }
  237. /*
  238. server -> portA
  239. server -> portB
  240. */
  241. func (c *ProxyRelayConfig) Host2host(address1, address2 string, stopChan chan bool) error {
  242. c.Running = true
  243. go func() {
  244. <-stopChan
  245. log.Println("[x]", "Received stop signal. Exiting Host to Host forwarder")
  246. c.Running = false
  247. }()
  248. for c.Running {
  249. log.Println("[+]", "try to connect host:["+address1+"] and ["+address2+"]")
  250. var host1, host2 net.Conn
  251. var err error
  252. for {
  253. d := net.Dialer{Timeout: time.Duration(c.Timeout)}
  254. host1, err = d.Dial("tcp", address1)
  255. if err == nil {
  256. log.Println("[→]", "connect ["+address1+"] success.")
  257. break
  258. } else {
  259. log.Println("[x]", "connect target address ["+address1+"] faild. retry in ", c.Timeout, " seconds. ")
  260. time.Sleep(time.Duration(c.Timeout) * time.Second)
  261. }
  262. if !c.Running {
  263. return nil
  264. }
  265. }
  266. for {
  267. d := net.Dialer{Timeout: time.Duration(c.Timeout)}
  268. host2, err = d.Dial("tcp", address2)
  269. if err == nil {
  270. log.Println("[→]", "connect ["+address2+"] success.")
  271. break
  272. } else {
  273. log.Println("[x]", "connect target address ["+address2+"] faild. retry in ", c.Timeout, " seconds. ")
  274. time.Sleep(time.Duration(c.Timeout) * time.Second)
  275. }
  276. if !c.Running {
  277. return nil
  278. }
  279. }
  280. forward(host1, host2, &c.aTobAccumulatedByteTransfer, &c.bToaAccumulatedByteTransfer)
  281. }
  282. return nil
  283. }