aboutsummaryrefslogtreecommitdiff
path: root/src/runtime/internal/wasitest/tcpecho_test.go
blob: c56af2cc85d4a80cee96ad13db9dd6c908af8e9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package wasi_test

import (
	"bytes"
	"fmt"
	"math/rand"
	"net"
	"os"
	"os/exec"
	"testing"
	"time"
)

func TestTCPEcho(t *testing.T) {
	if target != "wasip1/wasm" {
		t.Skip()
	}

	// We're unable to pass port 0 here (let the OS choose a spare port).
	// Although wasmtime accepts port 0, and testdata/main.go successfully
	// listens, there's no way for this test case to query the chosen port
	// so that it can connect to the WASM module. The WASM module itself
	// cannot access any information about the socket due to limitations
	// with WASI preview 1 networking, and wasmtime does not log the address
	// when you preopen a socket. Instead, we probe for a free port here.
	var host string
	port := rand.Intn(10000) + 40000
	for attempts := 0; attempts < 10; attempts++ {
		host = fmt.Sprintf("127.0.0.1:%d", port)
		l, err := net.Listen("tcp", host)
		if err == nil {
			l.Close()
			break
		}
		port++
	}

	subProcess := exec.Command("go", "run", "./testdata/tcpecho.go")

	subProcess.Env = append(os.Environ(), "GOOS=wasip1", "GOARCH=wasm")

	switch os.Getenv("GOWASIRUNTIME") {
	case "wazero", "":
		subProcess.Env = append(subProcess.Env, "GOWASIRUNTIMEARGS=--listen="+host)
	case "wasmtime":
		subProcess.Env = append(subProcess.Env, "GOWASIRUNTIMEARGS=--tcplisten="+host)
	default:
		t.Skip("WASI runtime does not support sockets")
	}

	var b bytes.Buffer
	subProcess.Stdout = &b
	subProcess.Stderr = &b

	if err := subProcess.Start(); err != nil {
		t.Log(b.String())
		t.Fatal(err)
	}
	defer subProcess.Process.Kill()

	var conn net.Conn
	var err error
	for attempts := 0; attempts < 5; attempts++ {
		conn, err = net.Dial("tcp", host)
		if err == nil {
			break
		}
		time.Sleep(500 * time.Millisecond)
	}
	if err != nil {
		t.Log(b.String())
		t.Fatal(err)
	}
	defer conn.Close()

	payload := []byte("foobar")
	if _, err := conn.Write(payload); err != nil {
		t.Fatal(err)
	}
	var buf [256]byte
	n, err := conn.Read(buf[:])
	if err != nil {
		t.Fatal(err)
	}
	if string(buf[:n]) != string(payload) {
		t.Error("unexpected payload")
		t.Logf("expect: %d bytes (%v)", len(payload), payload)
		t.Logf("actual: %d bytes (%v)", n, buf[:n])
	}
}