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