Golang Getuid示例

说明

golang getuid示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: os

示例#1
文件: readonly_unix.go 项目: yanghongkjxy/go-ipfs

// 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
}

示例#2
文件: pipe_example.go 项目: jmptrader/go-utils-1

func main() {
	flagUsername := flag.String("username", "nobody", "username for the unprivileged child")

	isChild, r, w, _, err := privsep.MaybeBecomeChild()
	if err != nil {
		log.Fatalf("MaybeBecomeChild failed: %s", err)
	}

	who := "parent"
	if isChild {
		who = "child"
	}
	log.Printf("%s: pid=%d uid=%d euid=%d gid=%d egid=%d",
		who, os.Getpid(), os.Getuid(), os.Geteuid(), os.Getgid(), os.Getegid())

	if isChild {
		child(r, w)
		return
	}

	if os.Getuid() != 0 {
		log.Print("Warning: this example only works when run as the root user")
	}

	_, r, w, err = privsep.CreateChild(*flagUsername, os.Args[0], nil, nil)
	if err != nil {
		log.Fatalf("CreateChild failed: %s", err)
	}
	parent(r, w)
}

示例#3
文件: sem_test.go 项目: jmptrader/go-sysvipc

func TestSemStat(t *testing.T) {
	semSetup(t)
	defer semTeardown(t)

	// EIDRM with a bad semset id
	if _, err := (&SemaphoreSet{5, 2}).Stat(); err != syscall.EIDRM {
		t.Error("semctl(IPC_STAT) on a made up semset id should fail")
	}

	info, err := ss.Stat()
	if err != nil {
		t.Fatal(err)
	}

	if info.Perms.OwnerUID != os.Getuid() {
		t.Error("wrong owner uid", info.Perms.OwnerUID)
	}
	if info.Perms.CreatorUID != os.Getuid() {
		t.Error("wrong creator uid", info.Perms.CreatorUID)
	}
	if info.Perms.Mode&0777 != 0600 {
		t.Error("wrong mode", info.Perms.Mode)
	}
	if info.Count != 4 {
		t.Error("wrong count", info.Count)
	}
}

示例#4
文件: transport.go 项目: davecheney/dbus-old

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
}

示例#5
文件: nameserver_test.go 项目: jbooth/maggiefs

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

}

示例#6
文件: ls_test.go 项目: yangzhao28/ls

// 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)
}

示例#7
文件: listener_example.go 项目: jmptrader/go-utils-1

func main() {
	flagUsername := flag.String("username", "nobody", "username for the unprivileged child")

	isChild, _, _, files, err := privsep.MaybeBecomeChild()
	if err != nil {
		log.Fatalf("MaybeBecomeChild failed: %s", err)
	}

	who := "parent"
	if isChild {
		who = "child"
	}
	log.Printf("%s: pid=%d uid=%d euid=%d gid=%d egid=%d",
		who, os.Getpid(), os.Getuid(), os.Geteuid(), os.Getgid(), os.Getegid())

	if isChild {
		if len(files) < 1 {
			log.Fatalf("no extra files: %v", files)
		}
		l, err := net.FileListener(files[0])
		if err != nil {
			log.Fatalf("FileListener: %s", err)
		}
		child(l)
		return
	}

	if os.Getuid() != 0 {
		log.Print("Warning: this example only works when run as the root user")
	}

	addr := "localhost:1111"
	laddr, err := net.ResolveTCPAddr("tcp", addr)
	if err != nil {
		log.Fatalf("resolve %s: %s", addr, err)
	}

	l, err := net.ListenTCP("tcp", laddr)
	if err != nil {
		log.Fatalf("listen %s: %s", laddr, err)
	}

	sock, err := l.File()
	if err != nil {
		log.Fatalf("fd: %s", err)
	}

	proc, _, _, err := privsep.CreateChild(*flagUsername, os.Args[0], nil, []*os.File{sock})
	if err != nil {
		log.Fatalf("CreateChild failed: %s", err)
	}

	sock.Close()

	// tidy up so child doesn't run forever
	defer proc.Kill()

	parent(laddr)
}

