| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | package vz |
| 7 | |
| 8 | import ( |
| 9 | "context" |
| 10 | "errors" |
| 11 | "net" |
| 12 | |
| 13 | "github.com/inetaf/tcpproxy" |
| 14 | "github.com/sirupsen/logrus" |
| 15 | ) |
| 16 | |
| 17 | func (m *virtualMachineWrapper) startVsockForwarder(ctx context.Context, vsockPort uint32, hostAddress string) error { |
| 18 | |
| 19 | conn, err := m.dialVsock(ctx, vsockPort) |
| 20 | if err != nil { |
| 21 | return err |
| 22 | } |
| 23 | conn.Close() |
| 24 | |
| 25 | _, _, err = net.SplitHostPort(hostAddress) |
| 26 | if err != nil { |
| 27 | return err |
| 28 | } |
| 29 | var lc net.ListenConfig |
| 30 | l, err := lc.Listen(ctx, "tcp", hostAddress) |
| 31 | if err != nil { |
| 32 | return err |
| 33 | } |
| 34 | go func() { |
| 35 | <-ctx.Done() |
| 36 | l.Close() |
| 37 | }() |
| 38 | logrus.Infof("Started vsock forwarder: %s -> vsock:%d on VM", hostAddress, vsockPort) |
| 39 | go func() { |
| 40 | defer l.Close() |
| 41 | for { |
| 42 | conn, err := l.Accept() |
| 43 | if err != nil { |
| 44 | if errors.Is(err, net.ErrClosed) { |
| 45 | return |
| 46 | } |
| 47 | logrus.WithError(err).Errorf("vsock forwarder accept error: %v", err) |
| 48 | } else { |
| 49 | p := tcpproxy.DialProxy{ |
| 50 | DialContext: func(_ context.Context, _, _ string) (net.Conn, error) { |
| 51 | return m.dialVsock(ctx, vsockPort) |
| 52 | }, |
| 53 | } |
| 54 | go p.HandleConn(conn) |
| 55 | } |
| 56 | select { |
| 57 | case <-ctx.Done(): |
| 58 | return |
| 59 | default: |
| 60 | continue |
| 61 | } |
| 62 | } |
| 63 | }() |
| 64 | return nil |
| 65 | } |
| 66 | |
| 67 | func (m *virtualMachineWrapper) dialVsock(_ context.Context, port uint32) (conn net.Conn, err error) { |
| 68 | for _, socket := range m.SocketDevices() { |
| 69 | conn, err = socket.Connect(port) |
| 70 | if err == nil { |
| 71 | return conn, nil |
| 72 | } |
| 73 | } |
| 74 | return nil, err |
| 75 | } |