writeFileInPlace0600 writes data over path in place, following a symlink, as os.WriteFile did. A regular file is made 0600 before it is truncated, so the new tokens never land under a looser mode on a file we own; on one we cannot chmod (a foreign-owned file we may write) the write goes ahead, as os
(path string, data []byte)
| 410 | // cannot say whether the target is a regular file to truncate, and writing |
| 411 | // a shorter body without the truncate would leave the old tail behind. |
| 412 | func writeFileInPlace0600(path string, data []byte) error { |
| 413 | f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0600) |
| 414 | if err != nil { |
| 415 | return err |
| 416 | } |
| 417 | fi, err := statOpenFile(f) |
| 418 | if err != nil { |
| 419 | _ = f.Close() |
| 420 | return err |
| 421 | } |
| 422 | if fi.Mode().IsRegular() { |
| 423 | _ = f.Chmod(0600) |
| 424 | // The mtime is set before the truncate, so a reader's emptyConfirmed |
| 425 | // memo stops matching even when the file is already empty: POSIX moves |
| 426 | // mtime on ftruncate only when the size changes, and Windows' |
| 427 | // SetEndOfFile need not either (BUG-3838). Best effort, like the chmod: |
| 428 | // a foreign-owned file we may write but not touch keeps that residual. |
| 429 | _ = touchCredentialsFile(f, path) |
| 430 | if err := truncateCredentialsFile(f, 0); err != nil { |
| 431 | _ = f.Close() |
| 432 | return err |
| 433 | } |
| 434 | } |
| 435 | if _, err := f.Write(data); err != nil { |
| 436 | _ = f.Close() |
| 437 | return err |
| 438 | } |
| 439 | _ = f.Sync() |
| 440 | return f.Close() |
| 441 | } |
| 442 | |
| 443 | // statOpenFile is f.Stat, a variable so a test can fail it (BUG-3810). |
| 444 | var statOpenFile = (*os.File).Stat |