-
Notifications
You must be signed in to change notification settings - Fork 2
/
securetemp_unix.go
89 lines (74 loc) · 1.74 KB
/
securetemp_unix.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// +build !darwin
package securetemp
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
"golang.org/x/sys/unix"
)
const (
devShmPath = "/dev/shm"
)
func createRAMDisk(size int) (string, CleanupFunc, error) {
var (
mountPath string
err error
doCleanup = true
)
cleanupFunc := func() { cleanupRAMDisk(mountPath) }
defer func() {
if doCleanup {
cleanupFunc()
}
}()
if unix.Access(devShmPath, unix.W_OK) == nil && unix.Access(devShmPath, unix.X_OK) == nil {
// We'll use /dev/shm
mountPath, err = ioutil.TempDir(devShmPath, globalPrefix)
if err != nil {
return "", nil, fmt.Errorf("failed to create temp dir in %s: %s", devShmPath, err)
}
doCleanup = false
return mountPath, cleanupFunc, nil
}
mountPath, err = ioutil.TempDir("", globalPrefix)
if err != nil {
return "", nil, fmt.Errorf("failed to create temp dir: %s", err)
}
if err := createAndMount(mountPath, size); err != nil {
return "", nil, err
}
doCleanup = false
return mountPath, cleanupFunc, nil
}
func cleanupRAMDisk(mountPath string) {
if mountPath != "" {
if !strings.HasPrefix(mountPath, devShmPath) {
exec.Command("umount", mountPath).Run()
}
os.RemoveAll(mountPath)
}
}
func createAndMount(mountPath string, size int) error {
path, err := exec.LookPath("mount_mfs")
if err != nil {
return errors.New("did not find 'mount_mfs'")
}
cmd := exec.Command(path,
"-o", "noatime",
fmt.Sprintf("-s %d", size*2),
"/dev/wd0b",
mountPath)
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
return fmt.Errorf("failed to start 'mount_mfs': %s", err)
}
if err := cmd.Wait(); err != nil {
return fmt.Errorf("'mount_mfs' failed: %s, %s", err, stderr.String())
}
return nil
}