-
Notifications
You must be signed in to change notification settings - Fork 107
/
mount_darwin.go
427 lines (358 loc) · 10 KB
/
mount_darwin.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
package fuse
import (
"bytes"
"errors"
"fmt"
"log"
"os"
"os/exec"
"strconv"
"strings"
"syscall"
"github.com/jacobsa/fuse/internal/buffer"
"github.com/jacobsa/fuse/internal/fusekernel"
)
var errNoAvail = errors.New("no available fuse devices")
var errNotLoaded = errors.New("osxfuse is not loaded")
// errOSXFUSENotFound is returned from Mount when the OSXFUSE installation is
// not detected. Make sure OSXFUSE is installed.
var errOSXFUSENotFound = errors.New("cannot locate OSXFUSE")
// osxfuseInstallation describes the paths used by an installed OSXFUSE
// version.
type osxfuseInstallation struct {
// Prefix for the device file. At mount time, an incrementing number is
// suffixed until a free FUSE device is found.
DevicePrefix string
// Path of the load helper, used to load the kernel extension if no device
// files are found.
Load string
// Path of the mount helper, used for the actual mount operation.
Mount string
// Environment variable used to pass the path to the executable calling the
// mount helper.
DaemonVar string
// Environment variable used to pass the "called by library" flag.
LibVar string
// Open device manually (false) or receive the FD through a UNIX socket,
// like with fusermount (true)
UseCommFD bool
}
var (
osxfuseInstallations = []osxfuseInstallation{
// v4
{
DevicePrefix: "/dev/macfuse",
Load: "/Library/Filesystems/macfuse.fs/Contents/Resources/load_macfuse",
Mount: "/Library/Filesystems/macfuse.fs/Contents/Resources/mount_macfuse",
DaemonVar: "_FUSE_DAEMON_PATH",
LibVar: "_FUSE_CALL_BY_LIB",
UseCommFD: true,
},
// v3
{
DevicePrefix: "/dev/osxfuse",
Load: "/Library/Filesystems/osxfuse.fs/Contents/Resources/load_osxfuse",
Mount: "/Library/Filesystems/osxfuse.fs/Contents/Resources/mount_osxfuse",
DaemonVar: "MOUNT_OSXFUSE_DAEMON_PATH",
LibVar: "MOUNT_OSXFUSE_CALL_BY_LIB",
},
// v2
{
DevicePrefix: "/dev/osxfuse",
Load: "/Library/Filesystems/osxfusefs.fs/Support/load_osxfusefs",
Mount: "/Library/Filesystems/osxfusefs.fs/Support/mount_osxfusefs",
DaemonVar: "MOUNT_FUSEFS_DAEMON_PATH",
LibVar: "MOUNT_FUSEFS_CALL_BY_LIB",
},
}
)
const FUSET_SRV_PATH = "/usr/local/bin/go-nfsv4"
func loadOSXFUSE(bin string) error {
cmd := exec.Command(bin)
cmd.Dir = "/"
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
return err
}
func openOSXFUSEDev(devPrefix string) (dev *os.File, err error) {
// Try each device name.
for i := uint64(0); ; i++ {
path := devPrefix + strconv.FormatUint(i, 10)
dev, err = os.OpenFile(path, os.O_RDWR, 0000)
if os.IsNotExist(err) {
if i == 0 {
// Not even the first device was found. Fuse must not be loaded.
return nil, errNotLoaded
}
// Otherwise we've run out of kernel-provided devices
return nil, errNoAvail
}
if err2, ok := err.(*os.PathError); ok && err2.Err == syscall.EBUSY {
// This device is in use; try the next one.
continue
}
return dev, nil
}
}
func convertMountArgs(daemonVar string, libVar string,
cfg *MountConfig) ([]string, []string, error) {
// The mount helper doesn't understand any escaping.
for k, v := range cfg.toMap() {
if strings.Contains(k, ",") || strings.Contains(v, ",") {
return nil, nil, fmt.Errorf(
"mount options cannot contain commas on darwin: %q=%q",
k,
v)
}
}
env := []string{libVar + "="}
if daemonVar != "" {
env = append(env, daemonVar+"="+os.Args[0])
}
argv := []string{
"-o", cfg.toOptionsString(),
// Tell osxfuse-kext how large our buffer is. It must split
// writes larger than this into multiple writes.
//
// OSXFUSE seems to ignore InitResponse.MaxWrite, and uses
// this instead.
"-o", "iosize=" + strconv.FormatUint(buffer.MaxWriteSize, 10),
}
return argv, env, nil
}
func callMount(
bin string,
daemonVar string,
libVar string,
dir string,
cfg *MountConfig,
dev *os.File,
ready chan<- error) error {
argv, env, err := convertMountArgs(daemonVar, libVar, cfg)
if err != nil {
return err
}
// Call the mount helper, passing in the device file and saving output into a
// buffer.
argv = append(argv,
// refers to fd passed in cmd.ExtraFiles
"3",
dir,
)
cmd := exec.Command(bin, argv...)
cmd.ExtraFiles = []*os.File{dev}
cmd.Env = env
var buf bytes.Buffer
cmd.Stdout = &buf
cmd.Stderr = &buf
if err := cmd.Start(); err != nil {
return err
}
// In the background, wait for the command to complete.
go func() {
err := cmd.Wait()
if err != nil {
if buf.Len() > 0 {
output := buf.Bytes()
output = bytes.TrimRight(output, "\n")
err = fmt.Errorf("%v: %s", err, output)
}
}
ready <- err
}()
return nil
}
func callMountCommFD(
bin string,
daemonVar string,
libVar string,
dir string,
cfg *MountConfig) (*os.File, error) {
argv, env, err := convertMountArgs(daemonVar, libVar, cfg)
if err != nil {
return nil, err
}
env = append(env, "_FUSE_COMMVERS=2")
argv = append(argv, dir)
return fusermount(bin, argv, env, false, cfg.DebugLogger)
}
// Begin the process of mounting at the given directory, returning a connection
// to the kernel. Mounting continues in the background, and is complete when an
// error is written to the supplied channel. The file system may need to
// service the connection in order for mounting to complete.
func mountOsxFuse(
dir string,
cfg *MountConfig,
ready chan<- error) (dev *os.File, err error) {
// Find the version of osxfuse installed on this machine.
for _, loc := range osxfuseInstallations {
if _, err := os.Stat(loc.Mount); os.IsNotExist(err) {
// try the other locations
continue
}
if loc.UseCommFD {
// Call the mount binary with the device.
ready <- nil
dev, err = callMountCommFD(loc.Mount, loc.DaemonVar, loc.LibVar, dir, cfg)
if err != nil {
return nil, fmt.Errorf("callMount: %v", err)
}
return
}
// Open the device.
dev, err = openOSXFUSEDev(loc.DevicePrefix)
// Special case: we may need to explicitly load osxfuse. Load it, then
// try again.
if err == errNotLoaded {
err = loadOSXFUSE(loc.Load)
if err != nil {
return nil, fmt.Errorf("loadOSXFUSE: %v", err)
}
dev, err = openOSXFUSEDev(loc.DevicePrefix)
}
// Propagate errors.
if err != nil {
return nil, fmt.Errorf("openOSXFUSEDev: %v", err)
}
// Call the mount binary with the device.
if err := callMount(loc.Mount, loc.DaemonVar, loc.LibVar, dir, cfg, dev, ready); err != nil {
dev.Close()
return nil, fmt.Errorf("callMount: %v", err)
}
return dev, nil
}
return nil, errOSXFUSENotFound
}
func fusetBinary() (string, error) {
srv_path := os.Getenv("FUSE_NFSSRV_PATH")
if srv_path == "" {
srv_path = FUSET_SRV_PATH
}
if _, err := os.Stat(srv_path); err == nil {
return srv_path, nil
}
return "", fmt.Errorf("FUSE-T not found")
}
func unixgramSocketpair() (l, r *os.File, err error) {
fd, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_STREAM, 0)
if err != nil {
return nil, nil, os.NewSyscallError("socketpair",
err.(syscall.Errno))
}
l = os.NewFile(uintptr(fd[0]), fmt.Sprintf("socketpair-half%d", fd[0]))
r = os.NewFile(uintptr(fd[1]), fmt.Sprintf("socketpair-half%d", fd[1]))
return
}
var local, local_mon, remote, remote_mon *os.File
func startFuseTServer(binary string, argv []string,
additionalEnv []string,
wait bool,
debugLogger *log.Logger,
ready chan<- error) (*os.File, error) {
if debugLogger != nil {
debugLogger.Println("Creating a socket pair")
}
var err error
local, remote, err = unixgramSocketpair()
if err != nil {
return nil, err
}
defer remote.Close()
local_mon, remote_mon, err = unixgramSocketpair()
if err != nil {
return nil, err
}
defer remote_mon.Close()
syscall.CloseOnExec(int(local.Fd()))
syscall.CloseOnExec(int(local_mon.Fd()))
if debugLogger != nil {
debugLogger.Println("Creating files to wrap the sockets")
}
if debugLogger != nil {
debugLogger.Println("Starting fusermount/os mount")
}
// Start fusermount/mount_macfuse/mount_osxfuse.
cmd := exec.Command(binary, argv...)
cmd.Env = append(os.Environ(), "_FUSE_COMMFD=3")
cmd.Env = append(cmd.Env, "_FUSE_MONFD=4")
cmd.Env = append(cmd.Env, additionalEnv...)
cmd.ExtraFiles = []*os.File{remote, remote_mon}
cmd.Stderr = nil
cmd.Stdout = nil
// daemonize
cmd.SysProcAttr = &syscall.SysProcAttr{
Setsid: true,
}
// Run the command.
err = cmd.Start()
cmd.Process.Release()
if err != nil {
return nil, fmt.Errorf("running %v: %v", binary, err)
}
if debugLogger != nil {
debugLogger.Println("Wrapping socket pair in a connection")
}
if debugLogger != nil {
debugLogger.Println("Checking that we have a unix domain socket")
}
if debugLogger != nil {
debugLogger.Println("Read a message from socket")
}
go func() {
if _, err = local_mon.Write([]byte("mount")); err != nil {
err = fmt.Errorf("fuse-t failed: %v", err)
} else {
reply := make([]byte, 4)
if _, err = local_mon.Read(reply); err != nil {
fmt.Printf("mount read %v\n", err)
err = fmt.Errorf("fuse-t failed: %v", err)
}
}
ready <- err
close(ready)
}()
if debugLogger != nil {
debugLogger.Println("Successfully read the socket message.")
}
return local, nil
}
func mountFuset(
dir string,
cfg *MountConfig,
ready chan<- error) (dev *os.File, err error) {
fuseTBin, err := fusetBinary()
if err != nil {
return nil, err
}
fusekernel.IsPlatformFuseT = true
env := []string{}
argv := []string{
fmt.Sprintf("--rwsize=%d", buffer.MaxWriteSize),
}
if cfg.VolumeName != "" {
argv = append(argv, "--volname")
argv = append(argv, cfg.VolumeName)
}
if cfg.ReadOnly {
argv = append(argv, "-r")
}
env = append(env, "_FUSE_COMMVERS=2")
argv = append(argv, dir)
return startFuseTServer(fuseTBin, argv, env, false, cfg.DebugLogger, ready)
}
func mount(
dir string,
cfg *MountConfig,
ready chan<- error) (dev *os.File, err error) {
fusekernel.IsPlatformFuseT = false
switch cfg.FuseImpl {
case FUSEImplMacFUSE:
dev, err = mountOsxFuse(dir, cfg, ready)
case FUSEImplFuseT:
fallthrough
default:
dev, err = mountFuset(dir, cfg, ready)
}
return
}