func readDataFromClient(ch chan []byte, conn net.Conn, key []byte) { for { buffer := make([]byte, 2) _, err := io.ReadFull(conn, buffer) if err != nil { ch <- nil return } size := binary.BigEndian.Uint16(buffer) buffer = make([]byte, size) _, err = io.ReadFull(conn, buffer) if err != nil { ch <- nil return } data, err := encrypt.Decrypt(buffer, key) if err != nil { fmt.Printf("ERROR: cannot decrypt data from client.") ch <- nil return } ch <- data } }
func handleClient(client net.Conn) { defer client.Close() key := getKey() buffer := make([]byte, 1) _, err := io.ReadFull(client, buffer) if err != nil { fmt.Printf("cannot read size from client.\n") return } buffer = make([]byte, buffer[0]) _, err = io.ReadFull(client, buffer) if err != nil { fmt.Printf("cannot read host from client.\n") return } host, err := encrypt.Decrypt(buffer, key[:]) if err != nil { fmt.Printf("ERROR: cannot decrypt host.\n") return } buffer = make([]byte, 2) _, err = io.ReadFull(client, buffer) if err != nil { fmt.Printf("cannot read port from client.\n") return } port := binary.BigEndian.Uint16(buffer) url := net.JoinHostPort(string(host), strconv.Itoa(int(port))) // fmt.Printf("url: %s\n", url) remote, err := net.Dial("tcp", url) if err != nil { fmt.Printf("ERROR: cannot dial to %s\n", url) return } ch_client := make(chan []byte) ch_remote := make(chan DataInfo) go readDataFromClient(ch_client, client, key[:]) go readDataFromRemote(ch_remote, remote) for { select { case data := <-ch_client: if data == nil { client.Close() break } remote.Write(data) case di := <-ch_remote: if di.data == nil { remote.Close() break } buffer = encrypt.Encrypt(di.data[:di.size], key[:]) b := make([]byte, 2) binary.BigEndian.PutUint16(b, uint16(len(buffer))) client.Write(b) client.Write(buffer) } } }