@@ -2,6 +2,7 @@ package codespaces
22
33import (
44 "context"
5+ "errors"
56 "fmt"
67 "io"
78 "math/rand"
@@ -14,7 +15,7 @@ import (
1415 "github.com/github/go-liveshare"
1516)
1617
17- func MakeSSHTunnel (ctx context.Context , lsclient * liveshare.Client , serverPort int ) (int , <- chan error , error ) {
18+ func MakeSSHTunnel (ctx context.Context , lsclient * liveshare.Client , localSSHPort int , remoteSSHPort int ) (int , <- chan error , error ) {
1819 tunnelClosed := make (chan error )
1920
2021 server , err := liveshare .NewServer (lsclient )
@@ -24,12 +25,11 @@ func MakeSSHTunnel(ctx context.Context, lsclient *liveshare.Client, serverPort i
2425
2526 rand .Seed (time .Now ().Unix ())
2627 port := rand .Intn (9999 - 2000 ) + 2000 // improve this obviously
27- if serverPort != 0 {
28- port = serverPort
28+ if localSSHPort != 0 {
29+ port = localSSHPort
2930 }
3031
31- // TODO(josebalius): This port won't always be 2222
32- if err := server .StartSharing (ctx , "sshd" , 2222 ); err != nil {
32+ if err := server .StartSharing (ctx , "sshd" , remoteSSHPort ); err != nil {
3333 return 0 , nil , fmt .Errorf ("sharing sshd port: %v" , err )
3434 }
3535
@@ -45,6 +45,33 @@ func MakeSSHTunnel(ctx context.Context, lsclient *liveshare.Client, serverPort i
4545 return port , tunnelClosed , nil
4646}
4747
48+ // StartSSHServer installs (if necessary) and starts the SSH in the codespace.
49+ // It returns the remote port where it is running, the user to log in with, or an error if something failed.
50+ func StartSSHServer (ctx context.Context , client * liveshare.Client , log logger ) (serverPort int , user string , err error ) {
51+ log .Println ("Fetching SSH details..." )
52+
53+ sshServer , err := liveshare .NewSSHServer (client )
54+ if err != nil {
55+ return 0 , "" , fmt .Errorf ("error creating live share: %v" , err )
56+ }
57+
58+ sshServerStartResult , err := sshServer .StartRemoteServer (ctx )
59+ if err != nil {
60+ return 0 , "" , fmt .Errorf ("error starting live share: %v" , err )
61+ }
62+
63+ if ! sshServerStartResult .Result {
64+ return 0 , "" , errors .New (sshServerStartResult .Message )
65+ }
66+
67+ portInt , err := strconv .Atoi (sshServerStartResult .ServerPort )
68+ if err != nil {
69+ return 0 , "" , fmt .Errorf ("error parsing port: %v" , err )
70+ }
71+
72+ return portInt , sshServerStartResult .User , nil
73+ }
74+
4875func makeSSHArgs (port int , dst , cmd string ) ([]string , []string ) {
4976 connArgs := []string {"-p" , strconv .Itoa (port ), "-o" , "NoHostAuthenticationForLocalhost=yes" }
5077 cmdArgs := append ([]string {dst , "-X" , "-Y" , "-C" }, connArgs ... ) // X11, X11Trust, Compression
0 commit comments