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) } }
func main() { if !flag.Parsed() { flag.Parse() } var regexHandler = NewHttpHandlerRegexMatcher() http.Handle("/", http.StripPrefix(*prefix, regexHandler)) regexHandler.Handle("/test", HttpHandlerRestHandler{5}) regexHandler.Handle("/test/", HttpHandlerRestHandler{5}) regexHandler.Handle("/test/{id}", HttpHandlerRestHandler{5}) regexHandler.Handle("/ses/{request}", oauthFlowHandler{}) var socket = *socket os.Remove(socket) oldUmask := syscall.Umask(000) l, err := net.Listen("unix", socket) syscall.Umask(oldUmask) if err != nil { panic(err) } panic(fcgi.Serve(l, http.DefaultServeMux)) }
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) }
// UnpackTar unpacks the given tar file into the target directory func UnpackTar(r io.Reader, targetDir string, fn UnpackTarTransformFunc) error { // ensure we we extract with the original permissions oldUmask := syscall.Umask(0) defer syscall.Umask(oldUmask) return TarIterate(r, func(tr *tar.Reader, hdr *tar.Header) (err error) { // run tar transform func name := hdr.Name if fn != nil { name, err = fn(hdr.Name) if err != nil { return err } } path := filepath.Join(targetDir, name) mode := hdr.FileInfo().Mode() if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil { return err } switch { case mode.IsDir(): err := os.Mkdir(path, mode) if err != nil { return nil } case IsSymlink(mode): if err := os.Symlink(hdr.Linkname, path); err != nil { return err } case IsDevice(mode): switch { case (mode & os.ModeCharDevice) != 0: mode |= syscall.S_IFCHR case (mode & os.ModeDevice) != 0: mode |= syscall.S_IFBLK } devNum := Makedev(uint32(hdr.Devmajor), uint32(hdr.Devminor)) err = mknod(path, uint32(mode), int(devNum)) if err != nil { return err } case mode.IsRegular(): out, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, mode) if err != nil { return err } defer out.Close() _, err = io.Copy(out, tr) if err != nil { return err } default: return &ErrUnsupportedFileType{path, mode} } return nil }) }
// Setup initializes the proper /dev/console inside the rootfs path func Setup(rootfs, consolePath, mountLabel string) error { oldMask := syscall.Umask(0000) defer syscall.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 := syscall.Mount(consolePath, dest, "bind", syscall.MS_BIND, ""); err != nil { return fmt.Errorf("bind %s to %s %s", consolePath, dest, err) } return nil }
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) } }
func applyLayer() { runtime.LockOSThread() flag.Parse() if err := chroot(flag.Arg(0)); err != nil { fatal(err) } // We need to be able to set any perms oldmask := syscall.Umask(0) defer syscall.Umask(oldmask) tmpDir, err := ioutil.TempDir("/", "temp-docker-extract") if err != nil { fatal(err) } os.Setenv("TMPDIR", tmpDir) size, err := archive.UnpackLayer("/", os.Stdin) os.RemoveAll(tmpDir) if err != nil { fatal(err) } encoder := json.NewEncoder(os.Stdout) if err := encoder.Encode(applyLayerResponse{size}); err != nil { fatal(fmt.Errorf("unable to encode layerSize JSON: %s", err)) } flush(os.Stdout) flush(os.Stdin) os.Exit(0) }
func TestCreate(t *testing.T) { t.Parallel() f := &create1{} mnt, err := fstestutil.MountedT(t, fstestutil.SimpleFS{f}) if err != nil { t.Fatal(err) } defer mnt.Close() // uniform umask needed to make os.Create's 0666 into something // reproducible defer syscall.Umask(syscall.Umask(0022)) ff, err := os.Create(mnt.Dir + "/foo") if err != nil { t.Fatalf("create1 WriteFile: %v", err) } defer ff.Close() err = syscall.Fsync(int(ff.Fd())) if err != nil { t.Fatalf("Fsync = %v", err) } if f.f.RecordedFsync() == (fuse.FsyncRequest{}) { t.Errorf("never received expected fsync call") } ff.Close() }
func newUnixListener(addr string) (net.Listener, error) { if err := syscall.Unlink(addr); err != nil && !os.IsNotExist(err) { return nil, err } // there is no way to specify the unix rights to use when // creating the socket with net.Listener, so we use umask // to create the file without rights and then we chmod // to the desired unix rights. This prevent unwanted // connections between the creation and the chmod mask := syscall.Umask(0777) defer syscall.Umask(mask) l, err := newListener("unix", addr) if err != nil { return nil, err } // only usable by the user who started swarm if err := os.Chmod(addr, 0600); err != nil { return nil, err } return l, nil }
func (ts *HTestSuite) TestUnpackPermissions(c *C) { tarArchive := filepath.Join(c.MkDir(), "foo.tar") canaryName := "foo" canaryPerms := os.FileMode(0644) tmpdir := c.MkDir() err := ioutil.WriteFile(filepath.Join(tmpdir, canaryName), []byte(nil), canaryPerms) c.Assert(err, IsNil) ChDir(tmpdir, func() error { cmd := exec.Command("tar", "cvf", tarArchive, ".") _, err = cmd.CombinedOutput() c.Assert(err, IsNil) return err }) // set crazy umask oldUmask := syscall.Umask(0077) defer syscall.Umask(oldUmask) // unpack unpackdir := c.MkDir() f, err := os.Open(tarArchive) c.Assert(err, IsNil) defer f.Close() UnpackTar(f, unpackdir, nil) st, err := os.Stat(filepath.Join(unpackdir, canaryName)) c.Assert(err, IsNil) c.Assert(st.Mode()&os.ModePerm, Equals, canaryPerms) }
func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) fmt.Fprintf(os.Stderr, "\n %s [OPTIONS]\n\nOptions:\n", os.Args[0]) flag.PrintDefaults() } flag.Parse() version := fmt.Sprintf("async %s", Version) if *printVersion { fmt.Println(version) os.Exit(0) } log.Printf("Starting %s", version) // Good housekeeping for Unix sockets: unlink before binding if *listenNetwork == "unix" { if err := os.Remove(*listenAddr); err != nil && !os.IsNotExist(err) { log.Fatal(err) } } // Change the umask only around net.Listen() oldUmask := syscall.Umask(*listenUmask) listener, err := net.Listen(*listenNetwork, *listenAddr) syscall.Umask(oldUmask) if err != nil { log.Fatal(err) } async := NewASync(*cmdPrefix, *cmdsChanSize) log.Fatal(http.Serve(listener, async)) }
func (f *mknod1) test(path string, t *testing.T) { if os.Getuid() != 0 { t.Logf("skipping unless root") return } defer syscall.Umask(syscall.Umask(0)) err := syscall.Mknod(path+"/node", syscall.S_IFIFO|0666, 123) if err != nil { t.Fatalf("Mknod: %v", err) } gotr := <-f.seen.gotr if gotr == nil { t.Fatalf("no recorded MknodRequest") } if g, e := gotr.Name, "node"; g != e { t.Errorf("got Name = %q; want %q", g, e) } if g, e := gotr.Rdev, uint32(123); g != e { 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.) } else { t.Errorf("got Rdev = %v; want %v", g, e) } } if g, e := gotr.Mode, os.FileMode(os.ModeNamedPipe|0666); g != e { t.Errorf("got Mode = %v; want %v", g, e) } t.Logf("Got request: %#v", gotr) }
func setupUnixHttp(addr string, job *engine.Job) (*HttpServer, error) { r, err := createRouter(job.Eng, job.GetenvBool("Logging"), job.GetenvBool("EnableCors"), job.Getenv("Version")) if err != nil { return nil, err } if err := syscall.Unlink(addr); err != nil && !os.IsNotExist(err) { return nil, err } mask := syscall.Umask(0777) defer syscall.Umask(mask) l, err := newListener("unix", addr, job.GetenvBool("BufferRequests")) if err != nil { return nil, err } if err := setSocketGroup(addr, job.Getenv("SocketGroup")); err != nil { return nil, err } if err := os.Chmod(addr, 0660); err != nil { return nil, err } return &HttpServer{&http.Server{Addr: addr, Handler: r}, l}, nil }
// CopyFileSetPerms copies from src to dst until either EOF is reached // on src or an error occurs. It will create the destination file with // the specified permissions and return the number of bytes written (int64) // and an error (nil if no error). // Note: if destination file exists it will be removed by this routine func CopyFileSetPerms(src, dst string, mode os.FileMode) (int64, error) { cleanSrc := filepath.Clean(src) cleanDst := filepath.Clean(dst) if cleanSrc == cleanDst { return 0, nil } sf, err := os.Open(cleanSrc) if err != nil { return 0, out.WrapErr(err, "Failed to open source file", 4004) } defer sf.Close() if err := os.Remove(cleanDst); err != nil && !os.IsNotExist(err) { return 0, out.WrapErr(err, "Failed to clean/remove destination file", 4005) } oldUmask := syscall.Umask(0) defer syscall.Umask(oldUmask) df, err := os.OpenFile(cleanDst, syscall.O_CREAT|syscall.O_EXCL|syscall.O_APPEND|syscall.O_WRONLY, mode) if err != nil { return 0, out.WrapErr(err, "Failed to create destination file", 4006) } defer df.Close() bytes, err := io.Copy(df, sf) if err != nil { return bytes, out.WrapErr(err, "Failed to copy source file to destination", 4007) } return bytes, nil }
func TestCachePath(t *testing.T) { home, umask := os.Getenv("HOME"), syscall.Umask(0) abs, _ := filepath.Abs(".") defer func() { syscall.Umask(umask) _ = os.RemoveAll(filepath.Join(abs, ".cache")) _ = os.Setenv("HOME", home) }() _ = os.Setenv("HOME", abs) if err := os.Mkdir(filepath.Join(abs, ".cache"), 0777); err != nil { t.Fatal("Could not initialize test") } file := cachePath() if file == nil { t.Fatal("The given file should be ok") } info, err := file.Stat() if err != nil { t.Fatal("I should be able to stat the given file") } name, mode := file.Name(), info.Mode().Perm() _ = file.Close() _ = os.Remove(name) if name != filepath.Join(abs, ".cache", cacheName) { t.Fatal("Unexpected name") } if mode != 0666 { t.Fatal("Given file does not come from hell ;)") } }
func TestCacheBadJson(t *testing.T) { home, umask := os.Getenv("HOME"), syscall.Umask(0) abs, _ := filepath.Abs(".") test := filepath.Join(abs, "test") defer func() { syscall.Umask(umask) _ = os.Setenv("HOME", home) _ = os.Rename(filepath.Join(test, ".cache", cacheName), filepath.Join(test, ".cache", "bad.json")) }() _ = os.Setenv("HOME", test) _ = os.Rename(filepath.Join(test, ".cache", "bad.json"), filepath.Join(test, ".cache", cacheName)) buffer := bytes.NewBuffer([]byte{}) log.SetOutput(buffer) file := getCacheFile() if !file.Valid { t.Fatal("It should be valid") } if !strings.Contains(buffer.String(), "Decoding of cache file failed") { t.Fatal("Wrong log") } }
// This function wraps application with daemonization. // Returns isDaemon value to distinguish parent and daemonized processes. func Daemonize() (isDaemon bool, err error) { const errLoc = "daemonigo.Daemonize()" isDaemon = os.Getenv(EnvVarName) == EnvVarValue log.Println("IsDaemon: ", isDaemon) if WorkDir != "" { if err = os.Chdir(WorkDir); err != nil { err = fmt.Errorf( "%s: changing working directory failed, reason -> %s", errLoc, err.Error(), ) return } } if isDaemon { oldmask := syscall.Umask(int(Umask)) defer syscall.Umask(oldmask) if _, err = syscall.Setsid(); err != nil { err = fmt.Errorf( "%s: setsid failed, reason -> %s", errLoc, err.Error(), ) return } if pidFile, err = lockPidFile(); err != nil { err = fmt.Errorf( "%s: locking PID file failed, reason -> %s", errLoc, err.Error(), ) } } else { flag.Usage = func() { arr := make([]string, 0, len(actions)) for k, _ := range actions { arr = append(arr, k) } fmt.Fprintf(os.Stderr, "Usage: %s {%s}\n", os.Args[0], strings.Join(arr, "|"), ) flag.PrintDefaults() } if !flag.Parsed() { log.Printf(" flag.Parse\n") flag.Parse() } //fmt.Printf("after flag.Parse\n") //fmt.Printf("flag.Arg(0):%s\n", flag.Arg(0)) //action, exist := actions[flag.Arg(0)] action, exist := actions["daemon"] //fmt.Println("exist:", exist) if exist { action() } else { flag.Usage() } } return }
func (d *Directory) Create() error { log.Println("Create directory:", d.Path) oldMode := syscall.Umask(000) err := os.MkdirAll(d.Path, os.ModeDir|0777) syscall.Umask(oldMode) return err }
func (fs *Filesystem) CreateDevice(devpath string, dev int, mode uint32) error { p := fs.absPath(devpath) um := syscall.Umask(0) if err := syscall.Mknod(p, mode, dev); err != nil { return fmt.Errorf("failed to mknod device '%s': %v", p, err) } syscall.Umask(um) return nil }
func actionDump(c *cli.Context) { verbose := c.Bool(dumpFlagVerbose.Name) compress := c.Bool(dumpFlagCompress.Name) cd := c.String(dumpFlagCrashDir.Name) pid := c.Int(dumpFlagPid.Name) when := time.Unix(int64(c.Int(dumpFlagTime.Name)), 0) sig := c.Int(dumpFlagSig.Name) exe := c.String(dumpFlagExe.Name) // Make sure that we are using a sensible umask. oldMask := syscall.Umask(0000) defer syscall.Umask(oldMask) cd = filepath.Join(cd, exe, when.Format(time.RFC3339), fmt.Sprint(pid)) if err := os.MkdirAll(cd, 0755); err != nil { fmt.Fprintf(dumpOutputWriter, "Failed to create crash directory %s [%s]\n", cd, err) } ci := csi.CrashInspector{} if cr, err := ci.Inspect(pid, syscall.Signal(sig)); err != nil { fmt.Fprintf(dumpOutputWriter, "Failed to gather crash meta data [%s]\n", err) } else { if b, err := yaml.Marshal(cr); err != nil { fmt.Fprintf(dumpOutputWriter, "Failed to write crash meta data [%s]\n", err) } else { ry := filepath.Join(cd, "report.yaml") if f, err := os.Create(ry); err != nil { fmt.Fprintf(dumpOutputWriter, "Failed to dump crash report to %s [%s]\n", ry, err) } else { defer f.Close() fmt.Fprintf(f, "%s", b) } } } // And we finally dump the actual core file df := filepath.Join(cd, "core") if f, err := os.Create(df); err != nil { fmt.Fprintf(dumpOutputWriter, "Failed to dump core to %s [%s]", df, err) } else { defer f.Close() // TODO(tvoss): Investigate into syscall.Sendfile and figure out a way // to avoid copying of data to userspace. var dest io.Writer = f if compress { dest = snappy.NewWriter(f) } start := time.Now() n, _ := io.Copy(dest, os.Stdin) elapsed := time.Since(start) if verbose { fmt.Fprintf(dumpOutputWriter, "Wrote %d bytes of core dump to %s in %f seconds", n, df, elapsed.Seconds()) } } }
// Transform the supplied mode by the current umask. func applyUmask(m os.FileMode) os.FileMode { // HACK(jacobsa): Use umask(2) to change and restore the umask in order to // figure out what the mask is. See the listing in `man getumask`. umask := syscall.Umask(0) syscall.Umask(umask) // Apply it. return m &^ os.FileMode(umask) }
// setDefaultUmask sets the umask to 0022 to avoid problems // caused by custom umask func setDefaultUmask() error { desiredUmask := 0022 syscall.Umask(desiredUmask) if umask := syscall.Umask(desiredUmask); umask != desiredUmask { return fmt.Errorf("failed to set umask: expected %#o, got %#o", desiredUmask, umask) } return nil }
func (opens *openSuite) TestOpenDatabaseWorldWritableFail(c *C) { rootDir := filepath.Join(c.MkDir(), "asserts-db") oldUmask := syscall.Umask(0) os.MkdirAll(rootDir, 0777) syscall.Umask(oldUmask) cfg := &asserts.DatabaseConfig{Path: rootDir} db, err := asserts.OpenDatabase(cfg) c.Assert(err, ErrorMatches, "assert database root unexpectedly world-writable: .*") c.Check(db, IsNil) }
func (sdbs *sysDBSuite) TestOpenSysDatabaseKeypairManagerOpenFail(c *C) { // make it not world-writeable oldUmask := syscall.Umask(0) os.MkdirAll(filepath.Join(dirs.SnapAssertsDBDir, "private-keys-v1"), 0777) syscall.Umask(oldUmask) db, err := sysdb.Open() c.Assert(err, ErrorMatches, "assert storage root unexpectedly world-writable: .*") c.Check(db, IsNil) }
func (sdbs *sysDBSuite) TestOpenSysDatabaseBackstoreOpenFail(c *C) { // make it not world-writeable oldUmask := syscall.Umask(0) os.MkdirAll(filepath.Join(dirs.SnapAssertsDBDir, "asserts-v0"), 0777) syscall.Umask(oldUmask) db, err := asserts.OpenSysDatabase(dirs.SnapTrustedAccountKey) c.Assert(err, ErrorMatches, "assert storage root unexpectedly world-writable: .*") c.Check(db, IsNil) }
func (fsbss *fsKeypairMgrSuite) TestOpenWorldWritableFail(c *C) { topDir := filepath.Join(c.MkDir(), "asserts-db") // make it world-writable oldUmask := syscall.Umask(0) os.MkdirAll(filepath.Join(topDir, "private-keys-v0"), 0777) syscall.Umask(oldUmask) bs, err := asserts.OpenFSKeypairManager(topDir) c.Assert(err, ErrorMatches, "assert storage root unexpectedly world-writable: .*") c.Check(bs, IsNil) }
// this is copy from old libcontainer nodes.go func createDeviceNodes(rootfs string, nodesToCreate []*configs.Device) error { oldMask := syscall.Umask(0000) defer syscall.Umask(oldMask) for _, node := range nodesToCreate { if err := createDeviceNode(rootfs, node); err != nil { return err } } return nil }
func main() { mask := syscall.Umask(0) defer syscall.Umask(mask) err := os.MkdirAll("/tmp/gotest/", 0777) if err != nil { panic(err) } fmt.Println("Mkdir /tmp/gotest/") }
// Create the device nodes in the container. func createDevices(config *configs.Config) error { oldMask := syscall.Umask(0000) for _, node := range config.Devices { if err := createDeviceNode(config.Rootfs, node); err != nil { syscall.Umask(oldMask) return err } } syscall.Umask(oldMask) return nil }
// ApplyLayer parses a diff in the standard layer format from `layer`, and // applies it to the directory `dest`. func ApplyLayer(dest string, layer ArchiveReader) error { dest = filepath.Clean(dest) // We need to be able to set any perms oldmask := syscall.Umask(0) defer syscall.Umask(oldmask) layer, err := DecompressStream(layer) if err != nil { return err } return UnpackLayer(dest, layer) }