// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
	"fmt"
	"os"
	"path"
	"path/filepath"
	"testing"

	specs "github.com/opencontainers/runtime-spec/specs-go"
	"gvisor.dev/gvisor/runsc/boot"
	"gvisor.dev/gvisor/runsc/cmd/sandboxsetup"
	"gvisor.dev/gvisor/runsc/specutils"
)

func tmpDir() string {
	if dir, ok := os.LookupEnv("TEST_TMPDIR"); ok {
		return dir
	}
	return "/tmp"
}

type dir struct {
	rel  string
	link string
}

func construct(root string, dirs []dir) error {
	for _, d := range dirs {
		p := path.Join(root, d.rel)
		if d.link == "" {
			if err := os.MkdirAll(p, 0755); err != nil {
				return fmt.Errorf("error creating dir: %v", err)
			}
		} else {
			if err := os.MkdirAll(path.Dir(p), 0755); err != nil {
				return fmt.Errorf("error creating dir: %v", err)
			}
			if err := os.Symlink(d.link, p); err != nil {
				return fmt.Errorf("error creating symlink: %v", err)
			}
		}
	}
	return nil
}

func TestResolveSymlinks(t *testing.T) {
	root, err := os.MkdirTemp(tmpDir(), "root")
	if err != nil {
		t.Fatal("os.MkdirTemp() failed:", err)
	}
	dirs := []dir{
		{"dir1/dir11/dir111/dir1111", ""}, // Just a boring dir
		{"dir1/lnk12", "dir11"},           // Link to sibling
		{"dir1/lnk13", "./dir11"},         // Link to sibling through self
		{"dir1/lnk14", "../dir1/dir11"},   // Link to sibling through parent
		{"dir1/dir15/lnk151", ".."},       // Link to parent
		{"dir1/lnk16", "dir11/dir111"},    // Link to child
		{"dir1/lnk17", "."},               // Link to self
		{"dir1/lnk18", "lnk13"},           // Link to link
		{"lnk2", "dir1/lnk13"},            // Link to link to link
		{"dir3/dir21/lnk211", "../.."},    // Link to root relative
		{"dir3/lnk22", "/"},               // Link to root absolute
		{"dir3/lnk23", "/dir1"},           // Link to dir absolute
		{"dir3/lnk24", "/dir1/lnk12"},     // Link to link absolute
		{"lnk5", "../../.."},              // Link outside root
	}
	if err := construct(root, dirs); err != nil {
		t.Fatal("construct failed:", err)
	}

	tests := []struct {
		name        string
		rel         string
		want        string
		compareHost bool
	}{
		{name: "root", rel: "/", want: "/", compareHost: true},
		{name: "basic dir", rel: "/dir1/dir11/dir111", want: "/dir1/dir11/dir111", compareHost: true},
		{name: "dot 1", rel: "/dir1/dir11/./dir111", want: "/dir1/dir11/dir111", compareHost: true},
		{name: "dot 2", rel: "/dir1/././dir11/./././././dir111/.", want: "/dir1/dir11/dir111", compareHost: true},
		{name: "dotdot 1", rel: "/dir1/dir11/../dir15", want: "/dir1/dir15", compareHost: true},
		{name: "dotdot 2", rel: "/dir1/dir11/dir1111/../..", want: "/dir1", compareHost: true},

		{name: "link sibling", rel: "/dir1/lnk12", want: "/dir1/dir11", compareHost: true},
		{name: "link sibling + dir", rel: "/dir1/lnk12/dir111", want: "/dir1/dir11/dir111", compareHost: true},
		{name: "link sibling through self", rel: "/dir1/lnk13", want: "/dir1/dir11", compareHost: true},
		{name: "link sibling through parent", rel: "/dir1/lnk14", want: "/dir1/dir11", compareHost: true},

		{name: "link parent", rel: "/dir1/dir15/lnk151", want: "/dir1", compareHost: true},
		{name: "link parent + dir", rel: "/dir1/dir15/lnk151/dir11", want: "/dir1/dir11", compareHost: true},
		{name: "link child", rel: "/dir1/lnk16", want: "/dir1/dir11/dir111", compareHost: true},
		{name: "link child + dir", rel: "/dir1/lnk16/dir1111", want: "/dir1/dir11/dir111/dir1111", compareHost: true},
		{name: "link self", rel: "/dir1/lnk17", want: "/dir1", compareHost: true},
		{name: "link self + dir", rel: "/dir1/lnk17/dir11", want: "/dir1/dir11", compareHost: true},

		{name: "link^2", rel: "/dir1/lnk18", want: "/dir1/dir11", compareHost: true},
		{name: "link^2 + dir", rel: "/dir1/lnk18/dir111", want: "/dir1/dir11/dir111", compareHost: true},
		{name: "link^3", rel: "/lnk2", want: "/dir1/dir11", compareHost: true},
		{name: "link^3 + dir", rel: "/lnk2/dir111", want: "/dir1/dir11/dir111", compareHost: true},

		{name: "link abs", rel: "/dir3/lnk23", want: "/dir1"},
		{name: "link abs + dir", rel: "/dir3/lnk23/dir11", want: "/dir1/dir11"},
		{name: "link^2 abs", rel: "/dir3/lnk24", want: "/dir1/dir11"},
		{name: "link^2 abs + dir", rel: "/dir3/lnk24/dir111", want: "/dir1/dir11/dir111"},

		{name: "root link rel", rel: "/dir3/dir21/lnk211", want: "/", compareHost: true},
		{name: "root link abs", rel: "/dir3/lnk22", want: "/"},
		{name: "root contain link", rel: "/lnk5/dir1", want: "/dir1"},
		{name: "root contain dotdot", rel: "/dir1/dir11/../../../../../../../..", want: "/"},

		{name: "crazy", rel: "/dir3/dir21/lnk211/dir3/lnk22/dir1/dir11/../../lnk5/dir3/../dir3/lnk24/dir111/dir1111/..", want: "/dir1/dir11/dir111"},
	}
	for _, tst := range tests {
		t.Run(tst.name, func(t *testing.T) {
			got, err := sandboxsetup.ResolveSymlinks(root, tst.rel)
			if err != nil {
				t.Errorf("ResolveSymlinks(root, %q) failed: %v", tst.rel, err)
			}
			want := path.Join(root, tst.want)
			if got != want {
				t.Errorf("ResolveSymlinks(root, %q) got: %q, want: %q", tst.rel, got, want)
			}
			if tst.compareHost {
				// Check that host got to the same end result.
				host, err := filepath.EvalSymlinks(path.Join(root, tst.rel))
				if err != nil {
					t.Errorf("path.EvalSymlinks(root, %q) failed: %v", tst.rel, err)
				}
				if host != got {
					t.Errorf("ResolveSymlinks(root, %q) got: %q, want: %q", tst.rel, host, got)
				}
			}
		})
	}
}