示例#8
文件: exec_linux_test.go 项目: pjump/gcc

func TestCloneNEWUSERAndRemapNoRootSetgroupsEnableSetgroups(t *testing.T) {
	if os.Getuid() == 0 {
		t.Skip("skipping unprivileged user only test")
	}
	cmd := whoamiCmd(t, os.Getuid(), os.Getgid(), true)
	err := cmd.Run()
	if err == nil {
		t.Skip("probably old kernel without security fix")
	}
	if !os.IsPermission(err) {
		t.Fatalf("Unprivileged gid_map rewriting with GidMappingsEnableSetgroups must fail")
	}
}

示例#9
文件: ls_test.go 项目: yangzhao28/ls

// 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)
}

示例#10
文件: main.go 项目: CodyGuo/Go-Cody

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())

}

示例#11
文件: unicastsockopt_test.go 项目: EPICPaaS/go.net

func TestRawConnUnicastSocketOptions(t *testing.T) {
	switch runtime.GOOS {
	case "plan9":
		t.Skipf("not supported on %q", runtime.GOOS)
	}
	if os.Getuid() != 0 {
		t.Skip("must be root")
	}
	ifi := loopbackInterface()
	if ifi == nil {
		t.Skipf("not available on %q", runtime.GOOS)
	}

	c, err := net.ListenPacket("ip4:icmp", "127.0.0.1")
	if err != nil {
		t.Fatalf("net.ListenPacket failed: %v", err)
	}
	defer c.Close()

	r, err := ipv4.NewRawConn(c)
	if err != nil {
		t.Fatalf("ipv4.NewRawConn failed: %v", err)
	}

	testUnicastSocketOptions(t, r)
}

示例#12
文件: fs.go 项目: t3rm1n4l/camlistore

// 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
}

示例#13
文件: icmp_test.go 项目: Juraldinio/vole

func TestSetICMPFilter(t *testing.T) {
	switch runtime.GOOS {
	case "plan9", "windows":
		t.Skipf("not supported on %q", runtime.GOOS)
	}
	if !supportsIPv6 {
		t.Skip("ipv6 is not supported")
	}
	if os.Getuid() != 0 {
		t.Skip("must be root")
	}

	c, err := net.ListenPacket("ip6:ipv6-icmp", "::1")
	if err != nil {
		t.Fatalf("net.ListenPacket failed: %v", err)
	}
	defer c.Close()

	p := ipv6.NewPacketConn(c)

	var f ipv6.ICMPFilter
	f.SetAll(true)
	f.Set(ipv6.ICMPTypeEchoRequest, false)
	f.Set(ipv6.ICMPTypeEchoReply, false)
	if err := p.SetICMPFilter(&f); err != nil {
		t.Fatalf("ipv6.PacketConn.SetICMPFilter failed: %v", err)
	}
	kf, err := p.ICMPFilter()
	if err != nil {
		t.Fatalf("ipv6.PacketConn.ICMPFilter failed: %v", err)
	}
	if !reflect.DeepEqual(kf, &f) {
		t.Fatalf("got unexpected filter %#v; expected %#v", kf, f)
	}
}

示例#14
文件: multicast_posix_test.go 项目: redcatmiss/gcc

// TestMulticastListener tests both single and double listen to a test
// listener with same address family, same group address and same port.
func TestMulticastListener(t *testing.T) {
	switch runtime.GOOS {
	case "netbsd", "openbsd", "plan9", "windows":
		t.Logf("skipping test on %q", runtime.GOOS)
		return
	case "linux":
		if runtime.GOARCH == "arm" || runtime.GOARCH == "alpha" {
			t.Logf("skipping test on %q/%q", runtime.GOOS, runtime.GOARCH)
			return
		}
	}

	for _, tt := range multicastListenerTests {
		if tt.ipv6 && (!*testIPv6 || !supportsIPv6 || os.Getuid() != 0) {
			continue
		}
		ifi, err := availMulticastInterface(t, tt.flags)
		if err != nil {
			continue
		}
		c1, err := ListenMulticastUDP(tt.net, ifi, tt.gaddr)
		if err != nil {
			t.Fatalf("First ListenMulticastUDP failed: %v", err)
		}
		checkMulticastListener(t, err, c1, tt.gaddr)
		c2, err := ListenMulticastUDP(tt.net, ifi, tt.gaddr)
		if err != nil {
			t.Fatalf("Second ListenMulticastUDP failed: %v", err)
		}
		checkMulticastListener(t, err, c2, tt.gaddr)
		c2.Close()
		c1.Close()
	}
}

