core: run rclone as mount helper - #5594

This commit is contained in:
Ivan Andreev 2021-10-02 12:51:00 +03:00
parent ffa1b1a258
commit a95c7a001e
3 changed files with 391 additions and 0 deletions

View file

@ -7,6 +7,7 @@ package daemonize
import (
"os"
"strings"
"syscall"
"github.com/rclone/rclone/fs"
@ -29,6 +30,18 @@ func StartDaemon(args []string) (*os.Process, error) {
me = os.Args[0]
}
// os.Executable might have resolved symbolic link to the executable
// so we run the background process with pre-converted CLI arguments.
// Double conversion is still probable but isn't a problem as it should
// preserve the converted command line.
if len(args) != 0 {
args[0] = me
}
if fs.PassDaemonArgsAsEnviron {
args, env = argsToEnv(args, env)
}
null, err := os.Open(os.DevNull)
if err != nil {
return nil, err
@ -57,3 +70,42 @@ func StartDaemon(args []string) (*os.Process, error) {
return daemon, nil
}
// Processed command line flags of mount helper have simple structure:
// `--flag` or `--flag=value` but never `--flag value` or `-x`
// so we can easily pass them as environment variables.
func argsToEnv(origArgs, origEnv []string) (args, env []string) {
env = origEnv
if len(origArgs) == 0 {
return
}
args = []string{origArgs[0]}
for _, arg := range origArgs[1:] {
if !strings.HasPrefix(arg, "--") {
args = append(args, arg)
continue
}
arg = arg[2:]
key, val := arg, "true"
if idx := strings.Index(arg, "="); idx != -1 {
key, val = arg[:idx], arg[idx+1:]
}
name := "RCLONE_" + strings.ToUpper(strings.ReplaceAll(key, "-", "_"))
pref := name + "="
line := name + "=" + val
found := false
for i, s := range env {
if strings.HasPrefix(s, pref) {
env[i] = line
found = true
}
}
if !found {
env = append(env, line)
}
}
return
}