Skip to content

Use common Windows Subsystem path helper for calling tools on Windows #3300

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions cmd/limactl/copy.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@ import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"

"github.com/coreos/go-semver/semver"
"github.com/lima-vm/lima/pkg/ioutilx"
"github.com/lima-vm/lima/pkg/sshutil"
"github.com/lima-vm/lima/pkg/store"
"github.com/sirupsen/logrus"
Expand Down Expand Up @@ -80,6 +83,16 @@ func copyAction(cmd *cobra.Command, args []string) error {
// this assumes that ssh and scp come from the same place, but scp has no -V
legacySSH := sshutil.DetectOpenSSHVersion("ssh").LessThan(*semver.New("8.0.0"))
for _, arg := range args {
if runtime.GOOS == "windows" {
if filepath.IsAbs(arg) {
arg, err = ioutilx.WindowsSubsystemPath(arg)
if err != nil {
return err
}
} else {
arg = filepath.ToSlash(arg)
}
}
path := strings.Split(arg, ":")
switch len(path) {
case 1:
Expand Down
17 changes: 17 additions & 0 deletions cmd/limactl/shell.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@ import (
"fmt"
"os"
"os/exec"
"path"
"runtime"
"strconv"
"strings"

"al.essio.dev/pkg/shellescape"
"github.com/coreos/go-semver/semver"
"github.com/lima-vm/lima/pkg/ioutilx"
"github.com/lima-vm/lima/pkg/sshutil"
"github.com/lima-vm/lima/pkg/store"
"github.com/mattn/go-isatty"
Expand Down Expand Up @@ -92,13 +95,19 @@ func shellAction(cmd *cobra.Command, args []string) error {
// FIXME: check whether y.Mounts contains the home, not just len > 0
} else if len(inst.Config.Mounts) > 0 {
hostCurrentDir, err := os.Getwd()
if err == nil && runtime.GOOS == "windows" {
hostCurrentDir, err = mountDirFromWindowsDir(hostCurrentDir)
}
if err == nil {
changeDirCmd = fmt.Sprintf("cd %s", shellescape.Quote(hostCurrentDir))
} else {
changeDirCmd = "false"
logrus.WithError(err).Warn("failed to get the current directory")
}
hostHomeDir, err := os.UserHomeDir()
if err == nil && runtime.GOOS == "windows" {
hostHomeDir, err = mountDirFromWindowsDir(hostHomeDir)
}
if err == nil {
changeDirCmd = fmt.Sprintf("%s || cd %s", changeDirCmd, shellescape.Quote(hostHomeDir))
} else {
Expand Down Expand Up @@ -189,6 +198,14 @@ func shellAction(cmd *cobra.Command, args []string) error {
return sshCmd.Run()
}

func mountDirFromWindowsDir(dir string) (string, error) {
dir, err := ioutilx.WindowsSubsystemPath(dir)
if err == nil && !strings.HasPrefix(dir, "/mnt/") {
dir = path.Join("/mnt", dir)
}
Comment on lines +203 to +205
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't get a chance to review this PR properly, but wanted to comment that the /mnt prefix is just a default setting; it can be changed (or disabled) by the user in /etc/wsl.conf:

[automount]
enabled = true
root = /windir

So in general the directory name cannot be determined without checking /etc/wsl.conf inside the distro where you want to use it first.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm aware of this setting, yet to see it in real life, though.

I was focused on the "default" configuration with this change. I have a fix in mind, will submit it this week and ask you to review #3303

return dir, err
}

func shellBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return bashCompleteInstanceNames(cmd)
}
Expand Down
7 changes: 5 additions & 2 deletions hack/test-templates.sh
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,11 @@ tmpdir="$(mktemp -d "${TMPDIR:-/tmp}"/lima-test-templates.XXXXXX)"
defer "rm -rf \"$tmpdir\""
tmpfile="$tmpdir/lima-hostname"
rm -f "$tmpfile"
# TODO support Windows path https://github.com/lima-vm/lima/issues/3215
limactl cp "$NAME":/etc/hostname "$tmpfile"
tmpfile_host=$tmpfile
if [ "${OS_HOST}" = "Msys" ]; then
tmpfile_host="$(cygpath -w "$tmpfile")"
fi
limactl cp "$NAME":/etc/hostname "$tmpfile_host"
expected="$(limactl shell "$NAME" cat /etc/hostname)"
got="$(cat "$tmpfile")"
INFO "/etc/hostname: expected=${expected}, got=${got}"
Expand Down
11 changes: 5 additions & 6 deletions pkg/ioutilx/ioutilx.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"io"
"os/exec"
"path/filepath"
"strings"

"github.com/sirupsen/logrus"
Expand Down Expand Up @@ -48,13 +49,11 @@ func FromUTF16leToString(r io.Reader) (string, error) {
return string(out), nil
}

func CanonicalWindowsPath(orig string) string {
newPath := orig
out, err := exec.Command("cygpath", "-m", orig).CombinedOutput()
func WindowsSubsystemPath(orig string) (string, error) {
out, err := exec.Command("cygpath", filepath.ToSlash(orig)).CombinedOutput()
if err != nil {
logrus.WithError(err).Errorf("failed to convert path to mingw, maybe not using Git ssh?")
} else {
newPath = strings.TrimSpace(string(out))
return orig, err
}
return newPath
return strings.TrimSpace(string(out)), nil
}
7 changes: 6 additions & 1 deletion pkg/osutil/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"strings"
"sync"

"github.com/lima-vm/lima/pkg/ioutilx"
. "github.com/lima-vm/lima/pkg/must"
"github.com/lima-vm/lima/pkg/version/versionutil"
"github.com/sirupsen/logrus"
Expand Down Expand Up @@ -144,7 +145,7 @@ func LimaUser(limaVersion string, warn bool) *user.User {
warnings = append(warnings, warning)
limaUser.Gid = formatUidGid(gid)
}
home, err := call([]string{"cygpath", limaUser.HomeDir})
home, err := ioutilx.WindowsSubsystemPath(limaUser.HomeDir)
if err != nil {
logrus.Debug(err)
} else {
Expand All @@ -159,6 +160,10 @@ func LimaUser(limaVersion string, warn bool) *user.User {
home += ".linux"
}
if !regexPath.MatchString(limaUser.HomeDir) {
// Trim prefix of well known default mounts
if strings.HasPrefix(home, "/mnt/") {
home = strings.TrimPrefix(home, "/mnt")
}
warning := fmt.Sprintf("local home %q is not a valid Linux path (must match %q); using %q home instead",
limaUser.HomeDir, regexPath.String(), home)
warnings = append(warnings, warning)
Expand Down
42 changes: 31 additions & 11 deletions pkg/sshutil/sshutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,15 @@ func DefaultPubKeys(loadDotSSH bool) ([]PubKey, error) {
}
if err := lockutil.WithDirLock(configDir, func() error {
// no passphrase, no user@host comment
privPath := filepath.Join(configDir, filenames.UserPrivateKey)
if runtime.GOOS == "windows" {
privPath, err = ioutilx.WindowsSubsystemPath(privPath)
if err != nil {
return err
}
}
keygenCmd := exec.Command("ssh-keygen", "-t", "ed25519", "-q", "-N", "",
"-C", "lima", "-f", filepath.Join(configDir, filenames.UserPrivateKey))
"-C", "lima", "-f", privPath)
logrus.Debugf("executing %v", keygenCmd.Args)
if out, err := keygenCmd.CombinedOutput(); err != nil {
return fmt.Errorf("failed to run %v: %q: %w", keygenCmd.Args, string(out), err)
Expand Down Expand Up @@ -171,12 +178,11 @@ func CommonOpts(sshPath string, useDotSSH bool) ([]string, error) {
return nil, err
}
var opts []string
if runtime.GOOS == "windows" {
privateKeyPath = ioutilx.CanonicalWindowsPath(privateKeyPath)
opts = []string{fmt.Sprintf(`IdentityFile='%s'`, privateKeyPath)}
} else {
opts = []string{fmt.Sprintf(`IdentityFile="%s"`, privateKeyPath)}
idf, err := identityFileEntry(privateKeyPath)
if err != nil {
return nil, err
}
opts = []string{idf}

// Append all private keys corresponding to ~/.ssh/*.pub to keep old instances working
// that had been created before lima started using an internal identity.
Expand Down Expand Up @@ -207,11 +213,11 @@ func CommonOpts(sshPath string, useDotSSH bool) ([]string, error) {
// Fail on permission-related and other path errors
return nil, err
}
if runtime.GOOS == "windows" {
opts = append(opts, fmt.Sprintf(`IdentityFile='%s'`, privateKeyPath))
} else {
opts = append(opts, fmt.Sprintf(`IdentityFile="%s"`, privateKeyPath))
idf, err = identityFileEntry(privateKeyPath)
if err != nil {
return nil, err
}
opts = append(opts, idf)
}
}

Expand Down Expand Up @@ -256,6 +262,17 @@ func CommonOpts(sshPath string, useDotSSH bool) ([]string, error) {
return opts, nil
}

func identityFileEntry(privateKeyPath string) (string, error) {
if runtime.GOOS == "windows" {
privateKeyPath, err := ioutilx.WindowsSubsystemPath(privateKeyPath)
if err != nil {
return "", err
}
return fmt.Sprintf(`IdentityFile='%s'`, privateKeyPath), nil
}
return fmt.Sprintf(`IdentityFile="%s"`, privateKeyPath), nil
}

// SSHOpts adds the following options to CommonOptions: User, ControlMaster, ControlPath, ControlPersist.
func SSHOpts(sshPath, instDir, username string, useDotSSH, forwardAgent, forwardX11, forwardX11Trusted bool) ([]string, error) {
controlSock := filepath.Join(instDir, filenames.SSHSock)
Expand All @@ -268,7 +285,10 @@ func SSHOpts(sshPath, instDir, username string, useDotSSH, forwardAgent, forward
}
controlPath := fmt.Sprintf(`ControlPath="%s"`, controlSock)
if runtime.GOOS == "windows" {
controlSock = ioutilx.CanonicalWindowsPath(controlSock)
controlSock, err = ioutilx.WindowsSubsystemPath(controlSock)
if err != nil {
return nil, err
}
controlPath = fmt.Sprintf(`ControlPath='%s'`, controlSock)
}
opts = append(opts,
Expand Down
Loading