示例#15
文件: dbus.go 项目: RubanDeventhiran/coreos-cloudinit

func (c *Conn) initConnection() error {
	var err error
	c.sysconn, err = dbus.SystemBusPrivate()
	if err != nil {
		return err
	}

	// Only use EXTERNAL method, and hardcode the uid (not username)
	// to avoid a username lookup (which requires a dynamically linked
	// libc)
	methods := []dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))}

	err = c.sysconn.Auth(methods)
	if err != nil {
		c.sysconn.Close()
		return err
	}

	err = c.sysconn.Hello()
	if err != nil {
		c.sysconn.Close()
		return err
	}

	c.sysobj = c.sysconn.Object("org.freedesktop.systemd1", dbus.ObjectPath("/org/freedesktop/systemd1"))

	// Setup the listeners on jobs so that we can get completions
	c.sysconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
		"type='signal', interface='org.freedesktop.systemd1.Manager', member='JobRemoved'")
	c.initSubscription()
	c.initDispatch()

	return nil
}

示例#16
文件: file_desc_test.go 项目: yufeng108/goleveldb

func TestFileDesc_Flock(t *testing.T) {
	pth := path.Join(os.TempDir(), fmt.Sprintf("goleveldbtestfd-%d", os.Getuid()))

	_, err := os.Stat(pth)
	if err == nil {
		err = os.RemoveAll(pth)
		if err != nil {
			t.Fatal("RemoveAll: got error: ", err)
		}
	}

	p1, err := OpenFile(pth)
	if err != nil {
		t.Fatal("OpenFile(1): got error: ", err)
	}

	defer os.RemoveAll(pth)

	p2, err := OpenFile(pth)
	if err != nil {
		t.Log("OpenFile(2): got error: ", err)
	} else {
		p2.Close()
		p1.Close()
		t.Fatal("OpenFile(2): expect error")
	}

	p1.Close()

	p3, err := OpenFile(pth)
	if err != nil {
		t.Fatal("OpenFile(3): got error: ", err)
	}
	p3.Close()
}

示例#17
文件: main.go 项目: jcantrill/geard

func switchnsExec(args []string) {
	var err error

	client, err := docker.GetConnection("unix:///var/run/docker.sock")
	if err != nil {
		fmt.Printf("Unable to connect to server\n")
		os.Exit(3)
	}

	uid := os.Getuid()

	if uid == 0 {
		runCommandInContainer(client, containerName, args, envs)
	} else {
		var u *user.User
		var containerId containers.Identifier

		if u, err = user.LookupId(strconv.Itoa(uid)); err != nil {
			fmt.Printf("Couldn't lookup uid %s\n", uid)
			os.Exit(2)
		}

		if containerId, err = containers.NewIdentifierFromUser(u); err != nil {
			fmt.Printf("Couldn't get identifier from user: %v\n", u)
			os.Exit(2)
		}
		runCommandInContainer(client, containerId.ContainerFor(), []string{"/bin/sh", "-l"}, []string{})
	}
}

示例#18
文件: input.go 项目: jlk/vFenseAgent-nix

func GetInput() {
	flag.Parse()

	// Using to append all fatal messages.
	fatalMessages := make([]string, 0)

	if os.Getuid() != 0 {
		fatalMessages = append(fatalMessages, "Install script must be run with root privileges.")
	}

	if *UserName == "" {
		fatalMessages = append(fatalMessages, "Please provide a username to -u.")
	}
	if *Password == "" {
		fatalMessages = append(fatalMessages, "Please provide a password to -pw.")
	}

	if *ServerHostName == "" && *ServerIpAddress == "" {
		fatalMessages = append(fatalMessages, "Please provide a server hostname to -s or a server ip address to -i.")
	}

	if len(fatalMessages) > 0 {
		utils.Errors(fatalMessages...)
	}
}

