// NewBadTempFile detects direct writes to predictable path in temporary directory
559161
func NewBadTempFile(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
	calls := gosec.NewCallList()
	calls.Add("io/ioutil", "WriteFile")
	calls.Add("os", "Create")
	return &badTempFile{
		calls: calls,
		args:  regexp.MustCompile(`^/tmp/.*$|^/var/tmp/.*$`),
		MetaData: gosec.MetaData{
			ID:         id,
			Severity:   gosec.Medium,
			Confidence: gosec.High,
			What:       "File creation in shared tmp directory without using ioutil.Tempfile",
		},
	}, []ast.Node{(*ast.CallExpr)(nil)}
}
916978
func TempFile(i []byte) (name string, err error) {
	// Create temp file
	var f *os.File
	if f, err = ioutil.TempFile(os.TempDir(), "astitools"); err != nil {
		err = errors.Wrap(err, "creating temp file failed")
		return
	}
	name = f.Name()
	defer f.Close()

	// Write
	if _, err = f.Write(i); err != nil {
		err = errors.Wrapf(err, "writing to %s failed", name)
		return
	}
	return
}
164764
func New(basePath string) (*bytes.Buffer, error) {
	fi, err := os.Stat(basePath)
	if err != nil {
		return nil, err
	}
	if !fi.IsDir() {
		return nil, fmt.Errorf("path %q is not a directory, which is required for a Firefox profile", basePath)
	}

	buf := new(bytes.Buffer)
	w := zip.NewWriter(buf)
	err = filepath.Walk(basePath, func(filePath string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.Mode().IsRegular() {
			return nil
		}

		zipFI, err := zip.FileInfoHeader(info)
		if err != nil {
			return err
		}

		// Strip the prefix from the filename (and the trailing directory
		// separator) so that the files are at the root of the zip file.
		zipFI.Name = filePath[len(basePath)+1:]

		// Without this, the Java zip reader throws a java.util.zip.ZipException:
		// "only DEFLATED entries can have EXT descriptor".
		zipFI.Method = zip.Deflate

		w, err := w.CreateHeader(zipFI)
		if err != nil {
			return err
		}

		f, err := os.Open(filePath)
		if err != nil {
			return err
		}
		defer f.Close()

		_, err = io.Copy(w, bufio.NewReader(f))
		return err
	})
	if err != nil {
		return nil, err
	}
	if err := w.Close(); err != nil {
		return nil, err
	}
	return buf, nil
}
1034743
func (c *SSHCommand) writeTemporaryFile(name string, data []byte, perms os.FileMode) (string, error, func() error) {
	// default closer to prevent panic
	closer := func() error { return nil }

	f, err := ioutil.TempFile("", name)
	if err != nil {
		return "", errors.Wrap(err, "creating temporary file"), closer
	}

	closer = func() error { return os.Remove(f.Name()) }

	if err := ioutil.WriteFile(f.Name(), data, perms); err != nil {
		return "", errors.Wrap(err, "writing temporary key"), closer
	}

	if err := f.Close(); err != nil {
		return "", errors.Wrap(err, "closing temporary key"), closer
	}

	return f.Name(), nil, closer
}
1322620
func TempDir(dir, prefix string) (name string, err error) {
	name, err = ioutil_base.TempDir(dir, prefix)
	if err != nil {
		return "", errors.Wrapf(err,
			"failed to make temp dir in %q with prefix %q",
			dir, prefix)
	}
	return name, nil
}
201166
func tempFilePath() string {
	f, _ := ioutil.TempFile("", "bolt-")
	if err := f.Close(); err != nil {
		log.Fatal(err)
	}
	if err := os.Remove(f.Name()); err != nil {
		log.Fatal(err)
	}
	return f.Name()
}
386457
func Temporary() option {
	return func(w *Writer) {
		w.ext = tsm1.TSMFileExtension + "." + tsm1.TmpTSMFileExtension
	}
}
1032208
func (w *AtomicWriter) newTimestampDir() (string, error) {
	tsDir, err := ioutil.TempDir(w.targetDir, time.Now().UTC().Format("..2006_01_02_15_04_05."))
	if err != nil {
		klog.Errorf("%s: unable to create new temp directory: %v", w.logContext, err)
		return "", err
	}

	// 0755 permissions are needed to allow 'group' and 'other' to recurse the
	// directory tree.  do a chmod here to ensure that permissions are set correctly
	// regardless of the process' umask.
	err = os.Chmod(tsDir, 0755)
	if err != nil {
		klog.Errorf("%s: unable to set mode on new temp directory: %v", w.logContext, err)
		return "", err
	}

	return tsDir, nil
}
348421
func (u *Updater) tempDir() string {
	tmpDir := util.TempPath("", "KeybaseUpdater.")
	if err := util.MakeDirs(tmpDir, 0700, u.log); err != nil {
		u.log.Warningf("Error trying to create temp dir: %s", err)
		return ""
	}
	return tmpDir
}
473802
func removeTempFile(dir, file string) {
	changeDir(dir)
	if err := os.Remove(file); err != nil {
		beeLogger.Log.Warnf("Could not remove temporary file: %s", err)
	}
}
855879
func TempFile(stream io.ReadCloser) (string, error) {
	f, err := ioutil.TempFile(os.TempDir(), "")
	if err != nil {
		return "", err
	}
	defer f.Close()
	defer stream.Close()

	_, err = io.Copy(f, stream)
	return f.Name(), err
}
832332
func New(t *testing.T) *GopathTest {
	base, err := ioutil.TempDir(os.TempDir(), "vendor_")
	if err != nil {
		t.Fatal(err)
	}
	wd, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}
	g := &GopathTest{
		T:    t,
		base: base,

		initPath: wd,
	}
	g.mkdir("src")
	os.Setenv("GOPATH", g.base)
	return g
}
1029791
func NewRFile(f *File) (RFile, error) {
	data, err := fileData(f)
	if err != nil {
		return nil, err
	}
	return &file{f: f, data: data, readable: true}, nil
}
389633
func (s *sharedPullerState) tempFile() (io.WriterAt, error) {
	s.mut.Lock()
	defer s.mut.Unlock()

	// If we've already hit an error, return early
	if s.err != nil {
		return nil, s.err
	}

	// If the temp file is already open, return the file descriptor
	if s.fd != nil {
		return lockedWriterAt{&s.mut, s.fd}, nil
	}

	// Ensure that the parent directory is writable. This is
	// osutil.InWritableDir except we need to do more stuff so we duplicate it
	// here.
	dir := filepath.Dir(s.tempName)
	if info, err := s.fs.Stat(dir); err != nil {
		s.failLocked(errors.Wrap(err, "ensuring parent dir is writeable"))
		return nil, err
	} else if info.Mode()&0200 == 0 {
		err := s.fs.Chmod(dir, 0755)
		if !s.ignorePerms && err == nil {
			defer func() {
				err := s.fs.Chmod(dir, info.Mode()&fs.ModePerm)
				if err != nil {
					panic(err)
				}
			}()
		}
	}

	// The permissions to use for the temporary file should be those of the
	// final file, except we need user read & write at minimum. The
	// permissions will be set to the final value later, but in the meantime
	// we don't want to have a temporary file with looser permissions than
	// the final outcome.
	mode := fs.FileMode(s.file.Permissions) | 0600
	if s.ignorePerms {
		// When ignorePerms is set we use a very permissive mode and let the
		// system umask filter it.
		mode = 0666
	}

	// Attempt to create the temp file
	// RDWR because of issue #2994.
	flags := fs.OptReadWrite
	if s.reused == 0 {
		flags |= fs.OptCreate | fs.OptExclusive
	} else if !s.ignorePerms {
		// With sufficiently bad luck when exiting or crashing, we may have
		// had time to chmod the temp file to read only state but not yet
		// moved it to its final name. This leaves us with a read only temp
		// file that we're going to try to reuse. To handle that, we need to
		// make sure we have write permissions on the file before opening it.
		//
		// When ignorePerms is set we trust that the permissions are fine
		// already and make no modification, as we would otherwise override
		// what the umask dictates.

		if err := s.fs.Chmod(s.tempName, mode); err != nil {
			s.failLocked(errors.Wrap(err, "setting perms on temp file"))
			return nil, err
		}
	}
	fd, err := s.fs.OpenFile(s.tempName, flags, mode)
	if err != nil {
		s.failLocked(errors.Wrap(err, "opening temp file"))
		return nil, err
	}

	// Hide the temporary file
	s.fs.Hide(s.tempName)

	// Don't truncate symlink files, as that will mean that the path will
	// contain a bunch of nulls.
	if s.sparse && !s.file.IsSymlink() {
		// Truncate sets the size of the file. This creates a sparse file or a
		// space reservation, depending on the underlying filesystem.
		if err := fd.Truncate(s.file.Size); err != nil {
			// The truncate call failed. That can happen in some cases when
			// space reservation isn't possible or over some network
			// filesystems... This generally doesn't matter.

			if s.reused > 0 {
				// ... but if we are attempting to reuse a file we have a
				// corner case when the old file is larger than the new one
				// and we can't just overwrite blocks and let the old data
				// linger at the end. In this case we attempt a delete of
				// the file and hope for better luck next time, when we
				// should come around with s.reused == 0.

				fd.Close()

				if remErr := s.fs.Remove(s.tempName); remErr != nil {
					l.Debugln("failed to remove temporary file:", remErr)
				}

				s.failLocked(err)
				return nil, err
			}
		}
	}

	// Same fd will be used by all writers
	s.fd = fd

	return lockedWriterAt{&s.mut, s.fd}, nil
}
1341999
func TempPath(tempDir string, prefix string) string {
	if tempDir == "" {
		tempDir = os.TempDir()
	}
	filename, err := RandomID(prefix)
	if err != nil {
		// We had an error getting random bytes, we'll use current nanoseconds
		filename = fmt.Sprintf("%s%d", prefix, time.Now().UnixNano())
	}
	path := filepath.Join(tempDir, filename)
	return path
}
1104139
func NewBadParameterError(param string, actual interface{}) BadParameterError {
	return BadParameterError{parameter: param, value: actual}
}
1137096
func WriteTempDockerfile(rc io.ReadCloser) (dockerfileDir string, err error) {
	// err is a named return value, due to the defer call below.
	dockerfileDir, err = ioutil.TempDir("", "docker-build-tempdockerfile-")
	if err != nil {
		return "", errors.Errorf("unable to create temporary context directory: %v", err)
	}
	defer func() {
		if err != nil {
			os.RemoveAll(dockerfileDir)
		}
	}()

	f, err := os.Create(filepath.Join(dockerfileDir, DefaultDockerfileName))
	if err != nil {
		return "", err
	}
	defer f.Close()
	if _, err := io.Copy(f, rc); err != nil {
		return "", err
	}
	return dockerfileDir, rc.Close()
}