writeFileInPlace0600 writes data over path in place, following a symlink, as os.WriteFile did. A regular file is made 0600 on POSIX and given a protected owner-only DACL on Windows (BUG-3807) before it is touched, truncated or written, so new tokens never land under looser access on a file we own. O
(path string, data []byte)
| 452 | // cannot say whether the target is a regular file to truncate, and writing |
| 453 | // a shorter body without the truncate would leave the old tail behind. |
| 454 | func writeFileInPlace0600(path string, data []byte) error { |
| 455 | f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0600) |
| 456 | if err != nil { |
| 457 | return err |
| 458 | } |
| 459 | fi, err := statOpenFile(f) |
| 460 | if err != nil { |
| 461 | _ = f.Close() |
| 462 | return err |
| 463 | } |
| 464 | if fi.Mode().IsRegular() { |
| 465 | _ = f.Chmod(0600) |
| 466 | if err := restrictCredentials(path); err != nil && credentialsFileOwnedByUs(path) { |
| 467 | fmt.Fprintf(credentialsLockWarning, "warning: could not restrict access to %s to the current user (%v); saving credentials anyway\n", path, err) |
| 468 | } |
| 469 | // The mtime is set before the truncate, so a reader's emptyConfirmed |
| 470 | // memo stops matching even when the file is already empty: POSIX moves |
| 471 | // mtime on ftruncate only when the size changes, and Windows' |
| 472 | // SetEndOfFile need not either (BUG-3838). Best effort, like the chmod: |
| 473 | // a foreign-owned file we may write but not touch keeps that residual. |
| 474 | _ = touchCredentialsFile(f, path) |
| 475 | if err := truncateCredentialsFile(f, 0); err != nil { |
| 476 | _ = f.Close() |
| 477 | return err |
| 478 | } |
| 479 | } |
| 480 | if _, err := f.Write(data); err != nil { |
| 481 | _ = f.Close() |
| 482 | return err |
| 483 | } |
| 484 | _ = f.Sync() |
| 485 | return f.Close() |
| 486 | } |
| 487 | |
| 488 | // restrictCredentials is restrictCredentialsFile, swappable so a test can force |
| 489 | // an access-restriction failure on any OS (BUG-3807). |