示例#19
文件: socket.go 项目: rdterner/debug

// CollectGarbage deletes any no-longer-used sockets in the UID-specific sub-
// directory of /tmp.
func CollectGarbage() {
	dirName, _ := names(os.Getuid(), os.Getpid())
	dir, err := os.Open(dirName)
	if err != nil {
		return
	}
	defer dir.Close()
	fileNames, err := dir.Readdirnames(-1)
	if err != nil {
		return
	}
	for _, fileName := range fileNames {
		if len(fileName) < 3 || fileName[:3] != "pid" {
			continue
		}
		pid, ok := atoi(fileName[3:])
		if !ok {
			continue
		}
		// See if there is a process with the given PID. The os.FindProcess function
		// looks relevant, but on Unix that always succeeds even if there is no such
		// process. Instead, we send signal 0 and look for ESRCH.
		if syscall.Kill(pid, 0) != syscall.ESRCH {
			continue
		}
		os.Remove(dirName + "/" + fileName)
	}
}

示例#20
文件: serve_test.go 项目: djbarber/ipfs-hack

func TestMknod(t *testing.T) {
	t.Parallel()
	if os.Getuid() != 0 {
		t.Skip("skipping unless root")
	}

	f := &mknod1{}
	mnt, err := fstestutil.MountedT(t, fstestutil.SimpleFS{f})
	if err != nil {
		t.Fatal(err)
	}
	defer mnt.Close()

	defer syscall.Umask(syscall.Umask(0))
	err = syscall.Mknod(mnt.Dir+"/node", syscall.S_IFIFO|0666, 123)
	if err != nil {
		t.Fatalf("Mknod: %v", err)
	}

	want := fuse.MknodRequest{
		Name: "node",
		Mode: os.FileMode(os.ModeNamedPipe | 0666),
		Rdev: uint32(123),
	}
	if runtime.GOOS == "linux" {
		// Linux fuse doesn't echo back the rdev if the node
		// isn't a device (we're using a FIFO here, as that
		// bit is portable.)
		want.Rdev = 0
	}
	if g, e := f.RecordedMknod(), want; g != e {
		t.Fatalf("mknod saw %+v, want %+v", g, e)
	}
}

示例#21
文件: storage.go 项目: conseweb/goleveldb

func NewStorage() *Storage {
	var stor storage.Storage
	var closeFn func() error
	if storageUseFS {
		for {
			storageMu.Lock()
			num := storageNum
			storageNum++
			storageMu.Unlock()
			path := filepath.Join(os.TempDir(), fmt.Sprintf("goleveldb-test%d0%d0%d", os.Getuid(), os.Getpid(), num))
			if _, err := os.Stat(path); os.IsNotExist(err) {
				stor, err = storage.OpenFile(path)
				ExpectWithOffset(1, err).NotTo(HaveOccurred(), "creating storage at %s", path)
				closeFn = func() error {
					if storageKeepFS {
						return nil
					}
					return os.RemoveAll(path)
				}
				break
			}
		}
	} else {
		stor = storage.NewMemStorage()
	}
	s := &Storage{
		Storage: stor,
		closeFn: closeFn,
		opens:   make(map[uint64]bool),
	}
	s.stallCond.L = &s.mu
	return s
}

示例#22
文件: acirenderer_test.go 项目: krnowak/appc-spec

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
}

示例#23
文件: main.go 项目: jcantrill/geard

