Source file src/os/file.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package os provides a platform-independent interface to operating system
     6  // functionality. The design is Unix-like, although the error handling is
     7  // Go-like; failing calls return values of type error rather than error numbers.
     8  // Often, more information is available within the error. For example,
     9  // if a call that takes a file name fails, such as [Open] or [Stat], the error
    10  // will include the failing file name when printed and will be of type
    11  // [*PathError], which may be unpacked for more information.
    12  //
    13  // The os interface is intended to be uniform across all operating systems.
    14  // Features not generally available appear in the system-specific package syscall.
    15  //
    16  // Here is a simple example, opening a file and reading some of it.
    17  //
    18  //	file, err := os.Open("file.go") // For read access.
    19  //	if err != nil {
    20  //		log.Fatal(err)
    21  //	}
    22  //
    23  // If the open fails, the error string will be self-explanatory, like
    24  //
    25  //	open file.go: no such file or directory
    26  //
    27  // The file's data can then be read into a slice of bytes. Read and
    28  // Write take their byte counts from the length of the argument slice.
    29  //
    30  //	data := make([]byte, 100)
    31  //	count, err := file.Read(data)
    32  //	if err != nil {
    33  //		log.Fatal(err)
    34  //	}
    35  //	fmt.Printf("read %d bytes: %q\n", count, data[:count])
    36  //
    37  // # Concurrency
    38  //
    39  // The methods of [File] correspond to file system operations. All are
    40  // safe for concurrent use. The maximum number of concurrent
    41  // operations on a File may be limited by the OS or the system. The
    42  // number should be high, but exceeding it may degrade performance or
    43  // cause other issues.
    44  package os
    45  
    46  import (
    47  	"errors"
    48  	"internal/filepathlite"
    49  	"internal/poll"
    50  	"internal/testlog"
    51  	"io"
    52  	"io/fs"
    53  	"runtime"
    54  	"syscall"
    55  	"time"
    56  	"unsafe"
    57  )
    58  
    59  // Name returns the name of the file as presented to Open.
    60  //
    61  // It is safe to call Name after [Close].
    62  func (f *File) Name() string { return f.name }
    63  
    64  // Stdin, Stdout, and Stderr are open Files pointing to the standard input,
    65  // standard output, and standard error file descriptors.
    66  //
    67  // Note that the Go runtime writes to standard error for panics and crashes;
    68  // closing Stderr may cause those messages to go elsewhere, perhaps
    69  // to a file opened later.
    70  var (
    71  	Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
    72  	Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
    73  	Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
    74  )
    75  
    76  // Flags to OpenFile wrapping those of the underlying system. Not all
    77  // flags may be implemented on a given system.
    78  const (
    79  	// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
    80  	O_RDONLY int = syscall.O_RDONLY // open the file read-only.
    81  	O_WRONLY int = syscall.O_WRONLY // open the file write-only.
    82  	O_RDWR   int = syscall.O_RDWR   // open the file read-write.
    83  	// The remaining values may be or'ed in to control behavior.
    84  	O_APPEND int = syscall.O_APPEND // append data to the file when writing.
    85  	O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
    86  	O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist.
    87  	O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
    88  	O_TRUNC  int = syscall.O_TRUNC  // truncate regular writable file when opened.
    89  )
    90  
    91  // Seek whence values.
    92  //
    93  // Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd.
    94  const (
    95  	SEEK_SET int = 0 // seek relative to the origin of the file
    96  	SEEK_CUR int = 1 // seek relative to the current offset
    97  	SEEK_END int = 2 // seek relative to the end
    98  )
    99  
   100  // LinkError records an error during a link or symlink or rename
   101  // system call and the paths that caused it.
   102  type LinkError struct {
   103  	Op  string
   104  	Old string
   105  	New string
   106  	Err error
   107  }
   108  
   109  func (e *LinkError) Error() string {
   110  	return e.Op + " " + e.Old + " " + e.New + ": " + e.Err.Error()
   111  }
   112  
   113  func (e *LinkError) Unwrap() error {
   114  	return e.Err
   115  }
   116  
   117  // Read reads up to len(b) bytes from the File and stores them in b.
   118  // It returns the number of bytes read and any error encountered.
   119  // At end of file, Read returns 0, io.EOF.
   120  func (f *File) Read(b []byte) (n int, err error) {
   121  	if err := f.checkValid("read"); err != nil {
   122  		return 0, err
   123  	}
   124  	n, e := f.read(b)
   125  	return n, f.wrapErr("read", e)
   126  }
   127  
   128  // ReadAt reads len(b) bytes from the File starting at byte offset off.
   129  // It returns the number of bytes read and the error, if any.
   130  // ReadAt always returns a non-nil error when n < len(b).
   131  // At end of file, that error is io.EOF.
   132  func (f *File) ReadAt(b []byte, off int64) (n int, err error) {
   133  	if err := f.checkValid("read"); err != nil {
   134  		return 0, err
   135  	}
   136  
   137  	if off < 0 {
   138  		return 0, &PathError{Op: "readat", Path: f.name, Err: errors.New("negative offset")}
   139  	}
   140  
   141  	for len(b) > 0 {
   142  		m, e := f.pread(b, off)
   143  		if e != nil {
   144  			err = f.wrapErr("read", e)
   145  			break
   146  		}
   147  		n += m
   148  		b = b[m:]
   149  		off += int64(m)
   150  	}
   151  	return
   152  }
   153  
   154  // ReadFrom implements io.ReaderFrom.
   155  func (f *File) ReadFrom(r io.Reader) (n int64, err error) {
   156  	if err := f.checkValid("write"); err != nil {
   157  		return 0, err
   158  	}
   159  	n, handled, e := f.readFrom(r)
   160  	if !handled {
   161  		return genericReadFrom(f, r) // without wrapping
   162  	}
   163  	return n, f.wrapErr("write", e)
   164  }
   165  
   166  // noReadFrom can be embedded alongside another type to
   167  // hide the ReadFrom method of that other type.
   168  type noReadFrom struct{}
   169  
   170  // ReadFrom hides another ReadFrom method.
   171  // It should never be called.
   172  func (noReadFrom) ReadFrom(io.Reader) (int64, error) {
   173  	panic("can't happen")
   174  }
   175  
   176  // fileWithoutReadFrom implements all the methods of *File other
   177  // than ReadFrom. This is used to permit ReadFrom to call io.Copy
   178  // without leading to a recursive call to ReadFrom.
   179  type fileWithoutReadFrom struct {
   180  	noReadFrom
   181  	*File
   182  }
   183  
   184  func genericReadFrom(f *File, r io.Reader) (int64, error) {
   185  	return io.Copy(fileWithoutReadFrom{File: f}, r)
   186  }
   187  
   188  // Write writes len(b) bytes from b to the File.
   189  // It returns the number of bytes written and an error, if any.
   190  // Write returns a non-nil error when n != len(b).
   191  func (f *File) Write(b []byte) (n int, err error) {
   192  	if err := f.checkValid("write"); err != nil {
   193  		return 0, err
   194  	}
   195  	n, e := f.write(b)
   196  	if n < 0 {
   197  		n = 0
   198  	}
   199  	if n != len(b) {
   200  		err = io.ErrShortWrite
   201  	}
   202  
   203  	epipecheck(f, e)
   204  
   205  	if e != nil {
   206  		err = f.wrapErr("write", e)
   207  	}
   208  
   209  	return n, err
   210  }
   211  
   212  var errWriteAtInAppendMode = errors.New("os: invalid use of WriteAt on file opened with O_APPEND")
   213  
   214  // WriteAt writes len(b) bytes to the File starting at byte offset off.
   215  // It returns the number of bytes written and an error, if any.
   216  // WriteAt returns a non-nil error when n != len(b).
   217  //
   218  // If file was opened with the O_APPEND flag, WriteAt returns an error.
   219  func (f *File) WriteAt(b []byte, off int64) (n int, err error) {
   220  	if err := f.checkValid("write"); err != nil {
   221  		return 0, err
   222  	}
   223  	if f.appendMode {
   224  		return 0, errWriteAtInAppendMode
   225  	}
   226  
   227  	if off < 0 {
   228  		return 0, &PathError{Op: "writeat", Path: f.name, Err: errors.New("negative offset")}
   229  	}
   230  
   231  	for len(b) > 0 {
   232  		m, e := f.pwrite(b, off)
   233  		if e != nil {
   234  			err = f.wrapErr("write", e)
   235  			break
   236  		}
   237  		n += m
   238  		b = b[m:]
   239  		off += int64(m)
   240  	}
   241  	return
   242  }
   243  
   244  // WriteTo implements io.WriterTo.
   245  func (f *File) WriteTo(w io.Writer) (n int64, err error) {
   246  	if err := f.checkValid("read"); err != nil {
   247  		return 0, err
   248  	}
   249  	n, handled, e := f.writeTo(w)
   250  	if handled {
   251  		return n, f.wrapErr("read", e)
   252  	}
   253  	return genericWriteTo(f, w) // without wrapping
   254  }
   255  
   256  // noWriteTo can be embedded alongside another type to
   257  // hide the WriteTo method of that other type.
   258  type noWriteTo struct{}
   259  
   260  // WriteTo hides another WriteTo method.
   261  // It should never be called.
   262  func (noWriteTo) WriteTo(io.Writer) (int64, error) {
   263  	panic("can't happen")
   264  }
   265  
   266  // fileWithoutWriteTo implements all the methods of *File other
   267  // than WriteTo. This is used to permit WriteTo to call io.Copy
   268  // without leading to a recursive call to WriteTo.
   269  type fileWithoutWriteTo struct {
   270  	noWriteTo
   271  	*File
   272  }
   273  
   274  func genericWriteTo(f *File, w io.Writer) (int64, error) {
   275  	return io.Copy(w, fileWithoutWriteTo{File: f})
   276  }
   277  
   278  // Seek sets the offset for the next Read or Write on file to offset, interpreted
   279  // according to whence: 0 means relative to the origin of the file, 1 means
   280  // relative to the current offset, and 2 means relative to the end.
   281  // It returns the new offset and an error, if any.
   282  // The behavior of Seek on a file opened with O_APPEND is not specified.
   283  func (f *File) Seek(offset int64, whence int) (ret int64, err error) {
   284  	if err := f.checkValid("seek"); err != nil {
   285  		return 0, err
   286  	}
   287  	r, e := f.seek(offset, whence)
   288  	if e == nil && f.dirinfo.Load() != nil && r != 0 {
   289  		e = syscall.EISDIR
   290  	}
   291  	if e != nil {
   292  		return 0, f.wrapErr("seek", e)
   293  	}
   294  	return r, nil
   295  }
   296  
   297  // WriteString is like Write, but writes the contents of string s rather than
   298  // a slice of bytes.
   299  func (f *File) WriteString(s string) (n int, err error) {
   300  	b := unsafe.Slice(unsafe.StringData(s), len(s))
   301  	return f.Write(b)
   302  }
   303  
   304  // Mkdir creates a new directory with the specified name and permission
   305  // bits (before umask).
   306  // If there is an error, it will be of type *PathError.
   307  func Mkdir(name string, perm FileMode) error {
   308  	longName := fixLongPath(name)
   309  	e := ignoringEINTR(func() error {
   310  		return syscall.Mkdir(longName, syscallMode(perm))
   311  	})
   312  
   313  	if e != nil {
   314  		return &PathError{Op: "mkdir", Path: name, Err: e}
   315  	}
   316  
   317  	// mkdir(2) itself won't handle the sticky bit on *BSD and Solaris
   318  	if !supportsCreateWithStickyBit && perm&ModeSticky != 0 {
   319  		e = setStickyBit(name)
   320  
   321  		if e != nil {
   322  			Remove(name)
   323  			return e
   324  		}
   325  	}
   326  
   327  	return nil
   328  }
   329  
   330  // setStickyBit adds ModeSticky to the permission bits of path, non atomic.
   331  func setStickyBit(name string) error {
   332  	fi, err := Stat(name)
   333  	if err != nil {
   334  		return err
   335  	}
   336  	return Chmod(name, fi.Mode()|ModeSticky)
   337  }
   338  
   339  // Chdir changes the current working directory to the named directory.
   340  // If there is an error, it will be of type *PathError.
   341  func Chdir(dir string) error {
   342  	if e := syscall.Chdir(dir); e != nil {
   343  		testlog.Open(dir) // observe likely non-existent directory
   344  		return &PathError{Op: "chdir", Path: dir, Err: e}
   345  	}
   346  	if runtime.GOOS == "windows" {
   347  		getwdCache.Lock()
   348  		getwdCache.dir = dir
   349  		getwdCache.Unlock()
   350  	}
   351  	if log := testlog.Logger(); log != nil {
   352  		wd, err := Getwd()
   353  		if err == nil {
   354  			log.Chdir(wd)
   355  		}
   356  	}
   357  	return nil
   358  }
   359  
   360  // Open opens the named file for reading. If successful, methods on
   361  // the returned file can be used for reading; the associated file
   362  // descriptor has mode O_RDONLY.
   363  // If there is an error, it will be of type *PathError.
   364  func Open(name string) (*File, error) {
   365  	return OpenFile(name, O_RDONLY, 0)
   366  }
   367  
   368  // Create creates or truncates the named file. If the file already exists,
   369  // it is truncated. If the file does not exist, it is created with mode 0o666
   370  // (before umask). If successful, methods on the returned File can
   371  // be used for I/O; the associated file descriptor has mode O_RDWR.
   372  // If there is an error, it will be of type *PathError.
   373  func Create(name string) (*File, error) {
   374  	return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
   375  }
   376  
   377  // OpenFile is the generalized open call; most users will use Open
   378  // or Create instead. It opens the named file with specified flag
   379  // (O_RDONLY etc.). If the file does not exist, and the O_CREATE flag
   380  // is passed, it is created with mode perm (before umask). If successful,
   381  // methods on the returned File can be used for I/O.
   382  // If there is an error, it will be of type *PathError.
   383  func OpenFile(name string, flag int, perm FileMode) (*File, error) {
   384  	testlog.Open(name)
   385  	f, err := openFileNolog(name, flag, perm)
   386  	if err != nil {
   387  		return nil, err
   388  	}
   389  	f.appendMode = flag&O_APPEND != 0
   390  
   391  	return f, nil
   392  }
   393  
   394  // openDir opens a file which is assumed to be a directory. As such, it skips
   395  // the syscalls that make the file descriptor non-blocking as these take time
   396  // and will fail on file descriptors for directories.
   397  func openDir(name string) (*File, error) {
   398  	testlog.Open(name)
   399  	return openDirNolog(name)
   400  }
   401  
   402  // lstat is overridden in tests.
   403  var lstat = Lstat
   404  
   405  // Rename renames (moves) oldpath to newpath.
   406  // If newpath already exists and is not a directory, Rename replaces it.
   407  // OS-specific restrictions may apply when oldpath and newpath are in different directories.
   408  // Even within the same directory, on non-Unix platforms Rename is not an atomic operation.
   409  // If there is an error, it will be of type *LinkError.
   410  func Rename(oldpath, newpath string) error {
   411  	return rename(oldpath, newpath)
   412  }
   413  
   414  // Readlink returns the destination of the named symbolic link.
   415  // If there is an error, it will be of type *PathError.
   416  //
   417  // If the link destination is relative, Readlink returns the relative path
   418  // without resolving it to an absolute one.
   419  func Readlink(name string) (string, error) {
   420  	return readlink(name)
   421  }
   422  
   423  // Many functions in package syscall return a count of -1 instead of 0.
   424  // Using fixCount(call()) instead of call() corrects the count.
   425  func fixCount(n int, err error) (int, error) {
   426  	if n < 0 {
   427  		n = 0
   428  	}
   429  	return n, err
   430  }
   431  
   432  // checkWrapErr is the test hook to enable checking unexpected wrapped errors of poll.ErrFileClosing.
   433  // It is set to true in the export_test.go for tests (including fuzz tests).
   434  var checkWrapErr = false
   435  
   436  // wrapErr wraps an error that occurred during an operation on an open file.
   437  // It passes io.EOF through unchanged, otherwise converts
   438  // poll.ErrFileClosing to ErrClosed and wraps the error in a PathError.
   439  func (f *File) wrapErr(op string, err error) error {
   440  	if err == nil || err == io.EOF {
   441  		return err
   442  	}
   443  	if err == poll.ErrFileClosing {
   444  		err = ErrClosed
   445  	} else if checkWrapErr && errors.Is(err, poll.ErrFileClosing) {
   446  		panic("unexpected error wrapping poll.ErrFileClosing: " + err.Error())
   447  	}
   448  	return &PathError{Op: op, Path: f.name, Err: err}
   449  }
   450  
   451  // TempDir returns the default directory to use for temporary files.
   452  //
   453  // On Unix systems, it returns $TMPDIR if non-empty, else /tmp.
   454  // On Windows, it uses GetTempPath, returning the first non-empty
   455  // value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory.
   456  // On Plan 9, it returns /tmp.
   457  //
   458  // The directory is neither guaranteed to exist nor have accessible
   459  // permissions.
   460  func TempDir() string {
   461  	return tempDir()
   462  }
   463  
   464  // UserCacheDir returns the default root directory to use for user-specific
   465  // cached data. Users should create their own application-specific subdirectory
   466  // within this one and use that.
   467  //
   468  // On Unix systems, it returns $XDG_CACHE_HOME as specified by
   469  // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if
   470  // non-empty, else $HOME/.cache.
   471  // On Darwin, it returns $HOME/Library/Caches.
   472  // On Windows, it returns %LocalAppData%.
   473  // On Plan 9, it returns $home/lib/cache.
   474  //
   475  // If the location cannot be determined (for example, $HOME is not defined),
   476  // then it will return an error.
   477  func UserCacheDir() (string, error) {
   478  	var dir string
   479  
   480  	switch runtime.GOOS {
   481  	case "windows":
   482  		dir = Getenv("LocalAppData")
   483  		if dir == "" {
   484  			return "", errors.New("%LocalAppData% is not defined")
   485  		}
   486  
   487  	case "darwin", "ios":
   488  		dir = Getenv("HOME")
   489  		if dir == "" {
   490  			return "", errors.New("$HOME is not defined")
   491  		}
   492  		dir += "/Library/Caches"
   493  
   494  	case "plan9":
   495  		dir = Getenv("home")
   496  		if dir == "" {
   497  			return "", errors.New("$home is not defined")
   498  		}
   499  		dir += "/lib/cache"
   500  
   501  	default: // Unix
   502  		dir = Getenv("XDG_CACHE_HOME")
   503  		if dir == "" {
   504  			dir = Getenv("HOME")
   505  			if dir == "" {
   506  				return "", errors.New("neither $XDG_CACHE_HOME nor $HOME are defined")
   507  			}
   508  			dir += "/.cache"
   509  		}
   510  	}
   511  
   512  	return dir, nil
   513  }
   514  
   515  // UserConfigDir returns the default root directory to use for user-specific
   516  // configuration data. Users should create their own application-specific
   517  // subdirectory within this one and use that.
   518  //
   519  // On Unix systems, it returns $XDG_CONFIG_HOME as specified by
   520  // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if
   521  // non-empty, else $HOME/.config.
   522  // On Darwin, it returns $HOME/Library/Application Support.
   523  // On Windows, it returns %AppData%.
   524  // On Plan 9, it returns $home/lib.
   525  //
   526  // If the location cannot be determined (for example, $HOME is not defined),
   527  // then it will return an error.
   528  func UserConfigDir() (string, error) {
   529  	var dir string
   530  
   531  	switch runtime.GOOS {
   532  	case "windows":
   533  		dir = Getenv("AppData")
   534  		if dir == "" {
   535  			return "", errors.New("%AppData% is not defined")
   536  		}
   537  
   538  	case "darwin", "ios":
   539  		dir = Getenv("HOME")
   540  		if dir == "" {
   541  			return "", errors.New("$HOME is not defined")
   542  		}
   543  		dir += "/Library/Application Support"
   544  
   545  	case "plan9":
   546  		dir = Getenv("home")
   547  		if dir == "" {
   548  			return "", errors.New("$home is not defined")
   549  		}
   550  		dir += "/lib"
   551  
   552  	default: // Unix
   553  		dir = Getenv("XDG_CONFIG_HOME")
   554  		if dir == "" {
   555  			dir = Getenv("HOME")
   556  			if dir == "" {
   557  				return "", errors.New("neither $XDG_CONFIG_HOME nor $HOME are defined")
   558  			}
   559  			dir += "/.config"
   560  		}
   561  	}
   562  
   563  	return dir, nil
   564  }
   565  
   566  // UserHomeDir returns the current user's home directory.
   567  //
   568  // On Unix, including macOS, it returns the $HOME environment variable.
   569  // On Windows, it returns %USERPROFILE%.
   570  // On Plan 9, it returns the $home environment variable.
   571  //
   572  // If the expected variable is not set in the environment, UserHomeDir
   573  // returns either a platform-specific default value or a non-nil error.
   574  func UserHomeDir() (string, error) {
   575  	env, enverr := "HOME", "$HOME"
   576  	switch runtime.GOOS {
   577  	case "windows":
   578  		env, enverr = "USERPROFILE", "%userprofile%"
   579  	case "plan9":
   580  		env, enverr = "home", "$home"
   581  	}
   582  	if v := Getenv(env); v != "" {
   583  		return v, nil
   584  	}
   585  	// On some geese the home directory is not always defined.
   586  	switch runtime.GOOS {
   587  	case "android":
   588  		return "/sdcard", nil
   589  	case "ios":
   590  		return "/", nil
   591  	}
   592  	return "", errors.New(enverr + " is not defined")
   593  }
   594  
   595  // Chmod changes the mode of the named file to mode.
   596  // If the file is a symbolic link, it changes the mode of the link's target.
   597  // If there is an error, it will be of type *PathError.
   598  //
   599  // A different subset of the mode bits are used, depending on the
   600  // operating system.
   601  //
   602  // On Unix, the mode's permission bits, ModeSetuid, ModeSetgid, and
   603  // ModeSticky are used.
   604  //
   605  // On Windows, only the 0o200 bit (owner writable) of mode is used; it
   606  // controls whether the file's read-only attribute is set or cleared.
   607  // The other bits are currently unused. For compatibility with Go 1.12
   608  // and earlier, use a non-zero mode. Use mode 0o400 for a read-only
   609  // file and 0o600 for a readable+writable file.
   610  //
   611  // On Plan 9, the mode's permission bits, ModeAppend, ModeExclusive,
   612  // and ModeTemporary are used.
   613  func Chmod(name string, mode FileMode) error { return chmod(name, mode) }
   614  
   615  // Chmod changes the mode of the file to mode.
   616  // If there is an error, it will be of type *PathError.
   617  func (f *File) Chmod(mode FileMode) error { return f.chmod(mode) }
   618  
   619  // SetDeadline sets the read and write deadlines for a File.
   620  // It is equivalent to calling both SetReadDeadline and SetWriteDeadline.
   621  //
   622  // Only some kinds of files support setting a deadline. Calls to SetDeadline
   623  // for files that do not support deadlines will return ErrNoDeadline.
   624  // On most systems ordinary files do not support deadlines, but pipes do.
   625  //
   626  // A deadline is an absolute time after which I/O operations fail with an
   627  // error instead of blocking. The deadline applies to all future and pending
   628  // I/O, not just the immediately following call to Read or Write.
   629  // After a deadline has been exceeded, the connection can be refreshed
   630  // by setting a deadline in the future.
   631  //
   632  // If the deadline is exceeded a call to Read or Write or to other I/O
   633  // methods will return an error that wraps ErrDeadlineExceeded.
   634  // This can be tested using errors.Is(err, os.ErrDeadlineExceeded).
   635  // That error implements the Timeout method, and calling the Timeout
   636  // method will return true, but there are other possible errors for which
   637  // the Timeout will return true even if the deadline has not been exceeded.
   638  //
   639  // An idle timeout can be implemented by repeatedly extending
   640  // the deadline after successful Read or Write calls.
   641  //
   642  // A zero value for t means I/O operations will not time out.
   643  func (f *File) SetDeadline(t time.Time) error {
   644  	return f.setDeadline(t)
   645  }
   646  
   647  // SetReadDeadline sets the deadline for future Read calls and any
   648  // currently-blocked Read call.
   649  // A zero value for t means Read will not time out.
   650  // Not all files support setting deadlines; see SetDeadline.
   651  func (f *File) SetReadDeadline(t time.Time) error {
   652  	return f.setReadDeadline(t)
   653  }
   654  
   655  // SetWriteDeadline sets the deadline for any future Write calls and any
   656  // currently-blocked Write call.
   657  // Even if Write times out, it may return n > 0, indicating that
   658  // some of the data was successfully written.
   659  // A zero value for t means Write will not time out.
   660  // Not all files support setting deadlines; see SetDeadline.
   661  func (f *File) SetWriteDeadline(t time.Time) error {
   662  	return f.setWriteDeadline(t)
   663  }
   664  
   665  // SyscallConn returns a raw file.
   666  // This implements the syscall.Conn interface.
   667  func (f *File) SyscallConn() (syscall.RawConn, error) {
   668  	if err := f.checkValid("SyscallConn"); err != nil {
   669  		return nil, err
   670  	}
   671  	return newRawConn(f)
   672  }
   673  
   674  // DirFS returns a file system (an fs.FS) for the tree of files rooted at the directory dir.
   675  //
   676  // Note that DirFS("/prefix") only guarantees that the Open calls it makes to the
   677  // operating system will begin with "/prefix": DirFS("/prefix").Open("file") is the
   678  // same as os.Open("/prefix/file"). So if /prefix/file is a symbolic link pointing outside
   679  // the /prefix tree, then using DirFS does not stop the access any more than using
   680  // os.Open does. Additionally, the root of the fs.FS returned for a relative path,
   681  // DirFS("prefix"), will be affected by later calls to Chdir. DirFS is therefore not
   682  // a general substitute for a chroot-style security mechanism when the directory tree
   683  // contains arbitrary content.
   684  //
   685  // The directory dir must not be "".
   686  //
   687  // The result implements [io/fs.StatFS], [io/fs.ReadFileFS] and
   688  // [io/fs.ReadDirFS].
   689  func DirFS(dir string) fs.FS {
   690  	return dirFS(dir)
   691  }
   692  
   693  type dirFS string
   694  
   695  func (dir dirFS) Open(name string) (fs.File, error) {
   696  	fullname, err := dir.join(name)
   697  	if err != nil {
   698  		return nil, &PathError{Op: "open", Path: name, Err: err}
   699  	}
   700  	f, err := Open(fullname)
   701  	if err != nil {
   702  		// DirFS takes a string appropriate for GOOS,
   703  		// while the name argument here is always slash separated.
   704  		// dir.join will have mixed the two; undo that for
   705  		// error reporting.
   706  		err.(*PathError).Path = name
   707  		return nil, err
   708  	}
   709  	return f, nil
   710  }
   711  
   712  // The ReadFile method calls the [ReadFile] function for the file
   713  // with the given name in the directory. The function provides
   714  // robust handling for small files and special file systems.
   715  // Through this method, dirFS implements [io/fs.ReadFileFS].
   716  func (dir dirFS) ReadFile(name string) ([]byte, error) {
   717  	fullname, err := dir.join(name)
   718  	if err != nil {
   719  		return nil, &PathError{Op: "readfile", Path: name, Err: err}
   720  	}
   721  	b, err := ReadFile(fullname)
   722  	if err != nil {
   723  		if e, ok := err.(*PathError); ok {
   724  			// See comment in dirFS.Open.
   725  			e.Path = name
   726  		}
   727  		return nil, err
   728  	}
   729  	return b, nil
   730  }
   731  
   732  // ReadDir reads the named directory, returning all its directory entries sorted
   733  // by filename. Through this method, dirFS implements [io/fs.ReadDirFS].
   734  func (dir dirFS) ReadDir(name string) ([]DirEntry, error) {
   735  	fullname, err := dir.join(name)
   736  	if err != nil {
   737  		return nil, &PathError{Op: "readdir", Path: name, Err: err}
   738  	}
   739  	entries, err := ReadDir(fullname)
   740  	if err != nil {
   741  		if e, ok := err.(*PathError); ok {
   742  			// See comment in dirFS.Open.
   743  			e.Path = name
   744  		}
   745  		return nil, err
   746  	}
   747  	return entries, nil
   748  }
   749  
   750  func (dir dirFS) Stat(name string) (fs.FileInfo, error) {
   751  	fullname, err := dir.join(name)
   752  	if err != nil {
   753  		return nil, &PathError{Op: "stat", Path: name, Err: err}
   754  	}
   755  	f, err := Stat(fullname)
   756  	if err != nil {
   757  		// See comment in dirFS.Open.
   758  		err.(*PathError).Path = name
   759  		return nil, err
   760  	}
   761  	return f, nil
   762  }
   763  
   764  // join returns the path for name in dir.
   765  func (dir dirFS) join(name string) (string, error) {
   766  	if dir == "" {
   767  		return "", errors.New("os: DirFS with empty root")
   768  	}
   769  	name, err := filepathlite.Localize(name)
   770  	if err != nil {
   771  		return "", ErrInvalid
   772  	}
   773  	if IsPathSeparator(dir[len(dir)-1]) {
   774  		return string(dir) + name, nil
   775  	}
   776  	return string(dir) + string(PathSeparator) + name, nil
   777  }
   778  
   779  // ReadFile reads the named file and returns the contents.
   780  // A successful call returns err == nil, not err == EOF.
   781  // Because ReadFile reads the whole file, it does not treat an EOF from Read
   782  // as an error to be reported.
   783  func ReadFile(name string) ([]byte, error) {
   784  	f, err := Open(name)
   785  	if err != nil {
   786  		return nil, err
   787  	}
   788  	defer f.Close()
   789  
   790  	var size int
   791  	if info, err := f.Stat(); err == nil {
   792  		size64 := info.Size()
   793  		if int64(int(size64)) == size64 {
   794  			size = int(size64)
   795  		}
   796  	}
   797  	size++ // one byte for final read at EOF
   798  
   799  	// If a file claims a small size, read at least 512 bytes.
   800  	// In particular, files in Linux's /proc claim size 0 but
   801  	// then do not work right if read in small pieces,
   802  	// so an initial read of 1 byte would not work correctly.
   803  	if size < 512 {
   804  		size = 512
   805  	}
   806  
   807  	data := make([]byte, 0, size)
   808  	for {
   809  		n, err := f.Read(data[len(data):cap(data)])
   810  		data = data[:len(data)+n]
   811  		if err != nil {
   812  			if err == io.EOF {
   813  				err = nil
   814  			}
   815  			return data, err
   816  		}
   817  
   818  		if len(data) >= cap(data) {
   819  			d := append(data[:cap(data)], 0)
   820  			data = d[:len(data)]
   821  		}
   822  	}
   823  }
   824  
   825  // WriteFile writes data to the named file, creating it if necessary.
   826  // If the file does not exist, WriteFile creates it with permissions perm (before umask);
   827  // otherwise WriteFile truncates it before writing, without changing permissions.
   828  // Since WriteFile requires multiple system calls to complete, a failure mid-operation
   829  // can leave the file in a partially written state.
   830  func WriteFile(name string, data []byte, perm FileMode) error {
   831  	f, err := OpenFile(name, O_WRONLY|O_CREATE|O_TRUNC, perm)
   832  	if err != nil {
   833  		return err
   834  	}
   835  	_, err = f.Write(data)
   836  	if err1 := f.Close(); err1 != nil && err == nil {
   837  		err = err1
   838  	}
   839  	return err
   840  }
   841  

View as plain text