func unshareAndBind(workingRootDir string) bool { if *unshare { // Re-exec myself using the unshare syscall while on a locked thread. // This hack is required because syscall.Unshare() operates on only one // thread in the process, and Go switches execution between threads // randomly. Thus, the namespace can be suddenly switched for running // code. This is an aspect of Go that was not well thought out. runtime.LockOSThread() err := syscall.Unshare(syscall.CLONE_NEWNS) if err != nil { fmt.Printf("Unable to unshare mount namesace\t%s\n", err) return false } args := append(os.Args, "-unshare=false") err = syscall.Exec(args[0], args, os.Environ()) if err != nil { fmt.Printf("Unable to Exec:%s\t%s\n", args[0], err) return false } } err := syscall.Mount("none", "/", "", syscall.MS_REC|syscall.MS_PRIVATE, "") if err != nil { fmt.Printf("Unable to set mount sharing to private\t%s\n", err) return false } syscall.Unmount(workingRootDir, 0) err = syscall.Mount(*rootDir, workingRootDir, "", syscall.MS_BIND, "") if err != nil { fmt.Printf("Unable to bind mount %s to %s\t%s\n", *rootDir, workingRootDir, err) return false } return true }
func startAttachTag(tag string) { if *dockerFlag == "" { *dockerFlag, _ = exec.LookPath("docker") } var containers []string img := "gc14:" + tag foreachDockerPs(func(runningImage, containerID string) { if runningImage != img { return } containers = append(containers, containerID) }) switch { case len(containers) > 1: for _, container := range containers { // Best effort: exec.Command(*dockerFlag, "kill", container).Run() exec.Command(*dockerFlag, "rm", container).Run() } case len(containers) == 1: if err := syscall.Exec(*dockerFlag, []string{*dockerFlag, "attach", containers[0]}, os.Environ()); err != nil { log.Fatalf("docker attach exec: %v", err) } } if err := syscall.Exec(*dockerFlag, []string{*dockerFlag, "run", "-t", "-i", "-h", tag, "-w", "/home/gopher", img, "/bin/bash"}, os.Environ()); err != nil { log.Fatalf("docker run exec: %v", err) } }
func (UserExecer) ExecAsUser(uid, gid int, workDir, programName string, args ...string) error { if _, _, errNo := syscall.RawSyscall(syscall.SYS_SETGID, uintptr(gid), 0, 0); errNo != 0 { return fmt.Errorf("system: setgid: %s", errNo.Error()) } if _, _, errNo := syscall.RawSyscall(syscall.SYS_SETUID, uintptr(uid), 0, 0); errNo != 0 { return fmt.Errorf("system: setuid: %s", errNo.Error()) } if workDir == "" { return errors.New("system: working directory is not provided.") } if err := os.MkdirAll(workDir, 0755); err != nil { return fmt.Errorf("system: %s", err) } if err := os.Chdir(workDir); err != nil { return fmt.Errorf("system: invalid working directory: %s", workDir) } programPath, err := exec.LookPath(programName) if err != nil { return fmt.Errorf("system: program '%s' was not found in $PATH: %s", programName, err) } if err := syscall.Exec(programPath, append([]string{programName}, args...), os.Environ()); err != nil { return fmt.Errorf("system: exec of %s: %s", programName, err) } return nil }
func executeProgram(args *DockerInitArgs) error { setupEnv(args) if err := setupNetworking(args); err != nil { return err } if err := setupCapabilities(args); err != nil { return err } if err := setupWorkingDirectory(args); err != nil { return err } if err := changeUser(args); err != nil { return err } path, err := exec.LookPath(args.args[0]) if err != nil { log.Printf("Unable to locate %v", args.args[0]) os.Exit(127) } if err := syscall.Exec(path, args.args, os.Environ()); err != nil { panic(err) } // Will never reach here return nil }
func main() { // Para nuestro ejemplo usaremos `ls`. Go necesita // la ruta absoluta al binario que queremos ejecutar, // así que usaremos `exec.LookPath` para encontrarla // (probablemente está en `/bin/ls`). binary, lookErr := exec.LookPath("ls") if lookErr != nil { panic(lookErr) } // `Exec` necesita los argumentos en forma de slice // (en vez de un solo string). Le daremos a `ls` // algunos argumentos comunes. El primer argumento // debe de ser el nombre del programa. args := []string{"ls", "-a", "-l", "-h"} // `Exec` también necesita un conjunto de [variables de entorno](variables-de-entorno). // Aquí solamente le pasaremos nuestro ambiente // actual. env := os.Environ() // Aquí está la llamada a `os.Exec`. Si la llamada // es exitósa, la ejecución de nuestro proceso // terminará y será reemplazada por el proceso // `/bin/ls -a -l -h`. Si existe algún error, // recibiremos un valor de retorno. execErr := syscall.Exec(binary, args, env) if execErr != nil { panic(execErr) } }
// Run implements the running part of 'plz run'. func Run(graph *core.BuildGraph, label core.BuildLabel, args []string) { target := graph.TargetOrDie(label) if !target.IsBinary { log.Fatalf("Target %s cannot be run; it's not marked as binary", label) } // ReplaceSequences always quotes stuff in case it contains spaces or special characters, // that works fine if we interpret it as a shell but not to pass it as an argument here. cmd := strings.Trim(build.ReplaceSequences(target, fmt.Sprintf("$(out_exe %s)", target.Label)), "\"") // Handle targets where $(exe ...) returns something nontrivial splitCmd := strings.Split(cmd, " ") if !strings.Contains(splitCmd[0], "/") { // Probably it's a java -jar, we need an absolute path to it. cmd, err := exec.LookPath(splitCmd[0]) if err != nil { log.Fatalf("Can't find binary %s", splitCmd[0]) } splitCmd[0] = cmd } args = append(splitCmd, args...) log.Info("Running target %s...", strings.Join(args, " ")) output.SetWindowTitle("plz run: " + strings.Join(args, " ")) if err := syscall.Exec(splitCmd[0], args, os.Environ()); err != nil { log.Fatalf("Error running command %s: %s", strings.Join(args, " "), err) } }
func execDocker(config *Config, docker, cmd string, args []string) (*exec.Cmd, error) { if len(args) > 0 && args[0] == "docker" { args = args[1:] } log.Debugf("Launching Docker %s %s %v", docker, cmd, args) env := os.Environ() if len(config.Environment) != 0 { env = append(env, config.Environment...) } if config.Fork { cmd := exec.Command(docker, args...) if !config.NoLog { cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr } cmd.Env = env err := cmd.Start() return cmd, err } else { err := syscall.Exec(expand(docker), append([]string{cmd}, args...), env) return nil, err } }
func execBootstrap() error { command := []string{} if len(os.Args) == 2 { command = []string{"/bin/bash"} } else { if len(os.Args) == 3 && strings.Contains(os.Args[2], " ") { command = []string{"/bin/bash", "-c", os.Args[2]} } else { command = os.Args[2:] } } ioutil.WriteFile(os.Args[1], []byte{}, 0) ioutil.ReadFile(os.Args[1]) err := os.Remove(os.Args[1]) if err != nil { return fmt.Errorf( "can't remove control file '%s': %s", os.Args[1], err, ) } err = syscall.Exec(command[0], command[0:], os.Environ()) if err != nil { return fmt.Errorf( "can't execute bootstrapped command %q: %s", os.Args, err, ) } return nil }
// RestartProcess returns an error if things couldn't be // restarted. On success, this function never returns // because the process becomes the new process. func RestartProcess() error { path, err := SelfPath() if err != nil { return fmt.Errorf("RestartProcess failed: %v", err) } return syscall.Exec(path, os.Args, os.Environ()) }
func main() { log.SetFlags(0) // no timestamps on our logs if len(os.Args) <= 2 { log.Printf("Usage: %s user-spec command [args]", os.Args[0]) log.Printf(" ie: %s tianon bash", os.Args[0]) log.Printf(" %s nobody:root bash -c 'whoami && id'", os.Args[0]) log.Printf(" %s 1000:1 id", os.Args[0]) log.Println() log.Printf("%s version: %s (%s on %s/%s; %s)", os.Args[0], Version, runtime.Version(), runtime.GOOS, runtime.GOARCH, runtime.Compiler) log.Println() os.Exit(1) } // clear HOME so that SetupUser will set it os.Setenv("HOME", "") err := SetupUser(os.Args[1]) if err != nil { log.Fatalf("error: failed switching to %q: %v", os.Args[1], err) } name, err := exec.LookPath(os.Args[2]) if err != nil { log.Fatalf("error: %v", err) } err = syscall.Exec(name, os.Args[2:], os.Environ()) if err != nil { log.Fatalf("error: exec failed: %v", err) } }
func envAction(c *cli.Context) { cfg, err := config.LoadConfig() if err != nil { log.Fatal(err) } args := c.Args() if len(args) == 0 { return } osEnv := os.Environ() envMap := make(map[string]string, len(cfg.Rancher.Environment)+len(osEnv)) for k, v := range cfg.Rancher.Environment { envMap[k] = v } for k, v := range util.KVPairs2Map(osEnv) { envMap[k] = v } if cmd, err := exec.LookPath(args[0]); err != nil { log.Fatal(err) } else { args[0] = cmd } if err := syscall.Exec(args[0], args, util.Map2KVPairs(envMap)); err != nil { log.Fatal(err) } }
func main() { if len(os.Args) <= 1 { os.Exit(0) } args := os.Args[1:] signalWait := 20 if args[0] == "-s" { signalWait = 0 args = args[1:] } interfaceWait := 20 - signalWait usr2 := make(chan os.Signal) signal.Notify(usr2, syscall.SIGUSR2) select { case <-usr2: case <-time.After(time.Duration(signalWait) * time.Second): } _, err := net.EnsureInterface("ethwe", interfaceWait) checkErr(err) binary, err := exec.LookPath(args[0]) checkErr(err) checkErr(syscall.Exec(binary, args, os.Environ())) }
func main() { if len(os.Args) < 2 { os.Exit(1) } pid, errno := fork() if errno != 0 { log.Panicf("fork error: %s", errno.Error()) } if pid != 0 { // parent cmd, err := exec.LookPath(os.Args[1]) if err != nil { log.Panicf("Could not find executable %s", os.Args[1]) } syscall.Exec(cmd, os.Args[1:], os.Environ()) } // child username, err := exec.Command("whoami").Output() if err != nil { log.Panicf("whoami error: %s, out: %s", err, username) } if err := spawnSSHD(string(username)); err != nil { log.Fatal(err) } }
func main() { if len(os.Args) < 2 { log.Fatalln("Usage: asbox <user> <shell command> [args...]") } user, args := os.Args[1], os.Args[2:] databox, err := isDataboxUser(user) if err != nil { log.Fatalln("Unable to determine if", user, "is a databox user:"******"is not a databox user") } binary, err := exec.LookPath("su") if err != nil { log.Fatalln("Unable to find 'su':", err) } runtime.LockOSThread() err = syscall.Setuid(0) if err != nil { log.Fatalln("Unable to setuid") } args = append([]string{"su", "-", user, "-c", args[0], "--"}, args[1:]...) err = syscall.Exec(binary, args, os.Environ()) log.Fatalln("Failed to exec:", err) }
func namespaced() { dataDir := os.Args[1] realGraphDir := os.Args[2] graphDir := filepath.Join(realGraphDir, "graph") secretGraphDir := os.Args[3] pidFile := os.Args[4] mustRun(exec.Command("mount", "--make-slave", dataDir)) mustRun(exec.Command("chmod", "go-x", realGraphDir)) mustBindMountOnce(graphDir, secretGraphDir) programPath, err := exec.LookPath(os.Args[5]) if err != nil { fmt.Printf("failed to look path in namespace : %s\n", err) os.Exit(1) } pid := strconv.Itoa(os.Getpid()) err = ioutil.WriteFile(pidFile, []byte(pid), 0644) if err != nil { fmt.Printf("failed writing pidfile: %s\n", err) os.Exit(1) } err = syscall.Exec(programPath, os.Args[5:], os.Environ()) if err != nil { fmt.Printf("exec failed in namespace: %s\n", err) os.Exit(1) } }
func main() { fmt.Fprintf(os.Stdout, "[?] Enter flag{...} to w00t w00t: ") os.Stdout.Sync() runtime.LockOSThread() val, err := bufio.NewReader(os.Stdin).ReadString('\n') if err != nil { fmt.Fprintf(os.Stderr, "[!] error while reading flag: %s\n", err) os.Exit(1) } val = strings.TrimSpace(val) if val != flag { fmt.Fprintf(os.Stderr, "[-] m33p m33p failed to g3t gl4d0s :(\n") os.Exit(1) } fmt.Fprintf(os.Stdout, "[+] w00t w00t g0t gl4d0s :)\n") /* * We need to use dash because bash is broken. * No that isn't a joke, and yes it's cancer. */ syscall.Exec("/bin/dash", []string{"-dash"}, os.Environ()) }
func setupNamespace(args *InitArgs) error { if err := setupEnv(args); err != nil { return err } if err := setupHostname(args); err != nil { return err } if err := setupNetworking(args); err != nil { return err } if err := finalizeNamespace(args); err != nil { return err } path, err := exec.LookPath(args.Args[0]) if err != nil { log.Printf("Unable to locate %v", args.Args[0]) os.Exit(127) } if err := syscall.Exec(path, args.Args, os.Environ()); err != nil { return fmt.Errorf("dockerinit unable to execute %s - %s", path, err) } return nil }
func main() { var root, cmd string var opts []string if len(os.Args) < 3 { panic("not enough arguments\n") } root = os.Args[1] cmd = os.Args[2] if len(os.Args) > 3 { opts = os.Args[3:len(os.Args)] } rs, err := os.Stat(root) if err != nil { if os.IsNotExist(err) { panic(fmt.Sprintf("'%s' does not exist, cannot chroot there!", root)) } else { panic(fmt.Sprintf("Could not stat '%s': %s", root, err)) } } else { if !rs.Mode().IsDir() { panic(fmt.Sprintf("'%s' is not a directory, cannot chroot there!", root)) } } fmt.Printf("root: %s, cmd: %s, opts: %s\n", root, cmd, opts) err = os.Chdir(root) if err != nil { panic(fmt.Sprintf("chdir failed: %s", err)) } err = syscall.Chroot(root) if err != nil { panic(fmt.Sprintf("chroot failed: %s", err)) } // we're going to exec right away in the child, CLONE_VFORK will block the // parent from being scheduled until the child starts up, see clone(2) pid, err := lnxns.NsFork(lnxns.CLONE_VFORK) if err == syscall.EINVAL { panic("OS returned EINVAL. Make sure your kernel configuration includes all CONFIG_*_NS options.") } else if err != nil { panic(fmt.Sprintf("lnxns.NsFork() failed: %s", err)) } if pid != 0 { proc, _ := os.FindProcess(pid) proc.Wait() } else { err = syscall.Exec(cmd, opts, os.Environ()) if err != nil { panic(fmt.Sprintf("exec failed: %s", err)) } panic("impossible") } }
func execIfAliases(config *lxd.Config, origArgs []string) { newArgs := []string{} expandedAlias := false for _, arg := range origArgs { changed := false for k, v := range config.Aliases { if k == arg { expandedAlias = true changed = true newArgs = append(newArgs, strings.Split(v, " ")...) break } } if !changed { newArgs = append(newArgs, arg) } } if expandedAlias { path, err := exec.LookPath(origArgs[0]) if err != nil { fmt.Fprintf(os.Stderr, i18n.G("processing aliases failed %s\n"), err) os.Exit(5) } ret := syscall.Exec(path, newArgs, syscall.Environ()) fmt.Fprintf(os.Stderr, i18n.G("processing aliases failed %s\n"), ret) os.Exit(5) } }
func main() { // Для нашего примера мы выполним `ls`. Go требует абсолютный // путь к команде (программе) которую мы хотим отправить на выполнение, поэтому // мы будем использовать `exec.LookPath` для поиска местонахождения // `ls` (скорей всего `/bin/ls`). binary, lookErr := exec.LookPath("ls") if lookErr != nil { panic(lookErr) } // `Exec` требует аргументы в форме среза (вместо одной длинной строки). // Мы отправим как входные параметры несколько простых аргументов. Стоит заметить, // что первый аргумент должен быть название команды (программы). args := []string{"ls", "-a", "-l", "-h"} // `Exec`'у так же необходим набор [переменных окружения](environment-variables). // Мы будем просто использовать текущее окружение. env := os.Environ() // Это фактический вызов `syscall.Exec`. Если вызов будет успешным // выполнение нашей программы будет окончено тут и она будет заменена // процессом `/bin/ls -a -l -h`. Если произойдет ошибка, то мы ее // получим в возвращаемом значении. execErr := syscall.Exec(binary, args, env) if execErr != nil { panic(execErr) } }
func main() { var ( args = os.Args[1:] notInExec = true ) if len(args) > 0 && args[0] == "-s" { notInExec = false args = args[1:] } if notInExec { usr2 := make(chan os.Signal) signal.Notify(usr2, syscall.SIGUSR2) <-usr2 } _, err := weavenet.EnsureInterface("ethwe", -1) checkErr(err) if len(args) == 0 { checkErr(ErrNoCommandSpecified) } binary, err := exec.LookPath(args[0]) checkErr(err) checkErr(syscall.Exec(binary, args, os.Environ())) }
// restartProcess returns an error if things couldn't be // restarted. On success, this function never returns // because the process becomes the new process. func RestartProcess() error { path, err := selfPath() if err != nil { return err } return syscall.Exec(path, os.Args, os.Environ()) }
func init() { execdriver.RegisterInitFunc(DriverName, func(args *execdriver.InitArgs) error { if err := setupHostname(args); err != nil { return err } if err := setupNetworking(args); err != nil { return err } if err := setupCapabilities(args); err != nil { return err } if err := setupWorkingDirectory(args); err != nil { return err } if err := changeUser(args); err != nil { return err } path, err := exec.LookPath(args.Args[0]) if err != nil { log.Printf("Unable to locate %v", args.Args[0]) os.Exit(127) } if err := syscall.Exec(path, args.Args, os.Environ()); err != nil { return fmt.Errorf("dockerinit unable to execute %s - %s", path, err) } panic("Unreachable") }) }
func main() { //get the video metdata video, err := yt.Get("tyy2fJiOZDE") check(err) fmt.Println(video) //download the video and write to file video.Download(0, "video.mp4") //convert to mp3 avconvPath, pathErr := exec.LookPath("avconv") check(pathErr) args := []string{"avconv", "-i", "video.mp4", "audio.mp3"} env := os.Environ() sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigs }() fmt.Println(avconvPath, args) avconvErr := syscall.Exec(avconvPath, args, env) check(avconvErr) }
func main(cfg *config.CloudConfig) error { os.Unsetenv("_LIBCONTAINER_INITPIPE") os.Unsetenv("_LIBCONTAINER_INITPID") if err := system.ParentDeathSignal(syscall.SIGKILL).Set(); err != nil { return err } if err := os.Remove("/var/run/docker.pid"); err != nil && !os.IsNotExist(err) { return err } dockerCfg := cfg.Rancher.Docker args := dockerCfg.FullArgs() log.Debugf("User Docker args: %v", args) if dockerCfg.TLS { log.Debug("Generating TLS certs if needed") if err := control.Generate(true, "/etc/docker/tls", []string{"localhost"}); err != nil { return err } } prog := findProgram("docker-init", "dockerlaunch", "docker") if strings.Contains(prog, "dockerlaunch") { args = append([]string{prog, "docker"}, args...) } else { args = append([]string{prog}, args...) } log.Infof("Running %v", args) return syscall.Exec(args[0], args, dockerCfg.AppendEnv()) }
func init() { execdriver.RegisterInitFunc(DriverName, func(args *execdriver.InitArgs) error { runtime.LockOSThread() if err := setupEnv(args); err != nil { return err } if err := setupHostname(args); err != nil { return err } if err := setupNetworking(args); err != nil { return err } if err := finalizeNamespace(args); err != nil { return err } path, err := exec.LookPath(args.Args[0]) if err != nil { log.Printf("Unable to locate %v", args.Args[0]) os.Exit(127) } if err := syscall.Exec(path, args.Args, os.Environ()); err != nil { return fmt.Errorf("dockerinit unable to execute %s - %s", path, err) } panic("Unreachable") }) }
func main() { // For our example we'll exec `ls`. Go requires an // absolute path to the binary we want to execute, so // we'll use `exec.LookPath` to find it (probably // `/bin/ls`). binary, lookErr := exec.LookPath("ls") if lookErr != nil { panic(lookErr) } // `Exec` requires arguments in slice form (as // apposed to one big string). We'll give `ls` a few // common arguments. Note that the first argument should // be the program name. args := []string{"ls", "-a", "-l", "-h"} // `Exec` also needs a set of [environment variables](environment-variables) // to use. Here we just provide our current // environment. env := os.Environ() // Here's the actual `os.Exec` call. If this call is // successful, the execution of our process will end // here and be replaced by the `/bin/ls -a -l -h` // process. If there is an error we'll get a return // value. execErr := syscall.Exec(binary, args, env) if execErr != nil { panic(execErr) } }
func main() { var ( u *user.User err error username string program string command []string ) if len(os.Args[1:]) < 2 { fmt.Fprintf(os.Stderr, "Usage: %s USERNAME COMMAND [args...]\n", os.Args[0]) os.Exit(1) } username = os.Args[1] program = os.Args[2] command = append(command, os.Args[3:]...) if u, err = user.Lookup(username); err != nil { abort(err) } if program, err = exec.LookPath(program); err != nil { abort(err) } if err = setupEnv(u); err != nil { abort(err) } fmt.Println("Found binary at", program) fmt.Println("Args: ", command) if err = syscall.Exec(program, command, os.Environ()); err != nil { abort(err) } }
func execManPage(page string) { binaryPath := os.Args[0] gemDir := path.Dir(path.Dir(binaryPath)) manDir := path.Join(gemDir, "man/build") zeus := path.Join(manDir, page) syscall.Exec("/usr/bin/env", []string{"/usr/bin/env", "man", zeus}, os.Environ()) }
func handleSignals(processGroup *ProcessGroup, c <-chan os.Signal, startTime int, sockfile *os.File) { for { signal := <-c // os.Signal syscallSignal := signal.(syscall.Signal) switch syscallSignal { case syscall.SIGUSR1: socketMasterFdEnvVar := fmt.Sprintf("SOCKETMASTER_FD=%d", sockfile.Fd()) syscall.Exec(os.Args[0], os.Args, append(os.Environ(), socketMasterFdEnvVar)) case syscall.SIGHUP: process, err := processGroup.StartProcess() if err != nil { log.Printf("Could not start new process: %v\n", err) } else { if startTime > 0 { time.Sleep(time.Duration(startTime) * time.Millisecond) } // A possible improvement woud be to only swap the // process if the new child is still alive. processGroup.SignalAll(signal, process) } default: // Forward signal processGroup.SignalAll(signal, nil) } } }