Browse Source

auto update script executed

Toby Chui 1 year ago
parent
commit
c00c8acd58
2 changed files with 67 additions and 2 deletions
  1. 65 0
      mod/tcpprox/conn.go
  2. 2 2
      mod/tcpprox/tcpprox_test.go

+ 65 - 0
mod/tcpprox/conn.go

@@ -5,6 +5,7 @@ import (
 	"io"
 	"log"
 	"net"
+	"strconv"
 	"sync"
 	"time"
 )
@@ -14,6 +15,29 @@ func isValidIP(ip string) bool {
 	return parsedIP != nil
 }
 
+func isValidPort(port string) bool {
+	portInt, err := strconv.Atoi(port)
+	if err != nil {
+		return false
+	}
+
+	if portInt < 1 || portInt > 65535 {
+		return false
+	}
+
+	return true
+}
+
+func isReachable(target string) bool {
+	timeout := time.Duration(2 * time.Second) // Set the timeout value as per your requirement
+	conn, err := net.DialTimeout("tcp", target, timeout)
+	if err != nil {
+		return false
+	}
+	defer conn.Close()
+	return true
+}
+
 func connCopy(conn1 net.Conn, conn2 net.Conn, wg *sync.WaitGroup, accumulator *int64) {
 	io.Copy(conn1, conn2)
 	conn1.Close()
@@ -53,11 +77,52 @@ func startListener(address string) (net.Listener, error) {
 	return server, nil
 }
 
+// Config validator
+func (c *ProxyRelayConfig) ValidateConfigs() error {
+	if c.Mode == ProxyMode_Transport {
+		//Port2Host: PortA int, PortB string
+		if !isValidPort(c.PortA) {
+			return errors.New("first address must be a valid port number")
+		}
+
+		if !isReachable(c.PortB) {
+			return errors.New("second address is unreachable")
+		}
+		return nil
+
+	} else if c.Mode == ProxyMode_Listen {
+		//Port2Port: Both port are port number
+		if !isValidPort(c.PortA) {
+			return errors.New("first address is not a valid port number")
+		}
+
+		if !isValidPort(c.PortB) {
+			return errors.New("second address is not a valid port number")
+		}
+
+		return nil
+	} else if c.Mode == ProxyMode_Starter {
+		//Host2Host: Both have to be hosts
+		if !isReachable(c.PortA) {
+			return errors.New("first address is unreachable")
+		}
+
+		if !isReachable(c.PortB) {
+			return errors.New("second address is unreachable")
+		}
+
+		return nil
+	} else {
+		return errors.New("invalid mode given")
+	}
+}
+
 /*
 portA -> server
 portB -> server
 */
 func (c *ProxyRelayConfig) Port2port(port1 string, port2 string, stopChan chan bool) error {
+	//Trim the Prefix of : if exists
 	listen1, err := startListener("0.0.0.0:" + port1)
 	if err != nil {
 		return err

+ 2 - 2
mod/tcpprox/tcpprox_test.go

@@ -19,14 +19,14 @@ func TestPort2Port(t *testing.T) {
 	// Run port2port in a separate goroutine
 	t.Log("Starting go routine for proxy service")
 	go func() {
-		err := config.Port2host("8080", ":80", stopChan)
+		err := config.Port2host("8080", "124.244.86.40:8080", stopChan)
 		if err != nil {
 			t.Errorf("port2port returned an error: %v", err)
 		}
 	}()
 
 	// Let the goroutine run for a while
-	time.Sleep(10 * time.Second)
+	time.Sleep(20 * time.Second)
 
 	// Send a stop signal to stopChan
 	t.Log("Sending over stop signal")