func TestResolveSymlinksLoop(t *testing.T) {
	root, err := os.MkdirTemp(tmpDir(), "root")
	if err != nil {
		t.Fatal("os.MkdirTemp() failed:", err)
	}
	dirs := []dir{
		{"loop1", "loop2"},
		{"loop2", "loop1"},
	}
	if err := construct(root, dirs); err != nil {
		t.Fatal("construct failed:", err)
	}
	if _, err := sandboxsetup.ResolveSymlinks(root, "loop1"); err == nil {
		t.Errorf("ResolveSymlinks() should have failed")
	}
}

func TestLisafsNeededForDirectFSSuppression(t *testing.T) {
	for _, tc := range []struct {
		name       string
		spec       *specs.Spec
		mountConfs []specutils.GoferMountConf
		want       bool
	}{
		{
			name:       "no suppression",
			spec:       suppressedMountSpec("foo", "default"),
			mountConfs: lisafsMountConfs(),
		},
		{
			name:       "suppressed lisafs mount",
			spec:       suppressedMountSpec("foo", "off"),
			mountConfs: lisafsMountConfs(),
			want:       true,
		},
		{
			name:       "suppressed mount not in spec",
			spec:       suppressedMountSpec("bar", "off"),
			mountConfs: lisafsMountConfs(),
		},
		{
			name: "suppressed erofs mount",
			spec: suppressedMountSpec("foo", "off"),
			mountConfs: []specutils.GoferMountConf{
				{Lower: specutils.Lisafs, Upper: specutils.NoOverlay},
				{Lower: specutils.Erofs, Upper: specutils.NoOverlay},
			},
		},
		{
			name:       "suppressed bind rootfs",
			spec:       suppressedRootfsSpec("bind", "off"),
			mountConfs: rootfsOnlyMountConfs(specutils.Lisafs),
			want:       true,
		},
		{
			name:       "rootfs hint without suppression",
			spec:       suppressedRootfsSpec("bind", "default"),
			mountConfs: rootfsOnlyMountConfs(specutils.Lisafs),
		},
		{
			name:       "suppressed erofs rootfs",
			spec:       suppressedRootfsSpec("erofs", "off"),
			mountConfs: rootfsOnlyMountConfs(specutils.Erofs),
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			mountHints, err := boot.NewPodMountHints(tc.spec)
			if err != nil {
				t.Fatalf("NewPodMountHints failed: %v", err)
			}
			rootfsHint, err := boot.NewRootfsHint(tc.spec)
			if err != nil {
				t.Fatalf("NewRootfsHint failed: %v", err)
			}
			if got := lisafsNeededForDirectFSSuppression(tc.spec, mountHints, rootfsHint, tc.mountConfs); got != tc.want {
				t.Errorf("lisafsNeededForDirectFSSuppression = %t, want %t", got, tc.want)
			}
		})
	}
}

func suppressedMountSpec(hintSource, directfs string) *specs.Spec {
	return &specs.Spec{
		Annotations: map[string]string{
			boot.MountPrefix + "mount1.source":   hintSource,
			boot.MountPrefix + "mount1.type":     "bind",
			boot.MountPrefix + "mount1.share":    "container",
			boot.MountPrefix + "mount1.directfs": directfs,
		},
		Mounts: []specs.Mount{
			{
				Source:      "foo",
				Type:        "bind",
				Destination: "/mnt",
			},
		},
	}
}

func suppressedRootfsSpec(rootfsType, directfs string) *specs.Spec {
	return &specs.Spec{
		Annotations: map[string]string{
			boot.RootfsPrefix + "source":   "/tmp/rootfs",
			boot.RootfsPrefix + "type":     rootfsType,
			boot.RootfsPrefix + "directfs": directfs,
		},
	}
}

func lisafsMountConfs() []specutils.GoferMountConf {
	return []specutils.GoferMountConf{
		{Lower: specutils.Lisafs, Upper: specutils.NoOverlay},
		{Lower: specutils.Lisafs, Upper: specutils.NoOverlay},
	}
}

func rootfsOnlyMountConfs(lower specutils.GoferMountConfLowerType) []specutils.GoferMountConf {
	return []specutils.GoferMountConf{
		{Lower: lower, Upper: specutils.NoOverlay},
	}
}
