sshRemoteForward starts forwarding connections from a remote listener to a local address via SSH in a goroutine. Accepts a `cookieAddr` as the local address.
(ctx context.Context, stderr io.Writer, sshClient *gossh.Client, localAddr, remoteAddr net.Addr)
| 105 | // |
| 106 | // Accepts a `cookieAddr` as the local address. |
| 107 | func sshRemoteForward(ctx context.Context, stderr io.Writer, sshClient *gossh.Client, localAddr, remoteAddr net.Addr) (io.Closer, error) { |
| 108 | listener, err := sshClient.Listen(remoteAddr.Network(), remoteAddr.String()) |
| 109 | if err != nil { |
| 110 | return nil, xerrors.Errorf("listen on remote SSH address %s: %w", remoteAddr.String(), err) |
| 111 | } |
| 112 | |
| 113 | go func() { |
| 114 | for { |
| 115 | remoteConn, err := listener.Accept() |
| 116 | if err != nil { |
| 117 | if ctx.Err() == nil { |
| 118 | _, _ = fmt.Fprintf(stderr, "Accept SSH listener connection: %+v\n", err) |
| 119 | } |
| 120 | return |
| 121 | } |
| 122 | |
| 123 | go func() { |
| 124 | defer remoteConn.Close() |
| 125 | |
| 126 | localConn, err := net.Dial(localAddr.Network(), localAddr.String()) |
| 127 | if err != nil { |
| 128 | _, _ = fmt.Fprintf(stderr, "Dial local address %s: %+v\n", localAddr.String(), err) |
| 129 | return |
| 130 | } |
| 131 | defer localConn.Close() |
| 132 | |
| 133 | if c, ok := localAddr.(cookieAddr); ok { |
| 134 | _, err = localConn.Write(c.cookie) |
| 135 | if err != nil { |
| 136 | _, _ = fmt.Fprintf(stderr, "Write cookie to local connection: %+v\n", err) |
| 137 | return |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | agentssh.Bicopy(ctx, localConn, remoteConn) |
| 142 | }() |
| 143 | } |
| 144 | }() |
| 145 | |
| 146 | return listener, nil |
| 147 | } |