]> ruderich.org/simon Gitweb - safcm/safcm.git/blob - remote/sync/files.go
remote: support creating files with missing parents in dry-run
[safcm/safcm.git] / remote / sync / files.go
1 // MsgSyncReq: copy files to the remote host
2
3 // Copyright (C) 2021-2023  Simon Ruderich
4 //
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 //go:build !windows
19 // +build !windows
20
21 package sync
22
23 import (
24         "bytes"
25         "fmt"
26         "io"
27         "io/fs"
28         "math/rand"
29         "net/http"
30         "os"
31         "os/user"
32         slashpath "path"
33         "path/filepath"
34         "sort"
35         "strconv"
36         "strings"
37         "time"
38
39         "github.com/ianbruene/go-difflib/difflib"
40         "golang.org/x/sys/unix"
41
42         "ruderich.org/simon/safcm"
43 )
44
45 // NOTE: Don't use plain os.Open, os.OpenFile, os.Remove or any other function
46 // which uses absolute paths. These are vulnerable to symlink attacks. Always
47 // use *at syscalls. See below for details.
48
49 // openReadonlyFlags are flags for open* syscalls to safely read a file or
50 // directory.
51 //
52 // O_NOFOLLOW prevents symlink attacks
53 // O_NONBLOCK is necessary to prevent blocking on FIFOs
54 const openReadonlyFlags = unix.O_RDONLY | unix.O_NOFOLLOW | unix.O_NONBLOCK
55
56 func (s *Sync) syncFiles() error {
57         // To create random file names for symlinks
58         rand.Seed(time.Now().UnixNano())
59
60         // Sort for deterministic order and so parent directories are present
61         // when files in them are created
62         var files []*safcm.File
63         for _, x := range s.req.Files {
64                 files = append(files, x)
65         }
66         sort.Slice(files, func(i, j int) bool {
67                 return files[i].Path < files[j].Path
68         })
69
70         for _, x := range files {
71                 var changed bool
72                 err := s.syncFile(x, &changed)
73                 if err != nil {
74                         return fmt.Errorf("%q: %v", x.Path, err)
75                 }
76                 if changed {
77                         s.queueTriggers(x)
78                 }
79         }
80
81         return nil
82 }
83
84 func (s *Sync) syncFile(file *safcm.File, changed *bool) error {
85         // The general strategy is "update by rename": If any property of a
86         // file changes it will be written to a temporary file and then
87         // renamed "over" the original file. This is simple and prevents race
88         // conditions where the file is partially readable while changes to
89         // permissions or owner/group are applied. However, this strategy does
90         // not work for directories which must be removed first (was
91         // directory), must remove the existing file (will be directory) or
92         // must be directly modified (changed permissions or owner). In the
93         // first two cases the old path is removed. In the last the directory
94         // is modified (carefully) in place.
95         //
96         // The implementation is careful not to follow any symlinks to prevent
97         // possible race conditions which can be exploited and are especially
98         // dangerous when running with elevated privileges (which will most
99         // likely be the case). This includes not using absolute paths in
100         // syscalls to prevent symlink attacks when a directory is writable by
101         // other users (e.g. when syncing a file to /home/user/dir/file the
102         // user could create dir as symlink to another directory and file
103         // would be written there). To prevent this *at syscalls are used and
104         // all symlinks in the path are rejected. This still permits the user
105         // to move dir during the sync but only to places which are writable
106         // by the user which cannot be prevented.
107
108         err := s.fileResolveIds(file)
109         if err != nil {
110                 return err
111         }
112
113         change := safcm.FileChange{
114                 Path: file.Path,
115                 New: safcm.FileChangeInfo{
116                         Mode:  file.Mode,
117                         User:  file.User,
118                         Uid:   file.Uid,
119                         Group: file.Group,
120                         Gid:   file.Gid,
121                 },
122         }
123
124         debugf := func(format string, a ...interface{}) {
125                 s.log.Debugf("files: %q (%s): %s",
126                         file.Path, file.OrigGroup, fmt.Sprintf(format, a...))
127         }
128         verbosef := func(format string, a ...interface{}) {
129                 s.log.Verbosef("files: %q (%s): %s",
130                         file.Path, file.OrigGroup, fmt.Sprintf(format, a...))
131         }
132
133         parentFd, baseName, err := OpenParentDirectoryNoSymlinks(file.Path)
134         if err != nil {
135                 if os.IsNotExist(err) && s.req.DryRun {
136                         change.Created = true
137                         debugf("will create (parent missing)")
138                         *changed = true
139                         debugf("dry-run, skipping changes")
140                         s.resp.FileChanges = append(s.resp.FileChanges, change)
141                         return nil
142                 }
143                 return err
144         }
145         defer unix.Close(parentFd)
146
147         var oldStat unix.Stat_t
148 reopen:
149         oldFh, err := OpenAtNoFollow(parentFd, baseName)
150         if err != nil {
151                 if err == unix.ELOOP || err == unix.EMLINK {
152                         // ELOOP from symbolic link, this is fine
153                         err := unix.Fstatat(parentFd, baseName, &oldStat,
154                                 unix.AT_SYMLINK_NOFOLLOW)
155                         if err != nil {
156                                 return err
157                         }
158                         if oldStat.Mode&unix.S_IFMT != unix.S_IFLNK {
159                                 debugf("type changed from symlink, retrying")
160                                 goto reopen
161                         }
162                 } else if os.IsNotExist(err) {
163                         change.Created = true
164                         debugf("will create")
165                 } else {
166                         return err
167                 }
168         } else {
169                 defer oldFh.Close()
170
171                 err := unix.Fstat(int(oldFh.Fd()), &oldStat)
172                 if err != nil {
173                         return err
174                 }
175         }
176
177         var oldData []byte
178         var changeType, changePerm, changeUserOrGroup, changeData bool
179         if !change.Created {
180                 // Manually convert to FileMode; from src/os/stat_linux.go in
181                 // Go's sources (stat_*.go for other UNIX systems are
182                 // identical, except for stat_darwin.go which has an extra
183                 // S_IFWHT)
184                 mode := fs.FileMode(oldStat.Mode & 0777)
185                 switch oldStat.Mode & unix.S_IFMT {
186                 case unix.S_IFBLK:
187                         mode |= fs.ModeDevice
188                 case unix.S_IFCHR:
189                         mode |= fs.ModeDevice | fs.ModeCharDevice
190                 case unix.S_IFDIR:
191                         mode |= fs.ModeDir
192                 case unix.S_IFIFO:
193                         mode |= fs.ModeNamedPipe
194                 case unix.S_IFLNK:
195                         mode |= fs.ModeSymlink
196                 case unix.S_IFREG:
197                         // nothing to do
198                 case unix.S_IFSOCK:
199                         mode |= fs.ModeSocket
200                 // Guard against unknown file types (e.g. on darwin); not in
201                 // stat_*.go
202                 default:
203                         return fmt.Errorf("unexpected file mode %v",
204                                 oldStat.Mode&unix.S_IFMT)
205                 }
206                 if oldStat.Mode&unix.S_ISGID != 0 {
207                         mode |= fs.ModeSetgid
208                 }
209                 if oldStat.Mode&unix.S_ISUID != 0 {
210                         mode |= fs.ModeSetuid
211                 }
212                 if oldStat.Mode&unix.S_ISVTX != 0 {
213                         mode |= fs.ModeSticky
214                 }
215
216                 // Compare permissions
217                 change.Old.Mode = mode
218                 if change.Old.Mode.Type() == fs.ModeSymlink {
219                         // Some BSD systems permit changing permissions of
220                         // symlinks but ignore them on traversal. To keep it
221                         // simple we don't support that and always use 0777
222                         // for symlink permissions (the value on GNU/Linux).
223                         //
224                         // TODO: Add proper support for symlinks on BSD
225                         change.Old.Mode |= 0777
226                 }
227                 if change.Old.Mode != file.Mode {
228                         if change.Old.Mode.Type() != file.Mode.Type() {
229                                 changeType = true
230                                 debugf("type differs %s -> %s",
231                                         change.Old.Mode.Type(),
232                                         file.Mode.Type())
233                         } else {
234                                 // Be careful with .Perm() which does not
235                                 // contain the setuid/setgid/sticky bits!
236                                 changePerm = true
237                                 debugf("permission differs %s -> %s",
238                                         change.Old.Mode, file.Mode)
239                         }
240                 }
241
242                 // Compare user/group
243                 change.Old.Uid = int(oldStat.Uid)
244                 change.Old.Gid = int(oldStat.Gid)
245                 if change.Old.Uid != file.Uid || change.Old.Gid != file.Gid {
246                         changeUserOrGroup = true
247                         debugf("uid/gid differs %d/%d -> %d/%d",
248                                 change.Old.Uid, change.Old.Gid,
249                                 file.Uid, file.Gid)
250                 }
251                 u, g, err := resolveIdsToNames(change.Old.Uid, change.Old.Gid)
252                 // Errors are not relevant as this is only used to report the
253                 // change. If the user/group no longer exits only the ids will
254                 // be reported.
255                 if err == nil {
256                         change.Old.User = u
257                         change.Old.Group = g
258                 }
259
260                 // Compare file content (if possible)
261                 switch change.Old.Mode.Type() { //nolint:exhaustive
262                 case 0: // regular file
263                         x, err := io.ReadAll(oldFh)
264                         if err != nil {
265                                 return fmt.Errorf("reading old content: %v",
266                                         err)
267                         }
268                         oldData = x
269                 case fs.ModeSymlink:
270                         buf := make([]byte, unix.PathMax)
271                         n, err := unix.Readlinkat(parentFd, baseName, buf)
272                         if err != nil {
273                                 return fmt.Errorf("reading old content: %v",
274                                         err)
275                         }
276                         oldData = buf[:n]
277                 }
278                 if !changeType && file.Mode.Type() != fs.ModeDir {
279                         if !bytes.Equal(oldData, file.Data) {
280                                 changeData = true
281                                 debugf("content differs")
282                         }
283                 }
284         }
285
286         // No changes
287         if !change.Created && !changeType &&
288                 !changePerm && !changeUserOrGroup &&
289                 !changeData {
290                 debugf("unchanged")
291                 return nil
292         }
293         *changed = true
294
295         // Don't show a diff with the full content for newly created files or
296         // on type changes. This is just noise for the user as the new file
297         // content is obvious. But we always want to see a diff when files are
298         // replaced because this destroys data.
299         if !change.Created &&
300                 (change.Old.Mode.Type() == 0 ||
301                         change.Old.Mode.Type() == fs.ModeSymlink) {
302                 change.DataDiff, err = diffData(oldData, file.Data)
303                 if err != nil {
304                         return err
305                 }
306         }
307
308         // Add change here so it is stored even when applying it fails. This
309         // way the user knows exactly what was attempted.
310         s.resp.FileChanges = append(s.resp.FileChanges, change)
311
312         if change.Created {
313                 verbosef("creating")
314         } else {
315                 verbosef("updating")
316         }
317
318         if s.req.DryRun {
319                 debugf("dry-run, skipping changes")
320                 return nil
321         }
322
323         // We cannot rename over directories and vice versa
324         if changeType && (change.Old.Mode.IsDir() || file.Mode.IsDir()) {
325                 debugf("removing (due to type change)")
326                 // In the past os.RemoveAll() was used here. However, this is
327                 // difficult to implement manually with *at syscalls. To keep
328                 // it simple only permit removing files and empty directories
329                 // here. This also has the bonus of preventing data loss when
330                 // (accidentally) replacing a directory tree with a file.
331                 const msg = "will not replace non-empty directory, " +
332                         "please remove manually"
333                 err := unix.Unlinkat(parentFd, baseName, 0)
334                 if err != nil && !os.IsNotExist(err) {
335                         err2 := unix.Unlinkat(parentFd, baseName,
336                                 unix.AT_REMOVEDIR)
337                         if err2 != nil && !os.IsNotExist(err2) {
338                                 // See src/os/file_unix.go in Go's sources
339                                 if err2 == unix.ENOTDIR {
340                                         return err
341                                 } else if err2 == unix.ENOTEMPTY {
342                                         return fmt.Errorf(msg)
343                                 } else {
344                                         return err2
345                                 }
346                         }
347                 }
348         }
349
350         // Directory: create new directory, also type change to directory
351         if file.Mode.IsDir() && (change.Created || changeType) {
352                 debugf("creating directory")
353                 err := unix.Mkdirat(parentFd, baseName, 0700)
354                 if err != nil {
355                         return err
356                 }
357                 // We must be careful not to chmod arbitrary files. If the
358                 // target directory is writable then it might have changed to
359                 // a symlink at this point. There's no lchmod and fchmodat is
360                 // incomplete so open the directory.
361                 debugf("chmodding %s", file.Mode)
362                 dh, err := OpenAtNoFollow(parentFd, baseName)
363                 if err != nil {
364                         return err
365                 }
366                 defer dh.Close()
367
368                 err = dh.Chmod(file.Mode)
369                 if err != nil {
370                         return err
371                 }
372                 // Less restrictive access is not relevant here because there
373                 // are no files present yet.
374                 debugf("chowning %d/%d", file.Uid, file.Gid)
375                 err = dh.Chown(file.Uid, file.Gid)
376                 if err != nil {
377                         return err
378                 }
379                 return nil
380         }
381         // Directory: changed permission or user/group
382         if file.Mode.IsDir() {
383                 // We don't know if the new permission or if the new
384                 // user/group is more restrictive (e.g. root:root 0750 ->
385                 // user:group 0700; applying group first gives group
386                 // unexpected access). To prevent a short window where the
387                 // access might be too lax we temporarily deny all access.
388                 if changePerm && changeUserOrGroup {
389                         // Only drop group and other permission because user
390                         // has access anyway (either before or after the
391                         // change). This also prevents temporary errors during
392                         // the error when the user tries to access this
393                         // directory (access for the group will fail though).
394                         mode := change.Old.Mode & fs.ModePerm & 0700
395                         // Retain setgid/sticky so that the behavior does not
396                         // change when creating and removing files.
397                         mode |= change.Old.Mode & fs.ModeSetgid
398                         mode |= change.Old.Mode & fs.ModeSticky
399                         debugf("chmodding %#o (temporary)", mode)
400                         err := oldFh.Chmod(mode)
401                         if err != nil {
402                                 return err
403                         }
404                 }
405                 if changeUserOrGroup {
406                         debugf("chowning %d/%d", file.Uid, file.Gid)
407                         err := oldFh.Chown(file.Uid, file.Gid)
408                         if err != nil {
409                                 return err
410                         }
411                 }
412                 if changePerm {
413                         debugf("chmodding %s", file.Mode)
414                         err := oldFh.Chmod(file.Mode)
415                         if err != nil {
416                                 return err
417                         }
418                 }
419                 return nil
420         }
421
422         dir := slashpath.Dir(file.Path) // only used in debug messages
423         // Create hidden file which should be ignored by most other tools and
424         // thus not affect anything during creation
425         tmpBase := "." + baseName
426
427         switch file.Mode.Type() {
428         case 0: // regular file
429                 debugf("creating temporary file %q",
430                         slashpath.Join(dir, tmpBase+"*"))
431                 x, err := WriteTempAt(parentFd, tmpBase, file.Data,
432                         file.Uid, file.Gid, file.Mode)
433                 if err != nil {
434                         return err
435                 }
436                 tmpBase = x
437
438         case fs.ModeSymlink:
439                 i := 0
440         retry:
441                 x := tmpBase + strconv.Itoa(rand.Int())
442                 debugf("creating temporary symlink %q",
443                         slashpath.Join(dir, x))
444                 err := unix.Symlinkat(string(file.Data), parentFd, x)
445                 if err != nil {
446                         if os.IsExist(err) && i < 10000 {
447                                 i++
448                                 goto retry
449                         }
450                         return err
451                 }
452                 tmpBase = x
453
454                 err = unix.Fchownat(parentFd, tmpBase, file.Uid, file.Gid,
455                         unix.AT_SYMLINK_NOFOLLOW)
456                 if err != nil {
457                         unix.Unlinkat(parentFd, tmpBase, 0) //nolint:errcheck
458                         return err
459                 }
460                 // Permissions are irrelevant for symlinks (on most systems)
461
462         default:
463                 panic(fmt.Sprintf("invalid file type %s", file.Mode))
464         }
465
466         debugf("renaming %q", slashpath.Join(dir, tmpBase))
467         err = unix.Renameat(parentFd, tmpBase, parentFd, baseName)
468         if err != nil {
469                 unix.Unlinkat(parentFd, tmpBase, 0) //nolint:errcheck
470                 return err
471         }
472         // To guarantee durability fsync must be called on a parent directory
473         // after adding, renaming or removing files therein.
474         //
475         // Calling sync on the files itself is not enough according to POSIX;
476         // man 2 fsync: "Calling fsync() does not necessarily ensure that the
477         // entry in the directory containing the file has also reached disk.
478         // For that an explicit fsync() on a file descriptor for the directory
479         // is also needed."
480         err = unix.Fsync(parentFd)
481         if err != nil {
482                 return err
483         }
484
485         return nil
486 }
487
488 func (s *Sync) fileResolveIds(file *safcm.File) error {
489         if file.User != "" && file.Uid != -1 {
490                 return fmt.Errorf("cannot set both User (%q) and Uid (%d)",
491                         file.User, file.Uid)
492         }
493         if file.Group != "" && file.Gid != -1 {
494                 return fmt.Errorf("cannot set both Group (%q) and Gid (%d)",
495                         file.Group, file.Gid)
496         }
497
498         if file.User == "" && file.Uid == -1 {
499                 file.User = s.defaultUser
500         }
501         if file.User != "" {
502                 x, err := user.Lookup(file.User)
503                 if err != nil {
504                         return err
505                 }
506                 id, err := strconv.Atoi(x.Uid)
507                 if err != nil {
508                         return err
509                 }
510                 file.Uid = id
511         }
512
513         if file.Group == "" && file.Gid == -1 {
514                 file.Group = s.defaultGroup
515         }
516         if file.Group != "" {
517                 x, err := user.LookupGroup(file.Group)
518                 if err != nil {
519                         return err
520                 }
521                 id, err := strconv.Atoi(x.Gid)
522                 if err != nil {
523                         return err
524                 }
525                 file.Gid = id
526         }
527
528         return nil
529 }
530
531 // OpenParentDirectoryNoSymlinks opens the dirname of path without following
532 // any symlinks and returns a file descriptor to it and the basename of path.
533 // To prevent symlink attacks in earlier path components when these are
534 // writable by other users it starts at the root (or current directory for
535 // relative paths) and uses openat (with O_NOFOLLOW) for each path component.
536 // If a symlink is encountered it returns an error. However, it's impossible
537 // to guarantee that the returned descriptor refers to the same location as
538 // given in path because users with write access can rename path components.
539 // But this is not required to prevent the mentioned attacks.
540 func OpenParentDirectoryNoSymlinks(path string) (int, string, error) {
541         // Slash separated paths are used for the configuration
542         parts := strings.Split(path, "/")
543
544         var dir string
545         if path == "/" {
546                 // Root: use root itself as base name because root is the
547                 // parent of itself
548                 dir = "/"
549                 parts = []string{"/"}
550         } else if parts[0] == "" {
551                 // Absolute path
552                 dir = "/"
553                 parts = parts[1:]
554         } else if path == "." {
555                 // Current directory: open parent directory and use current
556                 // directory name as base name
557                 wd, err := os.Getwd()
558                 if err != nil {
559                         return -1, "", fmt.Errorf(
560                                 "failed to get working directory: %w", err)
561                 }
562                 dir = ".."
563                 parts = []string{filepath.Base(wd)}
564         } else {
565                 // Relative path: start at the current directory
566                 dir = "."
567                 if parts[0] == "." {
568                         parts = parts[1:]
569                 }
570         }
571
572         dirFd, err := unix.Openat(unix.AT_FDCWD, dir, openReadonlyFlags, 0)
573         if err != nil {
574                 return -1, "", err
575         }
576         // Walk path one directory at a time to ensure there are no symlinks
577         // in the path. This prevents users with write access to change the
578         // path to point to arbitrary locations. O_NOFOLLOW when opening the
579         // path is not enough as only the last path component is checked.
580         for i, name := range parts[:len(parts)-1] {
581                 fd, err := unix.Openat(dirFd, name, openReadonlyFlags, 0)
582                 if err != nil {
583                         unix.Close(dirFd)
584                         if err == unix.ELOOP || err == unix.EMLINK {
585                                 x := filepath.Join(append([]string{dir},
586                                         parts[:i+1]...)...)
587                                 return -1, "", fmt.Errorf(
588                                         "symlink not permitted in path: %q",
589                                         x)
590                         }
591                         return -1, "", err
592                 }
593                 unix.Close(dirFd)
594                 dirFd = fd
595         }
596
597         return dirFd, parts[len(parts)-1], nil
598 }
599
600 func resolveIdsToNames(uid, gid int) (string, string, error) {
601         u, err := user.LookupId(strconv.Itoa(uid))
602         if err != nil {
603                 return "", "", err
604         }
605         g, err := user.LookupGroupId(strconv.Itoa(gid))
606         if err != nil {
607                 return "", "", err
608         }
609         return u.Username, g.Name, nil
610 }
611
612 func diffData(oldData []byte, newData []byte) (string, error) {
613         oldBin := !strings.HasPrefix(http.DetectContentType(oldData), "text/")
614         newBin := !strings.HasPrefix(http.DetectContentType(newData), "text/")
615         if oldBin && newBin {
616                 return fmt.Sprintf("Binary files differ (%d -> %d bytes), "+
617                         "cannot show diff", len(oldData), len(newData)), nil
618         }
619         if oldBin {
620                 oldData = []byte(fmt.Sprintf("<binary content, %d bytes>\n",
621                         len(oldData)))
622         }
623         if newBin {
624                 newData = []byte(fmt.Sprintf("<binary content, %d bytes>\n",
625                         len(newData)))
626         }
627
628         // TODO: difflib shows empty context lines at the end of the file
629         // which should not be there
630         // TODO: difflib has issues with missing newlines in either side
631         result, err := difflib.GetUnifiedDiffString(difflib.LineDiffParams{
632                 A:       difflib.SplitLines(string(oldData)),
633                 B:       difflib.SplitLines(string(newData)),
634                 Context: 3,
635         })
636         if err != nil {
637                 return "", err
638         }
639         return result, nil
640 }
641
642 func OpenFileNoSymlinks(path string) (*os.File, error) {
643         parentFd, baseName, err := OpenParentDirectoryNoSymlinks(path)
644         if err != nil {
645                 return nil, err
646         }
647         defer unix.Close(parentFd)
648         return OpenAtNoFollow(parentFd, baseName)
649 }
650
651 func OpenAtNoFollow(dirFd int, base string) (*os.File, error) {
652         fd, err := unix.Openat(dirFd, base, openReadonlyFlags, 0)
653         if err != nil {
654                 return nil, err
655         }
656         return os.NewFile(uintptr(fd), ""), nil
657 }
658
659 func WriteTempAt(dirFd int, base string, data []byte, uid, gid int,
660         mode fs.FileMode) (string, error) {
661
662         fh, tmpBase, err := createTempAt(dirFd, base)
663         if err != nil {
664                 return "", err
665         }
666
667         _, err = fh.Write(data)
668         if err != nil {
669                 fh.Close()
670                 unix.Unlinkat(dirFd, tmpBase, 0) //nolint:errcheck
671                 return "", err
672         }
673         // createTempAt() creates the file with 0600
674         err = fh.Chown(uid, gid)
675         if err != nil {
676                 fh.Close()
677                 unix.Unlinkat(dirFd, tmpBase, 0) //nolint:errcheck
678                 return "", err
679         }
680         err = fh.Chmod(mode)
681         if err != nil {
682                 fh.Close()
683                 unix.Unlinkat(dirFd, tmpBase, 0) //nolint:errcheck
684                 return "", err
685         }
686         err = fh.Sync()
687         if err != nil {
688                 fh.Close()
689                 unix.Unlinkat(dirFd, tmpBase, 0) //nolint:errcheck
690                 return "", err
691         }
692         err = fh.Close()
693         if err != nil {
694                 unix.Unlinkat(dirFd, tmpBase, 0) //nolint:errcheck
695                 return "", err
696         }
697
698         return tmpBase, nil
699 }
700
701 // createTempAt works similar to os.CreateTemp but uses unix.Openat to create
702 // the temporary file.
703 func createTempAt(dirFd int, base string) (*os.File, string, error) {
704         var tmpBase string
705
706         i := 0
707 retry:
708         tmpBase = base + strconv.Itoa(rand.Int())
709
710         fd, err := unix.Openat(dirFd, tmpBase,
711                 unix.O_RDWR|unix.O_CREAT|unix.O_EXCL, 0600)
712         if err != nil {
713                 if os.IsExist(err) && i < 10000 {
714                         i++
715                         goto retry
716                 }
717                 return nil, "", err
718         }
719
720         return os.NewFile(uintptr(fd), ""), tmpBase, nil
721 }