conn.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 (c *ProxyRelayConfig) accept(listener net.Listener) (net.Conn, error) {
  53. conn, err := listener.Accept()
  54. if err != nil {
  55. return nil, err
  56. }
  57. //Check if connection in blacklist or whitelist
  58. if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
  59. if !c.parent.Options.AccessControlHandler(conn) {
  60. time.Sleep(300 * time.Millisecond)
  61. conn.Close()
  62. log.Println("[x]", "Connection from "+addr.IP.String()+" rejected by access control policy")
  63. return nil, errors.New("Connection from " + addr.IP.String() + " rejected by access control policy")
  64. }
  65. }
  66. log.Println("[√]", "accept a new client. remote address:["+conn.RemoteAddr().String()+"], local address:["+conn.LocalAddr().String()+"]")
  67. return conn, err
  68. }
  69. func startListener(address string) (net.Listener, error) {
  70. log.Println("[+]", "try to start server on:["+address+"]")
  71. server, err := net.Listen("tcp", address)
  72. if err != nil {
  73. return nil, errors.New("listen address [" + address + "] faild")
  74. }
  75. log.Println("[√]", "start listen at address:["+address+"]")
  76. return server, nil
  77. }
  78. /*
  79. Config Functions
  80. */
  81. // Config validator
  82. func (c *ProxyRelayConfig) ValidateConfigs() error {
  83. if c.Mode == ProxyMode_Transport {
  84. //Port2Host: PortA int, PortB string
  85. if !isValidPort(c.PortA) {
  86. return errors.New("first address must be a valid port number")
  87. }
  88. if !isReachable(c.PortB) {
  89. return errors.New("second address is unreachable")
  90. }
  91. return nil
  92. } else if c.Mode == ProxyMode_Listen {
  93. //Port2Port: Both port are port number
  94. if !isValidPort(c.PortA) {
  95. return errors.New("first address is not a valid port number")
  96. }
  97. if !isValidPort(c.PortB) {
  98. return errors.New("second address is not a valid port number")
  99. }
  100. return nil
  101. } else if c.Mode == ProxyMode_Starter {
  102. //Host2Host: Both have to be hosts
  103. if !isReachable(c.PortA) {
  104. return errors.New("first address is unreachable")
  105. }
  106. if !isReachable(c.PortB) {
  107. return errors.New("second address is unreachable")
  108. }
  109. return nil
  110. } else {
  111. return errors.New("invalid mode given")
  112. }
  113. }
  114. // Start a proxy if stopped
  115. func (c *ProxyRelayConfig) Start() error {
  116. if c.Running {
  117. return errors.New("proxy already running")
  118. }
  119. // Create a stopChan to control the loop
  120. stopChan := make(chan bool)
  121. c.stopChan = stopChan
  122. //Validate configs
  123. err := c.ValidateConfigs()
  124. if err != nil {
  125. return err
  126. }
  127. //Start the proxy service
  128. go func() {
  129. c.Running = true
  130. if c.Mode == ProxyMode_Transport {
  131. err = c.Port2host(c.PortA, c.PortB, stopChan)
  132. } else if c.Mode == ProxyMode_Listen {
  133. err = c.Port2port(c.PortA, c.PortB, stopChan)
  134. } else if c.Mode == ProxyMode_Starter {
  135. err = c.Host2host(c.PortA, c.PortB, stopChan)
  136. }
  137. if err != nil {
  138. c.Running = false
  139. log.Println("Error starting proxy service " + c.Name + "(" + c.UUID + "): " + err.Error())
  140. }
  141. }()
  142. //Successfully spawned off the proxy routine
  143. return nil
  144. }
  145. // Stop a running proxy if running
  146. func (c *ProxyRelayConfig) IsRunning() bool {
  147. return c.Running || c.stopChan != nil
  148. }
  149. // Stop a running proxy if running
  150. func (c *ProxyRelayConfig) Stop() {
  151. if c.Running || c.stopChan != nil {
  152. c.stopChan <- true
  153. time.Sleep(300 * time.Millisecond)
  154. c.stopChan = nil
  155. c.Running = false
  156. }
  157. }
  158. /*
  159. Forwarder Functions
  160. */
  161. /*
  162. portA -> server
  163. portB -> server
  164. */
  165. func (c *ProxyRelayConfig) Port2port(port1 string, port2 string, stopChan chan bool) error {
  166. //Trim the Prefix of : if exists
  167. listen1, err := startListener("0.0.0.0:" + port1)
  168. if err != nil {
  169. return err
  170. }
  171. listen2, err := startListener("0.0.0.0:" + port2)
  172. if err != nil {
  173. return err
  174. }
  175. log.Println("[√]", "listen port:", port1, "and", port2, "success. waiting for client...")
  176. c.Running = true
  177. go func() {
  178. <-stopChan
  179. log.Println("[x]", "Received stop signal. Exiting Port to Port forwarder")
  180. c.Running = false
  181. listen1.Close()
  182. listen2.Close()
  183. }()
  184. for {
  185. conn1, err := c.accept(listen1)
  186. if err != nil {
  187. if !c.Running {
  188. return nil
  189. }
  190. continue
  191. }
  192. conn2, err := c.accept(listen2)
  193. if err != nil {
  194. if !c.Running {
  195. return nil
  196. }
  197. continue
  198. }
  199. if conn1 == nil || conn2 == nil {
  200. log.Println("[x]", "accept client faild. retry in ", c.Timeout, " seconds. ")
  201. time.Sleep(time.Duration(c.Timeout) * time.Second)
  202. continue
  203. }
  204. go forward(conn1, conn2, &c.aTobAccumulatedByteTransfer, &c.bToaAccumulatedByteTransfer)
  205. }
  206. }
  207. /*
  208. portA -> server
  209. server -> portB
  210. */
  211. func (c *ProxyRelayConfig) Port2host(allowPort string, targetAddress string, stopChan chan bool) error {
  212. server, err := startListener("0.0.0.0:" + allowPort)
  213. if err != nil {
  214. return err
  215. }
  216. //Start stop handler
  217. go func() {
  218. <-stopChan
  219. log.Println("[x]", "Received stop signal. Exiting Port to Host forwarder")
  220. c.Running = false
  221. server.Close()
  222. }()
  223. //Start blocking loop for accepting connections
  224. for {
  225. conn, err := c.accept(server)
  226. if conn == nil || err != nil {
  227. if !c.Running {
  228. //Terminate by stop chan. Exit listener loop
  229. return nil
  230. }
  231. //Connection error. Retry
  232. continue
  233. }
  234. go func(targetAddress string) {
  235. log.Println("[+]", "start connect host:["+targetAddress+"]")
  236. target, err := net.Dial("tcp", targetAddress)
  237. if err != nil {
  238. // temporarily unavailable, don't use fatal.
  239. log.Println("[x]", "connect target address ["+targetAddress+"] faild. retry in ", c.Timeout, "seconds. ")
  240. conn.Close()
  241. log.Println("[←]", "close the connect at local:["+conn.LocalAddr().String()+"] and remote:["+conn.RemoteAddr().String()+"]")
  242. time.Sleep(time.Duration(c.Timeout) * time.Second)
  243. return
  244. }
  245. log.Println("[→]", "connect target address ["+targetAddress+"] success.")
  246. forward(target, conn, &c.aTobAccumulatedByteTransfer, &c.bToaAccumulatedByteTransfer)
  247. }(targetAddress)
  248. }
  249. }
  250. /*
  251. server -> portA
  252. server -> portB
  253. */
  254. func (c *ProxyRelayConfig) Host2host(address1, address2 string, stopChan chan bool) error {
  255. c.Running = true
  256. go func() {
  257. <-stopChan
  258. log.Println("[x]", "Received stop signal. Exiting Host to Host forwarder")
  259. c.Running = false
  260. }()
  261. for c.Running {
  262. log.Println("[+]", "try to connect host:["+address1+"] and ["+address2+"]")
  263. var host1, host2 net.Conn
  264. var err error
  265. for {
  266. d := net.Dialer{Timeout: time.Duration(c.Timeout)}
  267. host1, err = d.Dial("tcp", address1)
  268. if err == nil {
  269. log.Println("[→]", "connect ["+address1+"] success.")
  270. break
  271. } else {
  272. log.Println("[x]", "connect target address ["+address1+"] faild. retry in ", c.Timeout, " seconds. ")
  273. time.Sleep(time.Duration(c.Timeout) * time.Second)
  274. }
  275. if !c.Running {
  276. return nil
  277. }
  278. }
  279. for {
  280. d := net.Dialer{Timeout: time.Duration(c.Timeout)}
  281. host2, err = d.Dial("tcp", address2)
  282. if err == nil {
  283. log.Println("[→]", "connect ["+address2+"] success.")
  284. break
  285. } else {
  286. log.Println("[x]", "connect target address ["+address2+"] faild. retry in ", c.Timeout, " seconds. ")
  287. time.Sleep(time.Duration(c.Timeout) * time.Second)
  288. }
  289. if !c.Running {
  290. return nil
  291. }
  292. }
  293. go forward(host1, host2, &c.aTobAccumulatedByteTransfer, &c.bToaAccumulatedByteTransfer)
  294. }
  295. return nil
  296. }