// Check root rights to use system service
350216
func checkPrivileges() (bool, error) {

	if output, err := exec.Command("id", "-g").Output(); err == nil {
		if gid, parseErr := strconv.ParseUint(strings.TrimSpace(string(output)), 10, 32); parseErr == nil {
			if gid == 0 {
				return true, nil
			}
			return false, ErrRootPrivileges
		}
	}
	return false, ErrUnsupportedSystem
}
640735
func (zk *zkf) GetServiceStateIDs(poolID, serviceID string) ([]zks.StateRequest, error) {
	logger := plog.WithFields(log.Fields{
		"poolid":    poolID,
		"serviceid": serviceID,
	})

	// get the root-based connection to look up the state ids for a service
	conn, err := zzk.GetLocalConnection("/")
	if err != nil {
		logger.WithError(err).Debug("Could not acquire root-based connection")
		return nil, err
	}

	return zks.GetServiceStateIDs(conn, poolID, serviceID)
}
652110
func RootCause(e error) error {
	if e == nil {
		return e
	}
	for {
		c := Cause(e)
		if c == nil {
			break
		} else {
			e = c
		}
	}
	return e
}
159576
func (d *Daemon) CheckServiceTasks(service string) func(*check.C) (interface{}, check.CommentInterface) {
	return func(c *check.C) (interface{}, check.CommentInterface) {
		tasks := d.GetServiceTasks(c, service)
		return len(tasks), nil
	}
}
757971
func checkHostNs(sysctlConfig string, path string) error {
	var currentProcessNetns = "/proc/self/ns/net"
	// readlink on the current processes network namespace
	destOfCurrentProcess, err := os.Readlink(currentProcessNetns)
	if err != nil {
		return fmt.Errorf("read soft link %q error", currentProcessNetns)
	}

	// First check if the provided path is a symbolic link
	symLink, err := isSymbolicLink(path)
	if err != nil {
		return fmt.Errorf("could not check that %q is a symlink: %v", path, err)
	}

	if symLink == false {
		// The provided namespace is not a symbolic link,
		// it is not the host namespace.
		return nil
	}

	// readlink on the path provided in the struct
	destOfContainer, err := os.Readlink(path)
	if err != nil {
		return fmt.Errorf("read soft link %q error", path)
	}
	if destOfContainer == destOfCurrentProcess {
		return fmt.Errorf("sysctl %q is not allowed in the hosts network namespace", sysctlConfig)
	}
	return nil
}
118381
func (c *aclCheckerV1) getPermissions(p string, username *string) (
	permissions permissionsV1, max permissionsV1, effectivePath string) {
	// This is only called on the root aclCheckerV1, and c.ac is always
	// populated here. So even if no other path shows up in the ACLs, any path
	// will get root's *accessControlV1 as the last resort.
	ac := c.getAccessControl(nil, p)
	permissions = ac.anonymous
	if ac.whitelistAdditional == nil || username == nil {
		return permissions, ac.maxPermission, ac.p
	}
	if perms, ok := ac.whitelistAdditional[*username]; ok {
		permissions.read = perms.read || permissions.read
		permissions.list = perms.list || permissions.list
	}
	return permissions, ac.maxPermission, ac.p
}
1152018
func (o *Options) CheckPermissions() error {
	// get the directory the file exists in
	path, err := o.getPath()
	if err != nil {
		return err
	}

	fileDir := filepath.Dir(path)
	fileName := filepath.Base(path)

	// attempt to open a file in the file's directory
	newPath := filepath.Join(fileDir, fmt.Sprintf(".%s.new", fileName))
	fp, err := openFile(newPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, o.TargetMode)
	if err != nil {
		return err
	}
	fp.Close()

	_ = os.Remove(newPath)
	return nil
}
356272
func (m *MergeQuest) Root(c context.Context) *ds.Key {
	return model.QuestKeyFromID(c, m.Quest.ID)
}
392991
func (a *ActivateExecution) Root(c context.Context) *datastore.Key {
	return model.AttemptKeyFromID(c, a.Auth.Id.AttemptID())
}
1033985
func checkAdminServiceStopSyntax(ctx *cli.Context) {
	if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
		cli.ShowCommandHelpAndExit(ctx, "stop", 1) // last argument is exit code
	}
}
829768
func (a *Account) GatewayRights(gatewayID string) (rights []types.Right, err error) {
	err = a.get(a.auth.WithScope(scope.Gateway(gatewayID)), fmt.Sprintf("/api/v2/gateways/%s/rights", gatewayID), &rights)
	if err != nil {
		return nil, err
	}

	return rights, nil
}
1284801
func (cfg *dynamicTLSConfig) Roots() *x509.CertPool {
	cfg.RLock()
	defer cfg.RUnlock()
	return cfg.roots
}
82765
func (r *RecordCompletion) Root(c context.Context) *ds.Key {
	return ds.KeyForObj(c, &model.BackDepGroup{Dependee: *r.For})
}
541718
func (k *KeybaseServiceBase) VerifyMerkleRoot(
	ctx context.Context, root keybase1.MerkleRootV2,
	kbfsRoot keybase1.KBFSRoot) error {
	return k.merkleClient.VerifyMerkleRootAndKBFS(ctx,
		keybase1.VerifyMerkleRootAndKBFSArg{
			Root:             root,
			ExpectedKBFSRoot: kbfsRoot,
		})
}
765749
func (a *Account) GrantRouterRights(routerID, username string, rights []types.Right) error {
	return a.GrantComponentRights("router", routerID, username, rights)
}
536632
func (v *Validator) CheckLinux() (errs error) {
	logrus.Debugf("check linux")

	if v.spec.Linux == nil {
		return
	}

	var nsTypeList = map[rspec.LinuxNamespaceType]struct {
		num      int
		newExist bool
	}{
		rspec.PIDNamespace:     {0, false},
		rspec.NetworkNamespace: {0, false},
		rspec.MountNamespace:   {0, false},
		rspec.IPCNamespace:     {0, false},
		rspec.UTSNamespace:     {0, false},
		rspec.UserNamespace:    {0, false},
		rspec.CgroupNamespace:  {0, false},
	}

	for index := 0; index < len(v.spec.Linux.Namespaces); index++ {
		ns := v.spec.Linux.Namespaces[index]
		if ns.Path != "" && !osFilepath.IsAbs(v.platform, ns.Path) {
			errs = multierror.Append(errs, specerror.NewError(specerror.NSPathAbs, fmt.Errorf("namespace.path %q is not an absolute path", ns.Path), rspec.Version))
		}

		tmpItem := nsTypeList[ns.Type]
		tmpItem.num = tmpItem.num + 1
		if tmpItem.num > 1 {
			errs = multierror.Append(errs, specerror.NewError(specerror.NSErrorOnDup, fmt.Errorf("duplicated namespace %q", ns.Type), rspec.Version))
		}

		if len(ns.Path) == 0 {
			tmpItem.newExist = true
		}
		nsTypeList[ns.Type] = tmpItem
	}

	if (len(v.spec.Linux.UIDMappings) > 0 || len(v.spec.Linux.GIDMappings) > 0) && !nsTypeList[rspec.UserNamespace].newExist {
		errs = multierror.Append(errs, errors.New("the UID/GID mappings requires a new User namespace to be specified as well"))
	}

	for k := range v.spec.Linux.Sysctl {
		if strings.HasPrefix(k, "net.") && !nsTypeList[rspec.NetworkNamespace].newExist {
			errs = multierror.Append(errs, fmt.Errorf("sysctl %v requires a new Network namespace to be specified as well", k))
		}
		if strings.HasPrefix(k, "fs.mqueue.") {
			if !nsTypeList[rspec.MountNamespace].newExist || !nsTypeList[rspec.IPCNamespace].newExist {
				errs = multierror.Append(errs, fmt.Errorf("sysctl %v requires a new IPC namespace and Mount namespace to be specified as well", k))
			}
		}
	}

	if v.platform == "linux" && !nsTypeList[rspec.UTSNamespace].newExist && v.spec.Hostname != "" {
		errs = multierror.Append(errs, fmt.Errorf("on Linux, hostname requires a new UTS namespace to be specified as well"))
	}

	// Linux devices validation
	devList := make(map[string]bool)
	devTypeList := make(map[string]bool)
	for index := 0; index < len(v.spec.Linux.Devices); index++ {
		device := v.spec.Linux.Devices[index]
		if !deviceValid(device) {
			errs = multierror.Append(errs, fmt.Errorf("device %v is invalid", device))
		}

		if _, exists := devList[device.Path]; exists {
			errs = multierror.Append(errs, fmt.Errorf("device %s is duplicated", device.Path))
		} else {
			var rootfsPath string
			if filepath.IsAbs(v.spec.Root.Path) {
				rootfsPath = v.spec.Root.Path
			} else {
				rootfsPath = filepath.Join(v.bundlePath, v.spec.Root.Path)
			}
			absPath := filepath.Join(rootfsPath, device.Path)
			fi, err := os.Stat(absPath)
			if os.IsNotExist(err) {
				devList[device.Path] = true
			} else if err != nil {
				errs = multierror.Append(errs, err)
			} else {
				fStat, ok := fi.Sys().(*syscall.Stat_t)
				if !ok {
					errs = multierror.Append(errs, specerror.NewError(specerror.DevicesAvailable,
						fmt.Errorf("cannot determine state for device %s", device.Path), rspec.Version))
					continue
				}
				var devType string
				switch fStat.Mode & syscall.S_IFMT {
				case syscall.S_IFCHR:
					devType = "c"
				case syscall.S_IFBLK:
					devType = "b"
				case syscall.S_IFIFO:
					devType = "p"
				default:
					devType = "unmatched"
				}
				if devType != device.Type || (devType == "c" && device.Type == "u") {
					errs = multierror.Append(errs, specerror.NewError(specerror.DevicesFileNotMatch,
						fmt.Errorf("unmatched %s already exists in filesystem", device.Path), rspec.Version))
					continue
				}
				if devType != "p" {
					dev := fStat.Rdev
					major := (dev >> 8) & 0xfff
					minor := (dev & 0xff) | ((dev >> 12) & 0xfff00)
					if int64(major) != device.Major || int64(minor) != device.Minor {
						errs = multierror.Append(errs, specerror.NewError(specerror.DevicesFileNotMatch,
							fmt.Errorf("unmatched %s already exists in filesystem", device.Path), rspec.Version))
						continue
					}
				}
				if device.FileMode != nil {
					expectedPerm := *device.FileMode & os.ModePerm
					actualPerm := fi.Mode() & os.ModePerm
					if expectedPerm != actualPerm {
						errs = multierror.Append(errs, specerror.NewError(specerror.DevicesFileNotMatch,
							fmt.Errorf("unmatched %s already exists in filesystem", device.Path), rspec.Version))
						continue
					}
				}
				if device.UID != nil {
					if *device.UID != fStat.Uid {
						errs = multierror.Append(errs, specerror.NewError(specerror.DevicesFileNotMatch,
							fmt.Errorf("unmatched %s already exists in filesystem", device.Path), rspec.Version))
						continue
					}
				}
				if device.GID != nil {
					if *device.GID != fStat.Gid {
						errs = multierror.Append(errs, specerror.NewError(specerror.DevicesFileNotMatch,
							fmt.Errorf("unmatched %s already exists in filesystem", device.Path), rspec.Version))
						continue
					}
				}
			}
		}

		// unify u->c when comparing, they are synonyms
		var devID string
		if device.Type == "u" {
			devID = fmt.Sprintf("%s:%d:%d", "c", device.Major, device.Minor)
		} else {
			devID = fmt.Sprintf("%s:%d:%d", device.Type, device.Major, device.Minor)
		}

		if _, exists := devTypeList[devID]; exists {
			logrus.Warnf("%v", specerror.NewError(specerror.DevicesErrorOnDup, fmt.Errorf("type:%s, major:%d and minor:%d for linux devices is duplicated", device.Type, device.Major, device.Minor), rspec.Version))
		} else {
			devTypeList[devID] = true
		}
	}

	if v.spec.Linux.Resources != nil {
		errs = multierror.Append(errs, v.CheckLinuxResources())
	}

	for _, maskedPath := range v.spec.Linux.MaskedPaths {
		if !strings.HasPrefix(maskedPath, "/") {
			errs = multierror.Append(errs,
				specerror.NewError(
					specerror.MaskedPathsAbs,
					fmt.Errorf("maskedPath %v is not an absolute path", maskedPath),
					rspec.Version))
		}
	}

	for _, readonlyPath := range v.spec.Linux.ReadonlyPaths {
		if !strings.HasPrefix(readonlyPath, "/") {
			errs = multierror.Append(errs,
				specerror.NewError(
					specerror.ReadonlyPathsAbs,
					fmt.Errorf("readonlyPath %v is not an absolute path", readonlyPath),
					rspec.Version))
		}
	}

	if v.spec.Linux.MountLabel != "" {
		if err := label.Validate(v.spec.Linux.MountLabel); err != nil {
			errs = multierror.Append(errs, fmt.Errorf("mountLabel %v is invalid", v.spec.Linux.MountLabel))
		}
	}

	return
}
579110
func (e *EnsureQuestAttempts) Root(c context.Context) *datastore.Key {
	return model.QuestKeyFromID(c, e.Quest.ID)
}