本文整理汇总了Golang中os.Chown函数的典型用法代码示例。如果您正苦于以下问题:Golang Chown函数的具体用法?Golang Chown怎么用?Golang Chown使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Chown函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: updatePerms
func updatePerms(dirPath, mockPath string) {
if knf.GetS(ACCESS_USER) != "" || knf.GetS(ACCESS_GROUP) != "" {
dirOwnerUID, dirOwnerGID, _ := fsutil.GetOwner(dirPath)
mockOwnerUID, mockOwnerGID, _ := fsutil.GetOwner(mockPath)
if knf.GetS(ACCESS_USER) != "" {
userInfo, err := system.LookupUser(knf.GetS(ACCESS_USER))
if err == nil {
dirOwnerUID = userInfo.UID
mockOwnerUID = userInfo.UID
}
}
if knf.GetS(ACCESS_GROUP) != "" {
groupInfo, err := system.LookupGroup(knf.GetS(ACCESS_GROUP))
if err == nil {
dirOwnerGID = groupInfo.GID
mockOwnerGID = groupInfo.GID
}
}
os.Chown(dirPath, dirOwnerUID, dirOwnerGID)
os.Chown(mockPath, mockOwnerUID, mockOwnerGID)
}
os.Chmod(dirPath, knf.GetM(ACCESS_MOCK_DIR_PERMS))
os.Chmod(mockPath, knf.GetM(ACCESS_MOCK_PERMS))
}
示例2: ExtractFileFromTar
func ExtractFileFromTar(hdr *tar.Header, r io.Reader) os.Error {
if hdr.Typeflag == tar.TypeDir {
e := os.Mkdir("./"+hdr.Name, uint32(hdr.Mode))
if e != nil {
return e
}
e = os.Chown("./"+hdr.Name, int(hdr.Uid), int(hdr.Gid))
return e
} else {
f, e := os.Open("./"+hdr.Name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, uint32(hdr.Mode))
if e != nil {
return e
}
defer f.Close()
_ = os.Chown("./"+hdr.Name, int(hdr.Uid), int(hdr.Gid))
_, e = io.Copy(f, r)
if e != nil {
return e
}
return nil
}
return nil // Never reached
}
示例3: TestUidshift
func TestUidshift(t *testing.T) {
if os.Getuid() != 0 {
t.Fatal("Tests needs to be run as root")
}
idmap := fuidshift.IdmapSet{}
idmap, err := idmap.Append("b:0:100000:65536")
ok(t, err)
tempdir, err := ioutil.TempDir(os.TempDir(), "fuidshift")
ok(t, err)
defer os.Remove(tempdir)
dir := path.Join(tempdir, "dir")
ok(t, os.Mkdir(dir, 0700))
ok(t, os.Chown(dir, 1, 1))
file := path.Join(tempdir, "file")
ok(t, ioutil.WriteFile(file, []byte("hello\ngo\n"), 0700))
ok(t, os.Chown(file, 0, 0))
ok(t, idmap.UidshiftIntoContainer(tempdir, false))
assertOwnership(t, dir, 100001, 100001)
assertOwnership(t, file, 100000, 100000)
ok(t, idmap.UidshiftFromContainer(tempdir, false))
assertOwnership(t, dir, 1, 1)
assertOwnership(t, file, 0, 0)
}
示例4: Create
func (d *Driver) Create() error {
b2dutils := mcnutils.NewB2dUtils(d.StorePath)
if err := b2dutils.CopyIsoToMachineDir(d.Boot2DockerURL, d.MachineName); err != nil {
return err
}
log.Infof("Creating VM...")
if err := os.MkdirAll(d.ResolveStorePath("."), 0755); err != nil {
return err
}
log.Infof("Extracting vmlinuz64 and initrd.img from %s...", isoFilename)
if err := d.extractKernelImages(); err != nil {
return err
}
log.Infof("Generating %dMB disk image...", d.DiskSize)
if err := d.generateDiskImage(d.DiskSize); err != nil {
return err
}
// Fix file permission root to current user for vmnet.framework
log.Infof("Fix file permission...")
os.Chown(d.ResolveStorePath("."), syscall.Getuid(), syscall.Getegid())
files, _ := ioutil.ReadDir(d.ResolveStorePath("."))
for _, f := range files {
log.Debugf(d.ResolveStorePath(f.Name()))
os.Chown(d.ResolveStorePath(f.Name()), syscall.Getuid(), syscall.Getegid())
}
log.Infof("Generate UUID...")
d.UUID = uuidgen()
log.Debugf("Generated UUID: %s", d.UUID)
log.Infof("Convert UUID to MAC address...")
rawUUID, err := d.getMACAdress()
if err != nil {
return err
}
d.MacAddr = trimMacAddress(rawUUID)
log.Debugf("Converted MAC address: %s", d.MacAddr)
log.Infof("Starting %s...", d.MachineName)
if err := d.Start(); err != nil {
return err
}
// Setup NFS sharing
if d.NFSShare {
log.Infof("NFS share folder must be root. Please insert root password.")
err = d.setupNFSShare()
if err != nil {
log.Errorf("NFS setup failed: %s", err.Error())
}
}
return nil
}
示例5: PrepareDocker
/* User Methods */
func (user *User) PrepareDocker() bool {
// Mkdir user.HomePath
os.Mkdir(user.HomePath, 0750)
// Chown syncthing:users
os.Chown(user.HomePath, st_uid, st_gid)
// ReplaceConfigXML user.HomePath/config.xml user.Name
ReplaceConfigXML(originconfigxml, user.HomePath+"/config.xml", user.Name, user.Password, strconv.Itoa(user.GuiPort), strconv.Itoa(user.ListenPort))
// Chown file
os.Chown(user.HomePath+"/config.xml", st_uid, st_gid)
return true
}
示例6: Create
func (l *LinuxFactory) Create(id string, config *configs.Config) (Container, error) {
if l.Root == "" {
return nil, newGenericError(fmt.Errorf("invalid root"), ConfigInvalid)
}
if err := l.validateID(id); err != nil {
return nil, err
}
if err := l.Validator.Validate(config); err != nil {
return nil, newGenericError(err, ConfigInvalid)
}
uid, err := config.HostUID()
if err != nil {
return nil, newGenericError(err, SystemError)
}
gid, err := config.HostGID()
if err != nil {
return nil, newGenericError(err, SystemError)
}
containerRoot := filepath.Join(l.Root, id)
if _, err := os.Stat(containerRoot); err == nil {
return nil, newGenericError(fmt.Errorf("container with id exists: %v", id), IdInUse)
} else if !os.IsNotExist(err) {
return nil, newGenericError(err, SystemError)
}
if err := os.MkdirAll(containerRoot, 0711); err != nil {
return nil, newGenericError(err, SystemError)
}
if err := os.Chown(containerRoot, uid, gid); err != nil {
return nil, newGenericError(err, SystemError)
}
fifoName := filepath.Join(containerRoot, execFifoFilename)
oldMask := syscall.Umask(0000)
if err := syscall.Mkfifo(fifoName, 0622); err != nil {
syscall.Umask(oldMask)
return nil, newGenericError(err, SystemError)
}
syscall.Umask(oldMask)
if err := os.Chown(fifoName, uid, gid); err != nil {
return nil, newGenericError(err, SystemError)
}
c := &linuxContainer{
id: id,
root: containerRoot,
config: config,
initPath: l.InitPath,
initArgs: l.InitArgs,
criuPath: l.CriuPath,
cgroupManager: l.NewCgroupsManager(config.Cgroups, nil),
}
c.state = &stoppedState{c: c}
return c, nil
}
示例7: mkdirAs
func mkdirAs(path string, mode os.FileMode, ownerUID, ownerGID int, mkAll, chownExisting bool) error {
// make an array containing the original path asked for, plus (for mkAll == true)
// all path components leading up to the complete path that don't exist before we MkdirAll
// so that we can chown all of them properly at the end. If chownExisting is false, we won't
// chown the full directory path if it exists
var paths []string
if _, err := os.Stat(path); err != nil && os.IsNotExist(err) {
paths = []string{path}
} else if err == nil && chownExisting {
if err := os.Chown(path, ownerUID, ownerGID); err != nil {
return err
}
// short-circuit--we were called with an existing directory and chown was requested
return nil
} else if err == nil {
// nothing to do; directory path fully exists already and chown was NOT requested
return nil
}
if mkAll {
// walk back to "/" looking for directories which do not exist
// and add them to the paths array for chown after creation
dirPath := path
for {
dirPath = filepath.Dir(dirPath)
if dirPath == "/" {
break
}
if _, err := os.Stat(dirPath); err != nil && os.IsNotExist(err) {
paths = append(paths, dirPath)
}
}
if err := system.MkdirAll(path, mode); err != nil && !os.IsExist(err) {
return err
}
} else {
if err := os.Mkdir(path, mode); err != nil && !os.IsExist(err) {
return err
}
}
// even if it existed, we will chown the requested path + any subpaths that
// didn't exist when we called MkdirAll
for _, pathComponent := range paths {
if err := os.Chown(pathComponent, ownerUID, ownerGID); err != nil {
return err
}
}
return nil
}
示例8: Execute
// Execute ChownJob.
func (job *ChownJob) Execute() {
defer job.finalize()
// -1 means not change.
uid := -1
gid := -1
if job.owner != "" {
newUser, err := user.Lookup(job.owner)
if err != nil {
job.setError(err)
return
}
uid, _ = strconv.Atoi(newUser.Uid)
}
if job.group != "" {
cGroupName := C.CString(job.group)
defer C.free(unsafe.Pointer(cGroupName))
group := C.getgrnam(cGroupName)
if group == nil {
job.setError(errors.New("no such a group"))
return
}
gid = int(group.gr_gid)
}
job.setError(os.Chown(job.file.GetPath(), uid, gid))
}
示例9: TestChmod
func TestChmod(t *testing.T) {
wd, clean := setupUfs(t)
defer clean()
ro_fn := wd + "/ro/file"
m_fn := wd + "/mount/file"
writeToFile(ro_fn, "a")
err := os.Chmod(m_fn, 07070)
CheckSuccess(err)
err = os.Chown(m_fn, 0, 0)
code := fuse.OsErrorToErrno(err)
if code != fuse.EPERM {
t.Error("Unexpected error code", code, err)
}
fi, err := os.Lstat(m_fn)
CheckSuccess(err)
if fi.Mode&07777 != 07272 {
t.Errorf("Unexpected mode found: %o", fi.Mode)
}
_, err = os.Lstat(wd + "/rw/file")
if err != nil {
t.Errorf("File not promoted")
}
}
示例10: Setup
// Setup initializes the proper /dev/console inside the rootfs path
func Setup(rootfs, consolePath, mountLabel string) error {
oldMask := system.Umask(0000)
defer system.Umask(oldMask)
if err := os.Chmod(consolePath, 0600); err != nil {
return err
}
if err := os.Chown(consolePath, 0, 0); err != nil {
return err
}
if err := label.SetFileLabel(consolePath, mountLabel); err != nil {
return fmt.Errorf("set file label %s %s", consolePath, err)
}
dest := filepath.Join(rootfs, "dev/console")
f, err := os.Create(dest)
if err != nil && !os.IsExist(err) {
return fmt.Errorf("create %s %s", dest, err)
}
if f != nil {
f.Close()
}
if err := system.Mount(consolePath, dest, "bind", syscall.MS_BIND, ""); err != nil {
return fmt.Errorf("bind %s to %s %s", consolePath, dest, err)
}
return nil
}
示例11: UnixAudienceListener
func UnixAudienceListener(sockaddr string, sockmode os.FileMode, sockuid int, sockgid int) {
fi, err := os.Stat(sockaddr)
if err == nil {
if (fi.Mode() & os.ModeSocket) != 0 {
os.Remove(sockaddr)
} else {
o.Fail("%s exists and is not a socket", sockaddr)
}
}
err = os.MkdirAll(path.Dir(sockaddr), 0755)
o.MightFail(err, "Couldn't create socket directory")
laddr, err := net.ResolveUnixAddr("unix", sockaddr)
o.MightFail(err, "Couldn't resolve audience socket address")
old_umask := syscall.Umask(0777)
defer syscall.Umask(old_umask)
l, err := net.ListenUnix("unix", laddr)
o.MightFail(err, "Couldn't start audience unixsock listener")
if sockuid >= 0 || sockgid >= 0 {
err = os.Chown(sockaddr, sockuid, sockgid)
o.MightFail(err, "Couldn't chown audience unixsock listener")
}
err = os.Chmod(sockaddr, sockmode)
o.MightFail(err, "Couldn't chmod audience unixsock listener")
// make sure we clean up the unix socket when we die.
defer l.Close()
defer os.Remove(sockaddr)
AudienceListener(l)
}
示例12: setupConsole
// setupConsole ensures that the container has a proper /dev/console setup
func setupConsole(rootfs, console string) error {
oldMask := system.Umask(0000)
defer system.Umask(oldMask)
stat, err := os.Stat(console)
if err != nil {
return fmt.Errorf("stat console %s %s", console, err)
}
var (
st = stat.Sys().(*syscall.Stat_t)
dest = filepath.Join(rootfs, "dev/console")
)
if err := os.Remove(dest); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("remove %s %s", dest, err)
}
if err := os.Chmod(console, 0600); err != nil {
return err
}
if err := os.Chown(console, 0, 0); err != nil {
return err
}
if err := system.Mknod(dest, (st.Mode&^07777)|0600, int(st.Rdev)); err != nil {
return fmt.Errorf("mknod %s %s", dest, err)
}
if err := system.Mount(console, dest, "bind", syscall.MS_BIND, ""); err != nil {
return fmt.Errorf("bind %s to %s %s", console, dest, err)
}
return nil
}
示例13: CopyIsoToMachineDir
func (d *Driver) CopyIsoToMachineDir(isoURL, machineName string) error {
b2d := b2d.NewB2dUtils(d.StorePath)
mcnutils := mcnutils.NewB2dUtils(d.StorePath)
if err := d.UpdateISOCache(isoURL); err != nil {
return err
}
isoPath := filepath.Join(b2d.ImgCachePath, isoFilename)
if isoStat, err := os.Stat(isoPath); err == nil {
if int(isoStat.Sys().(*syscall.Stat_t).Uid) == 0 {
log.Debugf("Fix %s file permission...", isoStat.Name())
os.Chown(isoPath, syscall.Getuid(), syscall.Getegid())
}
}
// TODO: This is a bit off-color.
machineDir := filepath.Join(d.StorePath, "machines", machineName)
machineIsoPath := filepath.Join(machineDir, isoFilename)
// By default just copy the existing "cached" iso to the machine's directory...
defaultISO := filepath.Join(b2d.ImgCachePath, defaultISOFilename)
if isoURL == "" {
log.Infof("Copying %s to %s...", defaultISO, machineIsoPath)
return CopyFile(defaultISO, machineIsoPath)
}
// if ISO is specified, check if it matches a github releases url or fallback to a direct download
downloadURL, err := b2d.GetReleaseURL(isoURL)
if err != nil {
return err
}
return mcnutils.DownloadISO(machineDir, b2d.Filename(), downloadURL)
}
示例14: createBase
func createBase(t *testing.T, driver graphdriver.Driver, name string) {
// We need to be able to set any perms
oldmask := syscall.Umask(0)
defer syscall.Umask(oldmask)
if err := driver.Create(name, ""); err != nil {
t.Fatal(err)
}
dir, err := driver.Get(name, "")
if err != nil {
t.Fatal(err)
}
defer driver.Put(name)
subdir := path.Join(dir, "a subdir")
if err := os.Mkdir(subdir, 0705|os.ModeSticky); err != nil {
t.Fatal(err)
}
if err := os.Chown(subdir, 1, 2); err != nil {
t.Fatal(err)
}
file := path.Join(dir, "a file")
if err := ioutil.WriteFile(file, []byte("Some data"), 0222|os.ModeSetuid); err != nil {
t.Fatal(err)
}
}
示例15: setupMounts
// setupMounts iterates through each of the mount points for a container and
// calls Setup() on each. It also looks to see if is a network mount such as
// /etc/resolv.conf, and if it is not, appends it to the array of mounts.
func (container *Container) setupMounts() ([]execdriver.Mount, error) {
var mounts []execdriver.Mount
for _, m := range container.MountPoints {
path, err := m.Setup()
if err != nil {
return nil, err
}
if !container.trySetNetworkMount(m.Destination, path) {
mounts = append(mounts, execdriver.Mount{
Source: path,
Destination: m.Destination,
Writable: m.RW,
})
}
}
mounts = sortMounts(mounts)
netMounts := container.networkMounts()
// if we are going to mount any of the network files from container
// metadata, the ownership must be set properly for potential container
// remapped root (user namespaces)
rootUID, rootGID := container.daemon.GetRemappedUIDGID()
for _, mount := range netMounts {
if err := os.Chown(mount.Source, rootUID, rootGID); err != nil {
return nil, err
}
}
return append(mounts, netMounts...), nil
}