// This implementation is shared between Linux and NsEnterMounter. Both pathname
// and base must be either already resolved symlinks or thet will be resolved in
// kubelet's mount namespace (in case it runs containerized).
769685
func doSafeMakeDir(pathname string, base string, perm os.FileMode) error {
	klog.V(4).Infof("Creating directory %q within base %q", pathname, base)

	if !mount.PathWithinBase(pathname, base) {
		return fmt.Errorf("path %s is outside of allowed base %s", pathname, base)
	}

	// Quick check if the directory already exists
	s, err := os.Stat(pathname)
	if err == nil {
		// Path exists
		if s.IsDir() {
			// The directory already exists. It can be outside of the parent,
			// but there is no race-proof check.
			klog.V(4).Infof("Directory %s already exists", pathname)
			return nil
		}
		return &os.PathError{Op: "mkdir", Path: pathname, Err: syscall.ENOTDIR}
	}

	// Find all existing directories
	existingPath, toCreate, err := findExistingPrefix(base, pathname)
	if err != nil {
		return fmt.Errorf("error opening directory %s: %s", pathname, err)
	}
	// Ensure the existing directory is inside allowed base
	fullExistingPath, err := filepath.EvalSymlinks(existingPath)
	if err != nil {
		return fmt.Errorf("error opening directory %s: %s", existingPath, err)
	}
	if !mount.PathWithinBase(fullExistingPath, base) {
		return fmt.Errorf("path %s is outside of allowed base %s", fullExistingPath, err)
	}

	klog.V(4).Infof("%q already exists, %q to create", fullExistingPath, filepath.Join(toCreate...))
	parentFD, err := doSafeOpen(fullExistingPath, base)
	if err != nil {
		return fmt.Errorf("cannot open directory %s: %s", existingPath, err)
	}
	childFD := -1
	defer func() {
		if parentFD != -1 {
			if err = syscall.Close(parentFD); err != nil {
				klog.V(4).Infof("Closing FD %v failed for safemkdir(%v): %v", parentFD, pathname, err)
			}
		}
		if childFD != -1 {
			if err = syscall.Close(childFD); err != nil {
				klog.V(4).Infof("Closing FD %v failed for safemkdir(%v): %v", childFD, pathname, err)
			}
		}
	}()

	currentPath := fullExistingPath
	// create the directories one by one, making sure nobody can change
	// created directory into symlink.
	for _, dir := range toCreate {
		currentPath = filepath.Join(currentPath, dir)
		klog.V(4).Infof("Creating %s", dir)
		err = syscall.Mkdirat(parentFD, currentPath, uint32(perm))
		if err != nil {
			return fmt.Errorf("cannot create directory %s: %s", currentPath, err)
		}
		// Dive into the created directory
		childFD, err := syscall.Openat(parentFD, dir, nofollowFlags, 0)
		if err != nil {
			return fmt.Errorf("cannot open %s: %s", currentPath, err)
		}
		// We can be sure that childFD is safe to use. It could be changed
		// by user after Mkdirat() and before Openat(), however:
		// - it could not be changed to symlink - we use nofollowFlags
		// - it could be changed to a file (or device, pipe, socket, ...)
		//   but either subsequent Mkdirat() fails or we mount this file
		//   to user's container. Security is no violated in both cases
		//   and user either gets error or the file that it can already access.

		if err = syscall.Close(parentFD); err != nil {
			klog.V(4).Infof("Closing FD %v failed for safemkdir(%v): %v", parentFD, pathname, err)
		}
		parentFD = childFD
		childFD = -1
	}

	// Everything was created. mkdirat(..., perm) above was affected by current
	// umask and we must apply the right permissions to the last directory
	// (that's the one that will be available to the container as subpath)
	// so user can read/write it. This is the behavior of previous code.
	// TODO: chmod all created directories, not just the last one.
	// parentFD is the last created directory.

	// Translate perm (os.FileMode) to uint32 that fchmod() expects
	kernelPerm := uint32(perm & os.ModePerm)
	if perm&os.ModeSetgid > 0 {
		kernelPerm |= syscall.S_ISGID
	}
	if perm&os.ModeSetuid > 0 {
		kernelPerm |= syscall.S_ISUID
	}
	if perm&os.ModeSticky > 0 {
		kernelPerm |= syscall.S_ISVTX
	}
	if err = syscall.Fchmod(parentFD, kernelPerm); err != nil {
		return fmt.Errorf("chmod %q failed: %s", currentPath, err)
	}
	return nil
}
1133555
func (mounter *Mounter) IsMountPointMatch(mp MountPoint, dir string) bool {
	return mp.Path == dir
}
415718
func (n *NsenterMounter) makeNsenterArgs(source, target, fstype string, options []string) []string {
	nsenterArgs := []string{
		"--mount=/rootfs/proc/1/ns/mnt",
		"--",
		n.absHostPath("mount"),
	}

	args := makeMountArgs(source, target, fstype, options)

	return append(nsenterArgs, args...)
}
522826
func (n *Mounter) IsLikelyNotMountPoint(file string) (bool, error) {
	file, err := filepath.Abs(file)
	if err != nil {
		return true, err
	}

	// Check the directory exists
	if _, err = os.Stat(file); os.IsNotExist(err) {
		klog.V(5).Infof("findmnt: directory %s does not exist", file)
		return true, err
	}

	// Resolve any symlinks in file, kernel would do the same and use the resolved path in /proc/mounts
	resolvedFile, err := n.EvalHostSymlinks(file)
	if err != nil {
		return true, err
	}

	// Add --first-only option: since we are testing for the absence of a mountpoint, it is sufficient to get only
	// the first of multiple possible mountpoints using --first-only.
	// Also add fstype output to make sure that the output of target file will give the full path
	// TODO: Need more refactoring for this function. Track the solution with issue #26996
	args := []string{"-o", "target,fstype", "--noheadings", "--first-only", "--target", resolvedFile}
	klog.V(5).Infof("nsenter findmnt args: %v", args)
	out, err := n.ne.Exec("findmnt", args).CombinedOutput()
	if err != nil {
		klog.V(2).Infof("Failed findmnt command for path %s: %s %v", resolvedFile, out, err)
		// Different operating systems behave differently for paths which are not mount points.
		// On older versions (e.g. 2.20.1) we'd get error, on newer ones (e.g. 2.26.2) we'd get "/".
		// It's safer to assume that it's not a mount point.
		return true, nil
	}
	mountTarget, err := parseFindMnt(string(out))
	if err != nil {
		return false, err
	}

	klog.V(5).Infof("IsLikelyNotMountPoint findmnt output for path %s: %v:", resolvedFile, mountTarget)

	if mountTarget == resolvedFile {
		klog.V(5).Infof("IsLikelyNotMountPoint: %s is a mount point", resolvedFile)
		return false, nil
	}
	klog.V(5).Infof("IsLikelyNotMountPoint: %s is not a mount point", resolvedFile)
	return true, nil
}
220019
func makeHostsMount(podDir, podIP, hostName, hostDomainName string, hostAliases []v1.HostAlias, useHostNetwork bool) (*kubecontainer.Mount, error) {
	hostsFilePath := path.Join(podDir, "etc-hosts")
	if err := ensureHostsFile(hostsFilePath, podIP, hostName, hostDomainName, hostAliases, useHostNetwork); err != nil {
		return nil, err
	}
	return &kubecontainer.Mount{
		Name:           "k8s-managed-etc-hosts",
		ContainerPath:  etcHostsPath,
		HostPath:       hostsFilePath,
		ReadOnly:       false,
		SELinuxRelabel: true,
	}, nil
}
77596
func (m *execMounter) IsLikelyNotMountPoint(file string) (bool, error) {
	return m.wrappedMounter.IsLikelyNotMountPoint(file)
}
543063
func makePDNameInternal(host volume.VolumeHost, pool string, image string) string {
	// Backward compatibility for the deprecated format: /var/lib/kubelet/plugins/kubernetes.io/rbd/rbd/pool-image-image.
	deprecatedDir := filepath.Join(host.GetPluginDir(rbdPluginName), "rbd", pool+"-image-"+image)
	info, err := os.Stat(deprecatedDir)
	if err == nil && info.IsDir() {
		// The device mount path has already been created with the deprecated format, return it.
		klog.V(5).Infof("Deprecated format path %s found", deprecatedDir)
		return deprecatedDir
	}
	// Return the canonical format path.
	return filepath.Join(host.GetPluginDir(rbdPluginName), volutil.MountsInGlobalPDPath, pool+"-image-"+image)
}
296303
func (k KeybaseServiceMeasured) EstablishMountDir(ctx context.Context) (string, error) {
	return k.delegate.EstablishMountDir(ctx)
}
601342
func (kc *kubeClient) ScaleDeployment(spaceName string, appName string, envName string, deployNumber int) (*int, error) {
	envNS, err := kc.getDeployableEnvironmentNamespace(envName)
	if err != nil {
		return nil, err
	}

	// Deployment Config name does not always match the application name, look up
	// DC name using available metadata
	dcName, err := kc.getDeploymentConfigNameForApp(envNS, appName, spaceName)
	if err != nil {
		return nil, err
	}

	// Look up the Scale for the DeploymentConfig corresponding to the application name in the provided environment
	scale, err := kc.GetDeploymentConfigScale(envNS, dcName)
	if err != nil {
		return nil, err
	}

	spec, ok := scale["spec"].(map[string]interface{})
	if !ok {
		log.Error(nil, map[string]interface{}{
			"err":              err,
			"space_name":       spaceName,
			"application_name": appName,
			"environment_name": envName,
		}, "invalid deployment config returned from endpoint")
		return nil, errs.New("invalid deployment config returned from endpoint: missing 'spec'")
	}

	replicas, pres := spec["replicas"]
	oldReplicas := 0 // replicas property may be missing from spec if set to 0
	if pres {
		oldReplicasFlt, ok := replicas.(float64)
		if !ok {
			return nil, errs.New("invalid deployment config returned from endpoint: 'replicas' is not a number")
		}
		oldReplicas = int(oldReplicasFlt)
	}
	spec["replicas"] = deployNumber

	_, err = kc.SetDeploymentConfigScale(envNS, dcName, scale)
	if err != nil {
		return nil, err
	}

	log.Info(nil, map[string]interface{}{
		"space_name":        spaceName,
		"application_name":  appName,
		"environment_name":  envName,
		"old_replica_count": oldReplicas,
		"new_replica_count": deployNumber,
	}, "scaled deployment to %d replicas", deployNumber)

	return &oldReplicas, nil
}
327788
func (b *KubeletBuilder) kubeletPath() string {
	kubeletCommand := "/usr/local/bin/kubelet"
	if b.Distribution == distros.DistributionCoreOS {
		kubeletCommand = "/opt/kubernetes/bin/kubelet"
	}
	if b.Distribution == distros.DistributionContainerOS {
		kubeletCommand = "/home/kubernetes/bin/kubelet"
	}
	return kubeletCommand
}
1013101
func findSELinuxfsMount(s *bufio.Scanner) string {
	for s.Scan() {
		txt := s.Text()
		// The first field after - is fs type.
		// Safe as spaces in mountpoints are encoded as \040
		if !strings.Contains(txt, " - selinuxfs ") {
			continue
		}
		const mPos = 5 // mount point is 5th field
		fields := strings.SplitN(txt, " ", mPos+1)
		if len(fields) < mPos+1 {
			continue
		}
		return fields[mPos-1]
	}

	return ""
}
882079
func GetSELinux(path string, mountInfoFilename string) (bool, error) {
	info, err := findMountInfo(path, mountInfoFilename)
	if err != nil {
		return false, err
	}

	// "seclabel" can be both in mount options and super options.
	for _, opt := range info.superOptions {
		if opt == "seclabel" {
			return true, nil
		}
	}
	for _, opt := range info.mountOptions {
		if opt == "seclabel" {
			return true, nil
		}
	}
	return false, nil
}
784867
func checkCrossDeviceMounts(endpoints EndpointList) (err error) {
	var absPaths []string
	for _, endpoint := range endpoints {
		if endpoint.IsLocal {
			var absPath string
			absPath, err = filepath.Abs(endpoint.Path)
			if err != nil {
				return err
			}
			absPaths = append(absPaths, absPath)
		}
	}
	return mountinfo.CheckCrossDevice(absPaths)
}
862434
func (n *NetNs) SymlinkCreate(name string) error {
	if n.netNS == nil {
		return errors.New("no netns set up")
	}
	b := make([]byte, 4)
	_, randErr := rand.Reader.Read(b)
	if randErr != nil {
		return randErr
	}

	nsName := fmt.Sprintf("%s-%x", name, b)
	symlinkPath := filepath.Join(NsRunDir, nsName)

	if err := os.Symlink(n.Path(), symlinkPath); err != nil {
		return err
	}

	fd, err := os.Open(symlinkPath)
	if err != nil {
		if removeErr := os.RemoveAll(symlinkPath); removeErr != nil {
			return removeErr
		}

		return err
	}

	n.symlink = fd

	return nil
}
1085162
func addHostPathMapping(pod *v1.Pod, container *v1.Container, name, path string) *v1.VolumeMount {
	pod.Spec.Volumes = append(pod.Spec.Volumes, v1.Volume{
		Name: name,
		VolumeSource: v1.VolumeSource{
			HostPath: &v1.HostPathVolumeSource{
				Path: path,
			},
		},
	})

	container.VolumeMounts = append(container.VolumeMounts, v1.VolumeMount{
		Name:      name,
		MountPath: path,
		ReadOnly:  true,
	})

	return &container.VolumeMounts[len(container.VolumeMounts)-1]
}
1110584
func forkAndMountat(dirfd uintptr, source, target, fstype, flags, data uintptr) (pid uintptr, errno syscall.Errno) {
	// block signal during clone
	beforeFork()

	// the cloned thread shares the open file descriptor, but the thread
	// never be reused by runtime.
	pid, _, errno = syscall.RawSyscall6(syscall.SYS_CLONE, uintptr(syscall.SIGCHLD)|syscall.CLONE_FILES, 0, 0, 0, 0, 0)
	if errno != 0 || pid != 0 {
		// restore all signals
		afterFork()
		return
	}

	// restore all signals
	afterForkInChild()

	// change working dir
	_, _, errno = syscall.RawSyscall(syscall.SYS_FCHDIR, dirfd, 0, 0)
	if errno != 0 {
		goto childerr
	}
	_, _, errno = syscall.RawSyscall6(syscall.SYS_MOUNT, source, target, fstype, flags, data, 0)

childerr:
	syscall.RawSyscall(syscall.SYS_EXIT, uintptr(errno), 0, 0)
	panic("unreachable")
}
557549
func IsLikelyMountPoint(path string) bool {
	s1, err := os.Lstat(path)
	if err != nil {
		return false
	}

	// A symlink can never be a mount point
	if s1.Mode()&os.ModeSymlink != 0 {
		return false
	}

	s2, err := os.Lstat(filepath.Dir(strings.TrimSuffix(path, "/")))
	if err != nil {
		return false
	}

	// If the directory has a different device as parent, then it is a mountpoint.
	if s1.Sys().(*syscall.Stat_t).Dev != s2.Sys().(*syscall.Stat_t).Dev {
		//  path/.. on a different device as path
		return true
	}

	// path/.. is the same i-node as path - this check is for bind mounts.
	return s1.Sys().(*syscall.Stat_t).Ino == s2.Sys().(*syscall.Stat_t).Ino
}