func TestLink(t *testing.T) { ino := maggiefs.NewInode(0, maggiefs.FTYPE_REG, 0755, uint32(os.Getuid()), uint32(os.Getgid())) id, err := testCluster.Names.AddInode(ino) if err != nil { panic(err) } ino.Inodeid = id ino2 := maggiefs.NewInode(0, maggiefs.FTYPE_REG, 0755, uint32(os.Getuid()), uint32(os.Getgid())) id, err = testCluster.Names.AddInode(ino) if err != nil { panic(err) } ino2.Inodeid = id // test normal link fmt.Println("linking") err = testCluster.Names.Link(ino.Inodeid, ino2.Inodeid, "name", true) if err != nil { panic(err) } ino, err = testCluster.Names.GetInode(ino.Inodeid) if err != nil { panic(err) } if ino.Children["name"].Inodeid != ino2.Inodeid { t.Fatalf("Didn't link properly!") } // test an unforced attempt to overwrite // test overwriting forced }
// Attr returns the attributes of a given node. func (s *Node) Attr(ctx context.Context, a *fuse.Attr) error { log.Debug("Node attr") if s.cached == nil { if err := s.loadData(); err != nil { return fmt.Errorf("readonly: loadData() failed: %s", err) } } switch s.cached.GetType() { case ftpb.Data_Directory: a.Mode = os.ModeDir | 0555 a.Uid = uint32(os.Getuid()) a.Gid = uint32(os.Getgid()) case ftpb.Data_File: size := s.cached.GetFilesize() a.Mode = 0444 a.Size = uint64(size) a.Blocks = uint64(len(s.Nd.Links)) a.Uid = uint32(os.Getuid()) a.Gid = uint32(os.Getgid()) case ftpb.Data_Raw: a.Mode = 0444 a.Size = uint64(len(s.cached.GetData())) a.Blocks = uint64(len(s.Nd.Links)) a.Uid = uint32(os.Getuid()) a.Gid = uint32(os.Getgid()) case ftpb.Data_Symlink: a.Mode = 0777 | os.ModeSymlink a.Size = uint64(len(s.cached.GetData())) a.Uid = uint32(os.Getuid()) a.Gid = uint32(os.Getgid()) default: return fmt.Errorf("Invalid data type - %s", s.cached.GetType()) } return nil }
// Test running 'ls -l' with a symlink 'b' pointing to a file 'a' func Test_l_File_Link2(t *testing.T) { setup_test_dir("l_File_Link2") time_now := time.Now() size := 13 path := "a" _mkfile2(path, 0600, os.Getuid(), os.Getgid(), size, time_now) _mklink(path, "b") var output_buffer bytes.Buffer args := []string{"-l", "--nocolor"} ls_err := ls(&output_buffer, args, tw) output := clean_output_buffer(output_buffer) // remove the permissions string from each file listing output_line_split := strings.Split(output, "\n") output_noperms := "" for _, l := range output_line_split { output_line_split_noperms := strings.Split(l, " ")[1:] output_line_noperms := strings.Join(output_line_split_noperms, " ") if len(output_noperms) == 0 { output_noperms = output_line_noperms } else { output_noperms = output_noperms + "\n" + output_line_noperms } } var owner string owner_lookup, err := user.LookupId(fmt.Sprintf("%d", os.Getuid())) if err != nil { owner = user_map[int(os.Getuid())] } else { owner = owner_lookup.Username } group := group_map[os.Getgid()] expected := fmt.Sprintf( "1 %s %s %d %s %02d %02d:%02d a\n1 %s %s 1 %s %02d %02d:%02d b -> %s", owner, group, size, time_now.Month().String()[0:3], time_now.Day(), time_now.Hour(), time_now.Minute(), owner, group, time_now.Month().String()[0:3], time_now.Day(), time_now.Hour(), time_now.Minute(), path) check_output(t, output_noperms, expected) check_error_nil(t, ls_err) }
// Test LS_COLORS with an orphan link func Test_LS_COLORS_orphan_link(t *testing.T) { setup_test_dir("LS_COLORS_orphan_link") time_now := time.Now() _mkfile2("a", 0600, os.Getuid(), os.Getgid(), 8, time_now) _mklink("a", "b") _rm("a") os.Setenv("LS_COLORS", default_LS_COLORS) var output_buffer bytes.Buffer args := []string{"-l"} ls_err := ls(&output_buffer, args, tw) output := clean_output_buffer(output_buffer) // remove the permissions string from the output output_noperms := strings.Join(strings.Split(output, " ")[1:], " ") var owner string owner_lookup, err := user.LookupId(fmt.Sprintf("%d", os.Getuid())) if err != nil { owner = user_map[int(os.Getuid())] } else { owner = owner_lookup.Username } group := group_map[os.Getgid()] // link info link_info, err := os.Lstat("b") if err != nil { t.Fatalf("error checking the symlink") } expected := fmt.Sprintf("1 %s %s %d %s %02d %02d:%02d %sb%s -> %sa%s", owner, group, link_info.Size(), time_now.Month().String()[0:3], time_now.Day(), time_now.Hour(), time_now.Minute(), "\x1b[40;31;01m", "\x1b[0m", "\x1b[01;05;37;41m", "\x1b[0m") check_output(t, output_noperms, expected) check_error_nil(t, ls_err) }
func (this *mapbe) DirMeta() (Meta, error) { return Meta{ Perm: 0755, Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid()), }, nil }
// Attr returns the attributes of a given node. func (d *Directory) Attr(ctx context.Context, a *fuse.Attr) error { log.Debug("Directory Attr") a.Mode = os.ModeDir | 0555 a.Uid = uint32(os.Getuid()) a.Gid = uint32(os.Getgid()) return nil }
func (n *mutFile) Attr() fuse.Attr { // TODO: don't grab n.mu three+ times in here. var mode os.FileMode = 0600 // writable n.mu.Lock() size := n.size var blocks uint64 if size > 0 { blocks = uint64(size)/512 + 1 } inode := n.permanode.Sum64() if n.symLink { mode |= os.ModeSymlink } n.mu.Unlock() return fuse.Attr{ Inode: inode, Mode: mode, Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid()), Size: uint64(size), Blocks: blocks, Mtime: n.modTime(), Atime: n.accessTime(), Ctime: serverStart, Crtime: serverStart, } }
// populateAttr should only be called once n.ss is known to be set and // non-nil func (n *node) populateAttr() error { ss := n.ss n.attr.Mode = ss.FileMode() if n.fs.IgnoreOwners { n.attr.Uid = uint32(os.Getuid()) n.attr.Gid = uint32(os.Getgid()) executeBit := n.attr.Mode & 0100 n.attr.Mode = (n.attr.Mode ^ n.attr.Mode.Perm()) & 0400 & executeBit } else { n.attr.Uid = uint32(ss.MapUid()) n.attr.Gid = uint32(ss.MapGid()) } // TODO: inode? n.attr.Mtime = ss.ModTime() switch ss.Type { case "file": n.attr.Size = ss.SumPartsSize() n.attr.Blocks = 0 // TODO: set? case "directory": // Nothing special? Just prevent default case. case "symlink": // Nothing special? Just prevent default case. default: log.Printf("unknown attr ss.Type %q in populateAttr", ss.Type) } return nil }
func newTestTar(entries []*testTarEntry, dir string) (string, error) { t, err := ioutil.TempFile(dir, "tar") if err != nil { return "", err } defer t.Close() tw := tar.NewWriter(t) for _, entry := range entries { // Add default mode if entry.header.Mode == 0 { if entry.header.Typeflag == tar.TypeDir { entry.header.Mode = 0755 } else { entry.header.Mode = 0644 } } // Add calling user uid and gid or tests will fail entry.header.Uid = os.Getuid() entry.header.Gid = os.Getgid() if err := tw.WriteHeader(entry.header); err != nil { return "", err } if _, err := io.WriteString(tw, entry.contents); err != nil { return "", err } } if err := tw.Close(); err != nil { return "", err } return t.Name(), nil }
func TestNewFileCreation(t *testing.T) { Convey("Given a file path", t, func() { fname := filepath.Join(os.TempDir(), "__test_filepath") Convey("It should create an empty file", func() { err := file.New(fname) So(err, ShouldBeNil) defer os.Remove(fname) _, err = os.Stat(fname) So(err, ShouldBeNil) }) Convey("With optional argument Contents", func() { c := "This is a file with text in it.\n" Convey("It should create a new file with the given contents", func() { err := file.New(fname, file.Contents(c)) So(err, ShouldBeNil) defer os.Remove(fname) out, err := ioutil.ReadFile(fname) So(err, ShouldBeNil) So(string(out), ShouldEqual, c) }) }) Convey("With optional argument Permissions", func() { p := os.FileMode(0700) Convey("It should create a new file with the same permissions", func() { err := file.New(fname, file.Permissions(p)) So(err, ShouldBeNil) defer os.Remove(fname) fi, err := os.Lstat(fname) So(err, ShouldBeNil) So(fi.Mode(), ShouldEqual, p) }) }) Convey("With optional argument User ID and/or Group ID", func() { userID, groupID := os.Getuid(), os.Getgid() Convey("It should create a new file belonging to given IDs", func() { err := file.New(fname, file.UID(userID), file.GID(groupID)) So(err, ShouldBeNil) defer os.Remove(fname) fi, err := os.Lstat(fname) So(err, ShouldBeNil) uid := fi.Sys().(*syscall.Stat_t).Uid So(uid, ShouldEqual, userID) gid := fi.Sys().(*syscall.Stat_t).Gid So(gid, ShouldEqual, groupID) }) }) }) }
func changePermissions(path string) error { var uid, gid int var err error suid := os.Getenv("SUDO_UID") if suid != "" { uid, err = strconv.Atoi(suid) if err != nil { return err } } else { uid = os.Getuid() } sgid := os.Getenv("SUDO_GID") if sgid != "" { gid, err = strconv.Atoi(sgid) if err != nil { return err } } else { gid = os.Getgid() } return os.Chown(path, uid, gid) }
func (n *rootsDir) Attr() fuse.Attr { return fuse.Attr{ Mode: os.ModeDir | n.dirMode(), Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid()), } }
func main() { runtime.GOMAXPROCS(runtime.NumCPU()) listener, err := reuseport.NewReusablePortListener("tcp4", "localhost:8881") if err != nil { panic(err) } defer listener.Close() server := &http.Server{} http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Println(os.Getgid()) go func() { cmd := exec.Command("./server") cmd.Start() log.Println("-------start") time.Sleep(18 * time.Second) log.Println("-------end") cmd.Process.Kill() cmd.Wait() }() fmt.Fprintf(w, "Hello, %q\n", html.EscapeString(r.URL.Path)) }) panic(server.Serve(listener)) }
func newDirFromSnapshot(repo *repository.Repository, snapshot SnapshotWithId, ownerIsRoot bool) (*dir, error) { tree, err := restic.LoadTree(repo, *snapshot.Tree) if err != nil { return nil, err } items := make(map[string]*restic.Node) for _, n := range tree.Nodes { nodes, err := replaceSpecialNodes(repo, n) if err != nil { return nil, err } for _, node := range nodes { items[node.Name] = node } } return &dir{ repo: repo, node: &restic.Node{ UID: uint32(os.Getuid()), GID: uint32(os.Getgid()), AccessTime: snapshot.Time, ModTime: snapshot.Time, ChangeTime: snapshot.Time, Mode: os.ModeDir | 0555, }, items: items, inode: inodeFromBackendId(snapshot.ID), ownerIsRoot: ownerIsRoot, }, nil }
func OpenRuntime(file string, flag int) (*os.File, error) { // TODO: Make sure that the runtime directory is only readable by the user. _, err := os.Stat(RuntimeDir) if err != nil { if os.IsNotExist(err) { err = os.MkdirAll(RuntimeDir, os.ModeDir|0700) if err != nil { return nil, err } _, err = os.Stat(RuntimeDir) if err != nil { // This really should never happen, but you never know! return nil, err } } else { return nil, err } } err = os.Chown(RuntimeDir, os.Getuid(), os.Getgid()) if err != nil { return nil, err } return open(UserRuntime(file), flag) }
func (n *root) Attr() fuse.Attr { return fuse.Attr{ Mode: os.ModeDir | 0755, Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid()), } }
func CurrentProcessInfo() *ProcessInfo { var hasTty bool cwd, _ := os.Getwd() grp, _ := os.Getgroups() // no syscall.Getsid() wrapper on Linux? sid, _, _ := syscall.RawSyscall(syscall.SYS_GETSID, 0, 0, 0) if fh, err := os.Open("/dev/tty"); err == nil { hasTty = true fh.Close() } return &ProcessInfo{ Ppid: os.Getppid(), Pid: os.Getpid(), Uid: os.Getuid(), Euid: os.Geteuid(), Gid: os.Getgid(), Egid: os.Getegid(), Pgrp: syscall.Getpgrp(), Sid: int(sid), Dir: cwd, Groups: grp, Args: os.Args, Env: os.Environ(), HasTty: hasTty, } }
func (statsDir) Attr() fuse.Attr { return fuse.Attr{ Mode: os.ModeDir | 0700, Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid()), } }
func (t *unixTransport) Auth() error { cred := syscall.UnixCredentials(&syscall.Ucred{ Pid: int32(os.Getpid()), Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid()), }) _, _, err := t.WriteMsgUnix([]byte{0}, cred, nil) if err != nil { return err } if _, err := fmt.Fprintf(t, "AUTH EXTERNAL %x\r\n", fmt.Sprintf("%d", os.Getuid())); err != nil { return err } var code, cookie string if _, err := fmt.Fscanln(t, &code, &cookie); err != nil { return err } fmt.Println(code, cookie) if _, err := fmt.Fprintf(t, "BEGIN\r\n"); err != nil { return err } return nil }
func newStore(t *testing.T) storage.Store { wd, err := ioutil.TempDir(topwd, "test.") if err != nil { t.Fatal(err) } err = os.MkdirAll(wd, 0700) if err != nil { t.Fatal(err) } run := filepath.Join(wd, "run") root := filepath.Join(wd, "root") uidmap := []idtools.IDMap{{ ContainerID: 0, HostID: os.Getuid(), Size: 1, }} gidmap := []idtools.IDMap{{ ContainerID: 0, HostID: os.Getgid(), Size: 1, }} store, err := storage.GetStore(storage.StoreOptions{ RunRoot: run, GraphRoot: root, GraphDriverName: "vfs", GraphDriverOptions: []string{}, UIDMap: uidmap, GIDMap: gidmap, }) if err != nil { t.Fatal(err) } Transport.SetStore(store) return store }
func (notImplementDirNode) Attr() fuse.Attr { return fuse.Attr{ Mode: os.ModeDir | 0000, Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid()), } }
func TestEmptyCredGroupsDisableSetgroups(t *testing.T) { cmd := whoamiCmd(t, os.Getuid(), os.Getgid(), false) cmd.SysProcAttr.Credential = &syscall.Credential{} if err := cmd.Run(); err != nil { t.Fatal(err) } }
func TestOwner(t *testing.T) { uid := os.Getuid() gid := os.Getgid() f, err := ioutil.TempFile("./", "") if err != nil { t.Error(err) } name := f.Name() owner, group, err := Owner(name) if err != nil { t.Error(err) } if owner != uid { t.Fail() } if group != gid { t.Fail() } if err := f.Close(); err != nil { t.Error(err) } if err != os.Remove(name) { t.Error(err) } }
func statusHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") fmt.Fprintf(w, "pid=%d\n", os.Getpid()) cwd, _ := os.Getwd() fmt.Fprintf(w, "cwd=%s\n", cwd) fmt.Fprintf(w, "uid=%d\n", os.Getuid()) fmt.Fprintf(w, "euid=%d\n", os.Geteuid()) fmt.Fprintf(w, "gid=%d\n", os.Getgid()) groups, gerr := exec.Command("groups").CombinedOutput() if gerr != nil { fmt.Fprintf(w, "groups_err=%q\n", gerr) } else { fmt.Fprintf(w, "groups=%s\n", strings.TrimSpace(string(groups))) } ulimitN, _ := exec.Command("ulimit", "-n").Output() fmt.Fprintf(w, "ulimit_nofiles=%s\n", strings.TrimSpace(string(ulimitN))) env := os.Environ() sort.Strings(env) for _, env := range env { fmt.Fprintf(w, "%s\n", env) } }
func (n *roFile) Attr(ctx context.Context, a *fuse.Attr) error { // TODO: don't grab n.mu three+ times in here. var mode os.FileMode = 0400 // read-only n.mu.Lock() size := n.size var blocks uint64 if size > 0 { blocks = uint64(size)/512 + 1 } inode := n.permanode.Sum64() if n.symLink { mode |= os.ModeSymlink } n.mu.Unlock() *a = fuse.Attr{ Inode: inode, Mode: mode, Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid()), Size: uint64(size), Blocks: blocks, Mtime: n.modTime(), Atime: n.accessTime(), Ctime: serverStart, Crtime: serverStart, } return nil }
func (n *mutFile) Attr() fuse.Attr { // TODO: don't grab n.mu three+ times in here. n.mu.Lock() size := n.size var blocks uint64 if size > 0 { blocks = uint64(size)/512 + 1 } inode := n.permanode.AsUint64() n.mu.Unlock() return fuse.Attr{ Inode: inode, Mode: 0600, // writable! Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid()), Size: uint64(size), Blocks: blocks, Mtime: n.modTime(), Atime: n.accessTime(), Ctime: serverStart, Crtime: serverStart, } }
func main() { // 获取系统名字 fmt.Println(os.Hostname()) // 获取系统内存 fmt.Println(os.Getpagesize()) // 获取系统环境变量 for index, env := range os.Environ() { fmt.Println(index, " : ", env) } // 获取指定key的环境变量,环境变量不区分大小写 fmt.Println("当前系统目录为:", os.Getenv("windir")) // 设置环境变量 fmt.Println("cody的环境变量为:", os.Getenv("cody")) os.Setenv("Cody", "guo") fmt.Println("cody的环境变量为:", os.Getenv("cody")) // 删除所有环境变量 os.Clearenv() fmt.Println(os.Environ()) // 如果存在os.Exit()就不会执行defer // defer fmt.Println("我在退出吗?") // os.Exit(0) fmt.Println("程序已退出,不打印了...") fmt.Println(os.Getuid(), os.Getgid()) fmt.Println(os.Getgroups()) fmt.Println(os.Getpid(), os.Getppid()) fmt.Println(os.TempDir()) }
func New(filepath string, setters ...argument) error { // Default arguments args := &arguments{ UID: os.Getuid(), GID: os.Getgid(), Contents: "", Permissions: 0666, Flags: os.O_CREATE | os.O_EXCL | os.O_WRONLY, } for _, setter := range setters { setter(args) } f, err := os.OpenFile(filepath, args.Flags, args.Permissions) if err != nil { return err } else { defer f.Close() } if _, err := f.WriteString(args.Contents); err != nil { return err } return f.Chown(args.UID, args.GID) }
func (n *atDir) Attr() fuse.Attr { return fuse.Attr{ Mode: os.ModeDir | 0500, Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid()), } }
// Returns the UID and GID to enforce. If the UID or GID is -1, it is not // to be enforced. Neither or both or either of the UID or GID may be -1. func resolveUIDGID(p *Permission) (uid, gid int, err error) { if p.UID == "$r" { uid = os.Getuid() } else if p.UID != "" { uid, err = passwd.ParseUID(p.UID) if err != nil { return } } else { uid = -1 } if p.GID == "$r" { gid = os.Getgid() } else if p.GID != "" { gid, err = passwd.ParseGID(p.GID) if err != nil { return } } else { gid = -1 } return }