// wsbx-fwd: guest side of the host tunnel. // Usage: wsbx-fwd PORT=VSOCKPORT... // Listens on 127.0.0.1:PORT and [::1]:PORT and pipes each connection to the host (vsock CID 2). package main import ( "encoding/binary" "fmt" "io" "net" "os" "strconv" "strings" "syscall" "unsafe" ) const afVsock = 40 func dialHost(port uint32) (*os.File, error) { fd, err := syscall.Socket(afVsock, syscall.SOCK_STREAM|syscall.SOCK_CLOEXEC, 0) if err != nil { return nil, err } // struct sockaddr_vm { u16 family; u16 reserved; u32 port; u32 cid; u8 flags; u8 zero[3]; } var sa [16]byte binary.LittleEndian.PutUint16(sa[0:], afVsock) binary.LittleEndian.PutUint32(sa[4:], port) binary.LittleEndian.PutUint32(sa[8:], 2) // VMADDR_CID_HOST if _, _, e := syscall.Syscall(syscall.SYS_CONNECT, uintptr(fd), uintptr(unsafe.Pointer(&sa[0])), 16); e != 0 { syscall.Close(fd) return nil, e } return os.NewFile(uintptr(fd), "vsock"), nil } func handle(c *net.TCPConn, port uint32) { defer c.Close() f, err := dialHost(port) if err != nil { fmt.Fprintln(os.Stderr, "wsbx-fwd: vsock:", err) return } defer f.Close() done := make(chan struct{}) go func() { io.Copy(c, f) c.CloseWrite() close(done) }() io.Copy(f, c) syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR) <-done } func main() { for _, spec := range os.Args[1:] { p, v, _ := strings.Cut(spec, "=") vport, err := strconv.ParseUint(v, 10, 32) if err != nil { fmt.Fprintln(os.Stderr, "wsbx-fwd: bad spec", spec) os.Exit(2) } for _, addr := range []string{"127.0.0.1:" + p, "[::1]:" + p} { ln, err := net.Listen("tcp", addr) if err != nil { fmt.Fprintln(os.Stderr, "wsbx-fwd:", err) continue } go func() { for { c, err := ln.Accept() if err == nil { go handle(c.(*net.TCPConn), uint32(vport)) } } }() } } // Signal readiness (run.sh waits on this) before the agent starts. fmt.Println("ready") os.Stdout.Close() select {} }