func switchnsGit() {
	var u *user.User
	var err error
	var repoId git.RepoIdentifier

	uid := os.Getuid()
	originalCommand := os.Getenv("SSH_ORIGINAL_COMMAND")

	if u, err = user.LookupId(strconv.Itoa(uid)); err != nil {
		fmt.Printf("Couldn't find user with uid %n\n", uid)
		os.Exit(2)
	}

	if uid != 0 {
		if !isValidGitCommand(originalCommand, !gitRw) {
			fmt.Printf("Invalid git command: %s\n", originalCommand)
			os.Exit(2)
		}
		if repoId, err = git.NewIdentifierFromUser(u); err != nil {
			fmt.Printf("Couldn't create identifier for user %v\n", u)
			os.Exit(2)
		}
		env := []string{fmt.Sprintf("HOME=%s", repoId.RepositoryPathFor())}
		client, err := docker.GetConnection("unix:///var/run/docker.sock")
		if err != nil {
			fmt.Printf("Unable to connect to server\n")
			os.Exit(3)
		}

		runCommandInContainer(client, "geard-githost", []string{"/usr/bin/git-shell", "-c", originalCommand}, env)
	} else {
		fmt.Println("Cannot switch into any git repo as root user")
		os.Exit(2)
	}
}

示例#24
文件: dbus.go 项目: 98pm/docker

func (c *Conn) initConnection() error {
	var err error
	c.conn, err = dbus.SystemBusPrivate()
	if err != nil {
		return err
	}

	// Only use EXTERNAL method, and hardcode the uid (not username)
	// to avoid a username lookup (which requires a dynamically linked
	// libc)
	methods := []dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))}

	err = c.conn.Auth(methods)
	if err != nil {
		c.conn.Close()
		return err
	}

	err = c.conn.Hello()
	if err != nil {
		c.conn.Close()
		return err
	}

	c.object = c.conn.Object("org.freedesktop.login1", dbus.ObjectPath(dbusPath))

	return nil
}

示例#25
文件: mut.go 项目: JayBlaze420/camlistore

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,
	}
}

示例#26
文件: message_test.go 项目: XLabWang/net

func TestMonitorAndParseRIB(t *testing.T) {
	if testing.Short() || os.Getuid() != 0 {
		t.Skip("must be root")
	}

	// We suppose that using an IPv4 link-local address and the
	// dot1Q ID for Token Ring and FDDI doesn't harm anyone.
	pv := &propVirtual{addr: "169.254.0.1", mask: "255.255.255.0"}
	if err := pv.configure(1002); err != nil {
		t.Skip(err)
	}
	if err := pv.setup(); err != nil {
		t.Skip(err)
	}
	pv.teardown()

	s, err := syscall.Socket(syscall.AF_ROUTE, syscall.SOCK_RAW, syscall.AF_UNSPEC)
	if err != nil {
		t.Fatal(err)
	}
	defer syscall.Close(s)

	go func() {
		b := make([]byte, os.Getpagesize())
		for {
			n, err := syscall.Read(s, b)
			if err != nil {
				return
			}
			ms, err := ParseRIB(0, b[:n])
			if err != nil {
				t.Error(err)
				return
			}
			ss, err := msgs(ms).validate()
			if err != nil {
				t.Error(err)
				return
			}
			for _, s := range ss {
				t.Log(s)
			}
		}
	}()

	for _, vid := range []int{1002, 1003, 1004, 1005} {
		pv := &propVirtual{addr: "169.254.0.1", mask: "255.255.255.0"}
		if err := pv.configure(vid); err != nil {
			t.Fatal(err)
		}
		if err := pv.setup(); err != nil {
			t.Fatal(err)
		}
		time.Sleep(200 * time.Millisecond)
		if err := pv.teardown(); err != nil {
			t.Fatal(err)
		}
		time.Sleep(200 * time.Millisecond)
	}
}

示例#27
文件: at.go 项目: camarox53/coreos-baremetal

func (n *atDir) Attr() fuse.Attr {
	return fuse.Attr{
		Mode: os.ModeDir | 0500,
		Uid:  uint32(os.Getuid()),
		Gid:  uint32(os.Getgid()),
	}
}

示例#28
文件: ro.go 项目: camlistore/camlistore

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
}

示例#29
文件: psnotify_test.go 项目: BarthV/gosigar

func skipTest(t *testing.T) bool {
	if runtime.GOOS == "linux" && os.Getuid() != 0 {
		fmt.Println("SKIP: test must be run as root on linux")
		return true
	}
	return false
}

示例#30
文件: ping_test.go 项目: koron/netx

func skipRawSocketTests() bool {
	if os.Getuid() != 0 {
		return true
	}

	return false
}

展开阅读全文