Example #1
2
// permToACL - convert perm to meaningful ACL
func permToACL(mode os.FileMode) BucketACL {
	switch mode.Perm() {
	case os.FileMode(0700):
		return BucketACL("private")
	case os.FileMode(0500):
		return BucketACL("public-read")
	case os.FileMode(0777):
		return BucketACL("public-read-write")
	default:
		return BucketACL("private")
	}
}
Example #2
0
File: copy.go Project: juju/utils
func copyDir(src, dst string, mode os.FileMode) error {
	srcf, err := os.Open(src)
	if err != nil {
		return err
	}
	defer srcf.Close()
	if mode&0500 == 0 {
		// The source directory doesn't have write permission,
		// so give the new directory write permission anyway
		// so that we have permission to create its contents.
		// We'll make the permissions match at the end.
		mode |= 0500
	}
	if err := os.Mkdir(dst, mode.Perm()); err != nil {
		return err
	}
	for {
		names, err := srcf.Readdirnames(100)
		for _, name := range names {
			if err := Copy(filepath.Join(src, name), filepath.Join(dst, name)); err != nil {
				return err
			}
		}
		if err == io.EOF {
			break
		}
		if err != nil {
			return fmt.Errorf("error reading directory %q: %v", src, err)
		}
	}
	if err := os.Chmod(dst, mode.Perm()); err != nil {
		return err
	}
	return nil
}
Example #3
0
File: p9.go Project: flynn/bake
// mode converts an os.FileMode to a go9p mode.
func mode(m os.FileMode, dotu bool) uint32 {
	other := uint32(m & 0777)
	if m.IsDir() {
		other |= go9p.DMDIR
	}

	if !dotu {
		return other
	}

	if m&os.ModeSymlink != 0 {
		other |= go9p.DMSYMLINK
	}
	if m&os.ModeSocket != 0 {
		other |= go9p.DMSOCKET
	}
	if m&os.ModeNamedPipe != 0 {
		other |= go9p.DMNAMEDPIPE
	}
	if m&os.ModeDevice != 0 {
		other |= go9p.DMDEVICE
	}
	if m&os.ModeSetuid != 0 {
		other |= go9p.DMSETUID
	}
	if m&os.ModeSetgid != 0 {
		other |= go9p.DMSETGID
	}

	return other
}
Example #4
0
func visit(path string, f os.FileInfo, err error) error {

	var fMod os.FileMode
	fMod = f.Mode()
	if fMod.IsDir() {
		fmt.Printf("Entering Folder: %s\n", f.Name())
		return nil
	}
	fmt.Printf("Saving log: %s\n", path)
	file, err := os.Open(path)
	if err != nil {
		fmt.Printf("trouble opening file: %s\n", err)
		return nil
	}

	b := make([]byte, f.Size())
	n, err := file.Read(b)

	if int64(n) != f.Size() {
		fmt.Printf("Error reading entire file: %s\n", err)
	}
	var finalkey = KEY_PREFIX + f.Name()
	var kmsg KafkaMsg = KafkaMsg{
		Topic: FolderTopic,
		Key:   finalkey,
		Value: string(b),
	}

	sendMsg(kmsg)

	return nil
}
Example #5
0
func (nd *Node) Chmod(newMode os.FileMode) error {
	if nd.Size() > 0 && newMode.IsDir() {
		return errors.New("File has size, cannot change to directory")
	}
	nd.mode = newMode
	return nd.save()
}
Example #6
0
// put single file
func put(args []string) error {
	fs := flag.NewFlagSet("put", flag.ContinueOnError)
	fs.Usage = func() {
		fmt.Fprintln(os.Stderr, "create usage: gomote put [put-opts] <buildlet-name> <source or '-' for stdin> [destination]")
		fs.PrintDefaults()
		os.Exit(1)
	}
	modeStr := fs.String("mode", "", "Unix file mode (octal); default to source file mode")
	fs.Parse(args)
	if n := fs.NArg(); n < 2 || n > 3 {
		fs.Usage()
	}

	bc, err := namedClient(fs.Arg(0))
	if err != nil {
		return err
	}

	var r io.Reader = os.Stdin
	var mode os.FileMode = 0666

	src := fs.Arg(1)
	if src != "-" {
		f, err := os.Open(src)
		if err != nil {
			return err
		}
		defer f.Close()
		r = f

		if *modeStr == "" {
			fi, err := f.Stat()
			if err != nil {
				return err
			}
			mode = fi.Mode()
		}
	}
	if *modeStr != "" {
		modeInt, err := strconv.ParseInt(*modeStr, 8, 64)
		if err != nil {
			return err
		}
		mode = os.FileMode(modeInt)
		if !mode.IsRegular() {
			return fmt.Errorf("bad mode: %v", mode)
		}
	}

	dest := fs.Arg(2)
	if dest == "" {
		if src == "-" {
			return errors.New("must specify destination file name when source is standard input")
		}
		dest = filepath.Base(src)
	}

	return bc.Put(r, dest, mode)
}
Example #7
0
func (fs *memFS) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
	fs.mu.Lock()
	defer fs.mu.Unlock()

	dir, frag, err := fs.find("open", name)
	if err != nil {
		return nil, err
	}
	var n *memFSNode
	if dir == nil {
		// We're opening the root.
		if flag&(os.O_WRONLY|os.O_RDWR) != 0 {
			return nil, os.ErrPermission
		}
		n, frag = &fs.root, "/"

	} else {
		n = dir.children[frag]
		if flag&(os.O_SYNC|os.O_APPEND) != 0 {
			// memFile doesn't support these flags yet.
			return nil, os.ErrInvalid
		}
		if flag&os.O_CREATE != 0 {
			if flag&os.O_EXCL != 0 && n != nil {
				return nil, os.ErrExist
			}
			if n == nil {
				n = &memFSNode{
					mode: perm.Perm(),
				}
				dir.children[frag] = n
			}
		}
		if n == nil {
			return nil, os.ErrNotExist
		}
		if flag&(os.O_WRONLY|os.O_RDWR) != 0 && flag&os.O_TRUNC != 0 {
			n.mu.Lock()
			n.data = nil
			n.mu.Unlock()
		}
	}

	children := make([]os.FileInfo, 0, len(n.children))
	for cName, c := range n.children {
		children = append(children, c.stat(cName))
	}
	return &memFile{
		n:                n,
		nameSnapshot:     frag,
		childrenSnapshot: children,
	}, nil
}
Example #8
0
func (pb *Packbuilder) WriteToFile(name string, mode os.FileMode) error {
	cname := C.CString(name)
	defer C.free(unsafe.Pointer(cname))

	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	ret := C.git_packbuilder_write(pb.ptr, cname, C.uint(mode.Perm()), nil, nil)
	if ret != 0 {
		return MakeGitError(ret)
	}
	return nil
}
Example #9
0
File: main.go Project: matomesc/rkt
func categorizeEntry(path string, mode os.FileMode, list *filelist.Lists) error {
	switch {
	case mode.IsDir():
		list.Dirs = append(list.Dirs, path)
	case mode.IsRegular():
		list.Files = append(list.Files, path)
	case isSymlink(mode):
		list.Symlinks = append(list.Symlinks, path)
	default:
		return fmt.Errorf("unsupported file mode: %d (not a file, directory or symlink)", mode&os.ModeType)
	}
	return nil
}
Example #10
0
// posixMode() returns the posix specific  mode bits from Go's portable mode bits
//
// Copied from the syscallMode() function in file_posix.go in the Go source
func posixMode(i os.FileMode) (o uint32) {
	o |= uint32(i.Perm())
	if i&os.ModeSetuid != 0 {
		o |= syscall.S_ISUID
	}
	if i&os.ModeSetgid != 0 {
		o |= syscall.S_ISGID
	}
	if i&os.ModeSticky != 0 {
		o |= syscall.S_ISVTX
	}
	return
}
Example #11
0
// https://github.com/jnwhiteh/golang/blob/master/src/pkg/os/file_posix.go#L61
func syscallMode(i os.FileMode) (o uint32) {
	o |= uint32(i.Perm())
	if i&os.ModeSetuid != 0 {
		o |= syscall.S_ISUID
	}
	if i&os.ModeSetgid != 0 {
		o |= syscall.S_ISGID
	}
	if i&os.ModeSticky != 0 {
		o |= syscall.S_ISVTX
	}
	// No mapping for Go's ModeTemporary (plan9 only).
	return
}
Example #12
0
// Given a FileMode from the os package, get it's permission bits
func FileMode(fm os.FileMode) PermissionBits {
	perm := PermissionBits(fm.Perm())

	if fm&os.ModeSetuid != 0 {
		perm.SetSetuid(true)
	}
	if fm&os.ModeSetgid != 0 {
		perm.SetSetgid(true)
	}
	if fm&os.ModeSticky != 0 {
		perm.SetSticky(true)
	}
	return perm
}
Example #13
0
func (fs *memFS) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
	var ret *memFile
	err := fs.walk("open", name, func(dir *memFSNode, frag string, final bool) error {
		if !final {
			return nil
		}
		if frag == "" {
			return os.ErrInvalid
		}
		if flag&(os.O_SYNC|os.O_APPEND) != 0 {
			return os.ErrInvalid
		}
		n := dir.children[frag]
		if flag&os.O_CREATE != 0 {
			if flag&os.O_EXCL != 0 && n != nil {
				return os.ErrExist
			}
			if n == nil {
				n = &memFSNode{
					name: frag,
					mode: perm.Perm(),
				}
				dir.children[frag] = n
			}
		}
		if n == nil {
			return os.ErrNotExist
		}
		if flag&(os.O_WRONLY|os.O_RDWR) != 0 && flag&os.O_TRUNC != 0 {
			n.mu.Lock()
			n.data = nil
			n.mu.Unlock()
		}

		children := make([]os.FileInfo, 0, len(n.children))
		for _, c := range n.children {
			children = append(children, c)
		}
		ret = &memFile{
			n:        n,
			children: children,
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return ret, nil
}
Example #14
0
func Command(rootfsPath string, uid, gid int, mode os.FileMode, recreate bool, paths ...string) *exec.Cmd {
	flags := []string{
		name,
		"-rootfsPath", rootfsPath,
		"-uid", strconv.Itoa(uid),
		"-gid", strconv.Itoa(gid),
		"-perm", strconv.Itoa(int(mode.Perm())),
	}

	if recreate {
		flags = append(flags, "-recreate=true")
	}

	return reexec.Command(append(flags, paths...)...)
}
Example #15
0
func (fs *memFS) Mkdir(name string, perm os.FileMode) error {
	return fs.walk("mkdir", name, func(dir *memFSNode, frag string, final bool) error {
		if !final {
			return nil
		}
		if frag == "" {
			return os.ErrInvalid
		}
		if _, ok := dir.children[frag]; ok {
			return os.ErrExist
		}
		dir.children[frag] = &memFSNode{
			name:     frag,
			children: make(map[string]*memFSNode),
			mode:     perm.Perm() | os.ModeDir,
			modTime:  time.Now(),
		}
		return nil
	})
}
Example #16
0
// mknod provides a shortcut for syscall.Mknod
func mknod(p string, mode os.FileMode, maj, min int) error {
	var (
		m   = syscallMode(mode.Perm())
		dev int
	)

	if mode&os.ModeDevice != 0 {
		dev = makedev(maj, min)

		if mode&os.ModeCharDevice != 0 {
			m |= syscall.S_IFCHR
		} else {
			m |= syscall.S_IFBLK
		}
	} else if mode&os.ModeNamedPipe != 0 {
		m |= syscall.S_IFIFO
	}

	return syscall.Mknod(p, m, dev)
}
Example #17
0
func modeToType(mode os.FileMode) byte {
	switch {
	case mode.IsDir():
		return 'd'
	case mode.IsRegular():
		return 'f'
	case mode&os.ModeSymlink != 0:
		return 'l'
	case mode&os.ModeSocket != 0:
		return 's'
	case mode&os.ModeNamedPipe != 0:
		return 'p'
	case mode&os.ModeDevice != 0 && mode&os.ModeCharDevice != 0:
		return 'C'
	case mode&os.ModeDevice != 0 && mode&os.ModeCharDevice == 0:
		return 'D'
	default:
		return 'u'
	}
}
Example #18
0
File: copy.go Project: juju/utils
func copyFile(src, dst string, mode os.FileMode) error {
	srcf, err := os.Open(src)
	if err != nil {
		return err
	}
	defer srcf.Close()
	dstf, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode.Perm())
	if err != nil {
		return err
	}
	defer dstf.Close()
	// Make the actual permissions match the source permissions
	// even in the presence of umask.
	if err := os.Chmod(dstf.Name(), mode.Perm()); err != nil {
		return err
	}
	if _, err := io.Copy(dstf, srcf); err != nil {
		return fmt.Errorf("cannot copy %q to %q: %v", src, dst, err)
	}
	return nil
}
Example #19
0
func (c *Client) PushFile(container string, p string, gid int, uid int, mode os.FileMode, buf io.ReadSeeker) error {
	query := url.Values{"path": []string{p}}
	uri := c.url(shared.APIVersion, "containers", container, "files") + "?" + query.Encode()

	req, err := http.NewRequest("POST", uri, buf)
	if err != nil {
		return err
	}
	req.Header.Set("User-Agent", shared.UserAgent)

	req.Header.Set("X-LXD-mode", fmt.Sprintf("%04o", mode.Perm()))
	req.Header.Set("X-LXD-uid", strconv.FormatUint(uint64(uid), 10))
	req.Header.Set("X-LXD-gid", strconv.FormatUint(uint64(gid), 10))

	raw, err := c.Http.Do(req)
	if err != nil {
		return err
	}

	_, err = HoistResponse(raw, Sync)
	return err
}
Example #20
0
func (fs *memFS) Mkdir(name string, perm os.FileMode) error {
	fs.mu.Lock()
	defer fs.mu.Unlock()

	dir, frag, err := fs.find("mkdir", name)
	if err != nil {
		return err
	}
	if dir == nil {
		// We can't create the root.
		return os.ErrInvalid
	}
	if _, ok := dir.children[frag]; ok {
		return os.ErrExist
	}
	dir.children[frag] = &memFSNode{
		children: make(map[string]*memFSNode),
		mode:     perm.Perm() | os.ModeDir,
		modTime:  time.Now(),
	}
	return nil
}
Example #21
0
func (w *Workspace) WriteEntry(name string, mode os.FileMode, modTime time.Time, r io.Reader, replace bool) error {
	os.MkdirAll(w.Root, 0755)
	filePath := w.getEntry(name)
	info, err := os.Stat(filePath)
	if err != nil {
		if mode.IsDir() {
			if err := os.MkdirAll(filePath, mode|0700); err != nil {
				return err
			}
		} else {
			if err := w.writeRegFile(filePath, mode|0600, modTime, r); err != nil {
				return err
			}
		}
	} else {
		if info.IsDir() {
			if mode.IsDir() {
				if err := os.Chmod(filePath, (mode&0777555)|0700); err != nil {
					return err
				}
			} else {
				if info.ModTime().Before(modTime) || replace {
					os.RemoveAll(filePath)
					if err := w.writeRegFile(filePath, mode|0600, modTime, r); err != nil {
						return err
					}
				} else {
					// pass
				}
			}
		} else {
			if mode.IsDir() {
				if info.ModTime().Before(modTime) || replace {
					os.RemoveAll(filePath)
					if err := os.MkdirAll(filePath, mode|0700); err != nil {
						return err
					}
				} else {
					// pass
				}
			} else {
				if info.ModTime().Before(modTime) || replace {
					if err := w.writeRegFile(filePath, mode|0600, modTime, r); err != nil {
						return err
					}
				} else {
					// pass
				}
			}
		}
	}

	return nil
}
Example #22
0
func (r *Remote) DirPerms(dir string, mode os.FileMode) (bool, error) {
	resp, err := r.RunCmd("ls -ld %s | awk '{printf $1}'", r.path(dir))
	if err != nil {
		return false, err
	}

	fmt.Println(resp, []byte(mode.String()), string(resp), mode.String())

	if string(resp) == mode.String()+"\n" {
		return true, nil
	}

	return false, nil
}
Example #23
0
// osFileModeToFuseFileMode converts a standard os.FileMode to the bit array used
// by the fuse package. Permissions, regular/dir modes, symlinks, and named pipes
// are the only bits that are converted.
func osFileModeToFuseFileMode(inMode os.FileMode) (outMode uint32) {
	if inMode.IsRegular() {
		outMode |= fuse.S_IFREG
	}
	if inMode.IsDir() {
		outMode |= fuse.S_IFDIR
	}
	if inMode&os.ModeSymlink == os.ModeSymlink {
		outMode |= fuse.S_IFLNK
	}
	if inMode&os.ModeNamedPipe == os.ModeNamedPipe {
		outMode |= fuse.S_IFIFO
	}
	outMode |= uint32(inMode.Perm())
	return
}
Example #24
0
// an entry looks something like this:
// type=file;size=12;modify=20150216084148;UNIX.mode=0644;unique=1000004g1187ec7; lorem.txt
func parseMLST(entry string, skipSelfParent bool) (os.FileInfo, error) {
	parseError := ftpError{err: fmt.Errorf(`failed parsing MLST entry: %s`, entry)}
	incompleteError := ftpError{err: fmt.Errorf(`MLST entry incomplete: %s`, entry)}

	parts := strings.Split(entry, "; ")
	if len(parts) != 2 {
		return nil, parseError
	}

	facts := make(map[string]string)
	for _, factPair := range strings.Split(parts[0], ";") {
		factParts := strings.SplitN(factPair, "=", 2)
		if len(factParts) != 2 {
			return nil, parseError
		}
		facts[strings.ToLower(factParts[0])] = strings.ToLower(factParts[1])
	}

	typ := facts["type"]

	if typ == "" {
		return nil, incompleteError
	}

	if skipSelfParent && (typ == "cdir" || typ == "pdir" || typ == "." || typ == "..") {
		return nil, nil
	}

	var mode os.FileMode
	if facts["unix.mode"] != "" {
		m, err := strconv.ParseInt(facts["unix.mode"], 8, 32)
		if err != nil {
			return nil, parseError
		}
		mode = os.FileMode(m)
	} else if facts["perm"] != "" {
		// see http://tools.ietf.org/html/rfc3659#section-7.5.5
		for _, c := range facts["perm"] {
			switch c {
			case 'a', 'd', 'c', 'f', 'm', 'p', 'w':
				// these suggest you have write permissions
				mode |= 0200
			case 'l':
				// can list dir entries means readable and executable
				mode |= 0500
			case 'r':
				// readable file
				mode |= 0400
			}
		}
	} else {
		// no mode info, just say it's readable to us
		mode = 0400
	}

	if typ == "dir" || typ == "cdir" || typ == "pdir" {
		mode |= os.ModeDir
	} else if strings.HasPrefix(typ, "os.unix=slink") || strings.HasPrefix(typ, "os.unix=symlink") {
		// note: there is no general way to determine whether a symlink points to a dir or a file
		mode |= os.ModeSymlink
	}

	var (
		size int64
		err  error
	)

	if facts["size"] != "" {
		size, err = strconv.ParseInt(facts["size"], 10, 64)
	} else if mode.IsDir() && facts["sizd"] != "" {
		size, err = strconv.ParseInt(facts["sizd"], 10, 64)
	} else if facts["type"] == "file" {
		return nil, incompleteError
	}

	if err != nil {
		return nil, parseError
	}

	if facts["modify"] == "" {
		return nil, incompleteError
	}

	mtime, err := time.ParseInLocation(timeFormat, facts["modify"], time.UTC)
	if err != nil {
		return nil, incompleteError
	}

	info := &ftpFile{
		name:  filepath.Base(parts[1]),
		size:  size,
		mtime: mtime,
		raw:   entry,
		mode:  mode,
	}

	return info, nil
}
Example #25
0
func (s *IntegrationTestSuite) assertFilePresent(c *chk.C, path string, perm os.FileMode, readableByNobodyUser bool) {
	info, err := os.Stat(path)
	c.Assert(err, chk.IsNil)
	if (info.Mode() & os.ModeSymlink) != 0 {
		linkedFile, err := os.Readlink(path)
		c.Assert(err, chk.IsNil)
		s.assertFilePresent(c, linkedFile, perm, readableByNobodyUser)
	} else {
		if info.Mode().Perm() != perm {
			c.Errorf("File %s has permission \"%s\" but expected \"%s\"", path, info.Mode().String(), perm.String())
		}
	}

	if readableByNobodyUser {
		for i := path; i != "/"; i = filepath.Dir(i) {
			info, err = os.Stat(i)
			c.Assert(err, chk.IsNil)
			c.Assert(info.Mode().Perm()&0005, chk.Not(chk.Equals), 0)
		}
	}
}
Example #26
0
File: perm.go Project: goftp/ftpd
func hasPerm(mode os.FileMode, idx int, rOrW string) bool {
	return string(mode.String()[idx]) == rOrW
}
Example #27
0
func parseModeSymbolic(s string, base os.FileMode) (os.FileMode, error) {
	// log.Println("-- " + s)
	perm := uint32(base.Perm())
	sbitsMask := uint32(os.ModeSetuid | os.ModeSetgid | os.ModeSticky)
	sbits := uint32(base) & sbitsMask

	for i := 0; i < len(s); {
		// user, group, other, or all
		var whom uint32

		for j, c := range s[i:] {
			// log.Printf("whom: %d %s\n", i, string(s[i]))
			if c == 'u' {
				whom = whom | 0700
			} else if c == 'g' {
				whom = whom | 0070
			} else if c == 'o' {
				whom = whom | 0007
			} else if c == 'a' {
				whom = whom | 0777
			} else {
				if j == 0 {
					whom = 0777
				}
				break
			}
			i++
		}
		if i >= len(s) {
			return 0, errors.New("failed to parse the mode, operator is not found")
		}

		for i < len(s) {
			// operator
			// log.Printf("op: %d %s\n", i, string(s[i]))
			op := 0
			switch s[i] {
			case '-':
				op = '-'
			case '+':
				op = '+'
			case '=':
				op = '='
			default:
				return 0, errors.New("failed to parse the mode, invalid operator")
			}
			i++

			// permission bits to modify
			var smod uint32
			var mod uint32
			if i < len(s) {
				// log.Printf("mod: %d %s\n", i, string(s[i]))
				switch s[i] {
				case 'u':
					mod = (perm & 0700) >> 6
					i++
				case 'g':
					mod = (perm & 0070) >> 3
					i++
				case 'o':
					mod = (perm & 0007) >> 0
					i++
				default:
					for i < len(s) {
						// log.Printf("mod-f: %d %s\n", i, string(s[i]))
						if s[i] == 'r' {
							mod = mod | 4
						} else if s[i] == 'w' {
							mod = mod | 2
						} else if s[i] == 'x' {
							mod = mod | 1
						} else if s[i] == 'X' {
							if base.IsDir() {
								mod = mod | 1
							}
						} else if s[i] == 's' {
							if (whom & 0700) > 0 {
								smod = smod | uint32(os.ModeSetuid)
							}
							if (whom & 0070) > 0 {
								smod = smod | uint32(os.ModeSetgid)
							}
						} else if s[i] == 't' {
							smod = smod | uint32(os.ModeSticky)
						} else {
							break
						}
						i++
					}
				}
				mod = mod<<6 | mod<<3 | mod<<0
			}
			// if i < len(s) {
			//	log.Printf("mod-e: %d %s\n", i, string(s[i]))
			//}

			switch op {
			case '-':
				perm = perm - (whom & mod)
				sbits = sbits - smod
			case '+':
				perm = perm | (whom & mod)
				sbits = sbits | smod
			case '=':
				perm = (perm & (0777 ^ whom)) | (whom & mod)
				sbits = smod
			}

			if i < len(s) {
				// log.Printf(",: %d %s\n", i, string(s[i]))
				if s[i] == ',' {
					i++
					break
				}
			}
		}
	}

	mode := uint32(base)&((1<<32-1)-0777-sbitsMask) | sbits&sbitsMask | perm&0777
	return os.FileMode(mode), nil
}