github.com/moby/docker@v26.1.3+incompatible/pkg/system/chtimes.go (about)

     1  package system // import "github.com/docker/docker/pkg/system"
     2  
     3  import (
     4  	"os"
     5  	"syscall"
     6  	"time"
     7  	"unsafe"
     8  )
     9  
    10  // Used by Chtimes
    11  var unixEpochTime, unixMaxTime time.Time
    12  
    13  func init() {
    14  	unixEpochTime = time.Unix(0, 0)
    15  	if unsafe.Sizeof(syscall.Timespec{}.Nsec) == 8 {
    16  		// This is a 64 bit timespec
    17  		// os.Chtimes limits time to the following
    18  		//
    19  		// Note that this intentionally sets nsec (not sec), which sets both sec
    20  		// and nsec internally in time.Unix();
    21  		// https://github.com/golang/go/blob/go1.19.2/src/time/time.go#L1364-L1380
    22  		unixMaxTime = time.Unix(0, 1<<63-1)
    23  	} else {
    24  		// This is a 32 bit timespec
    25  		unixMaxTime = time.Unix(1<<31-1, 0)
    26  	}
    27  }
    28  
    29  // Chtimes changes the access time and modified time of a file at the given path.
    30  // If the modified time is prior to the Unix Epoch (unixMinTime), or after the
    31  // end of Unix Time (unixEpochTime), os.Chtimes has undefined behavior. In this
    32  // case, Chtimes defaults to Unix Epoch, just in case.
    33  func Chtimes(name string, atime time.Time, mtime time.Time) error {
    34  	if atime.Before(unixEpochTime) || atime.After(unixMaxTime) {
    35  		atime = unixEpochTime
    36  	}
    37  
    38  	if mtime.Before(unixEpochTime) || mtime.After(unixMaxTime) {
    39  		mtime = unixEpochTime
    40  	}
    41  
    42  	if err := os.Chtimes(name, atime, mtime); err != nil {
    43  		return err
    44  	}
    45  
    46  	// Take platform specific action for setting create time.
    47  	return setCTime(name, mtime)
    48  }