github.com/criyle/go-sandbox@v0.10.3/pkg/mount/mount.go (about)

     1  package mount
     2  
     3  import (
     4  	"syscall"
     5  )
     6  
     7  // Mount defines syscall for mount points
     8  type Mount struct {
     9  	Source, Target, FsType, Data string
    10  	Flags                        uintptr
    11  }
    12  
    13  // SyscallParams defines the raw syscall arguments to mount
    14  type SyscallParams struct {
    15  	Source, Target, FsType, Data *byte
    16  	Flags                        uintptr
    17  	Prefixes                     []*byte
    18  	MakeNod                      bool
    19  }
    20  
    21  // ToSyscall convert Mount to SyscallPrams
    22  func (m *Mount) ToSyscall() (*SyscallParams, error) {
    23  	var data *byte
    24  	source, err := syscall.BytePtrFromString(m.Source)
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  	target, err := syscall.BytePtrFromString(m.Target)
    29  	if err != nil {
    30  		return nil, err
    31  	}
    32  	fsType, err := syscall.BytePtrFromString(m.FsType)
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  	if m.Data != "" {
    37  		data, err = syscall.BytePtrFromString(m.Data)
    38  		if err != nil {
    39  			return nil, err
    40  		}
    41  	}
    42  	prefix := pathPrefix(m.Target)
    43  	paths, err := arrayPtrFromStrings(prefix)
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  	return &SyscallParams{
    48  		Source:   source,
    49  		Target:   target,
    50  		FsType:   fsType,
    51  		Flags:    m.Flags,
    52  		Data:     data,
    53  		Prefixes: paths,
    54  	}, nil
    55  }
    56  
    57  // pathPrefix get all components from path
    58  func pathPrefix(path string) []string {
    59  	ret := make([]string, 0)
    60  	for i := 1; i < len(path); i++ {
    61  		if path[i] == '/' {
    62  			ret = append(ret, path[:i])
    63  		}
    64  	}
    65  	ret = append(ret, path)
    66  	return ret
    67  }
    68  
    69  // arrayPtrFromStrings converts strings to c style strings
    70  func arrayPtrFromStrings(str []string) ([]*byte, error) {
    71  	bytes := make([]*byte, 0, len(str))
    72  	for _, s := range str {
    73  		b, err := syscall.BytePtrFromString(s)
    74  		if err != nil {
    75  			return nil, err
    76  		}
    77  		bytes = append(bytes, b)
    78  	}
    79  	return bytes, nil
    80  }