// parseExec parses the specified args for the specified command and generates
// an ExecConfig from it.
552356
func parseExec(opts execOptions, configFile *configfile.ConfigFile) *types.ExecConfig {
	execConfig := &types.ExecConfig{
		User:       opts.user,
		Privileged: opts.privileged,
		Tty:        opts.tty,
		Cmd:        opts.command,
		Detach:     opts.detach,
		Env:        opts.env.GetAll(),
		WorkingDir: opts.workdir,
	}

	// If -d is not set, attach to everything by default
	if !opts.detach {
		execConfig.AttachStdout = true
		execConfig.AttachStderr = true
		if opts.interactive {
			execConfig.AttachStdin = true
		}
	}

	if opts.detachKeys != "" {
		execConfig.DetachKeys = opts.detachKeys
	} else {
		execConfig.DetachKeys = configFile.DetachKeys
	}
	return execConfig
}
1050860
func (t *Tree) parseFunc(name *NameExpr) (Expr, error) {
	var args []Expr
	for {
		switch tok := t.peek(); tok.tokenType {
		case tokenEOF:
			return nil, newUnexpectedEOFError(tok)

		case tokenParensClose:
		// do nothing

		default:
			argexp, err := t.parseExpr()
			if err != nil {
				return nil, err
			}

			args = append(args, argexp)
		}

		switch tok := t.nextNonSpace(); tok.tokenType {
		case tokenEOF:
			return nil, newUnexpectedEOFError(tok)

		case tokenPunctuation:
			if tok.value != "," {
				return nil, newUnexpectedValueError(tok, ",")
			}

		case tokenParensClose:
			return NewFuncExpr(name.Name, args, name.Pos), nil

		default:
			return nil, newUnexpectedTokenError(tok, tokenPunctuation, tokenParensClose)
		}
	}
}
358059
func (c *Command) Parse(params []CommandInfoParam) ([]internal.ReflectManagedMethodExecuterSoapArgument, error) {
	flags := flag.NewFlagSet(strings.Join(c.name, " "), flag.ExitOnError)
	vals := make([]string, len(params))

	for i, p := range params {
		v := &vals[i]
		for _, a := range p.Aliases {
			a = strings.TrimPrefix(a[1:], "-")
			flags.StringVar(v, a, "", p.Help)
		}
	}

	err := flags.Parse(c.args)
	if err != nil {
		return nil, err
	}

	args := []internal.ReflectManagedMethodExecuterSoapArgument{}

	for i, p := range params {
		if vals[i] == "" {
			continue
		}
		args = append(args, c.Argument(p.Name, vals[i]))
	}

	return args, nil
}
1351931
func ParseAndRun(stdout, stderr io.Writer, stdin io.Reader, args []string) int {
	errlog := log.New(stderr, "", 0)
	out := log.New(stdout, "", 0)
	inv, cmd, err := Parse(stderr, stdout, args)
	inv.Stderr = stderr
	inv.Stdin = stdin
	if err == flag.ErrHelp {
		return 0
	}
	if err != nil {
		errlog.Println("Error:", err)
		return 2
	}

	switch cmd {
	case Version:
		out.Println("Mage Build Tool", gitTag)
		out.Println("Build Date:", timestamp)
		out.Println("Commit:", commitHash)
		out.Println("built with:", runtime.Version())
		return 0
	case Init:
		if err := generateInit(inv.Dir); err != nil {
			errlog.Println("Error:", err)
			return 1
		}
		out.Println(initFile, "created")
		return 0
	case Clean:
		if err := removeContents(inv.CacheDir); err != nil {
			out.Println("Error:", err)
			return 1
		}
		out.Println(inv.CacheDir, "cleaned")
		return 0
	case CompileStatic:
		return Invoke(inv)
	case None:
		return Invoke(inv)
	default:
		panic(fmt.Errorf("Unknown command type: %v", cmd))
	}
}
316362
func (t *TermHandlers) HandleExec(ch ssh.Channel, req *ssh.Request, ctx *ServerContext) error {
	execRequest, err := parseExecRequest(req, ctx)
	if err != nil {
		return trace.Wrap(err)
	}

	// a terminal has been previously allocate for this command.
	// run this inside an interactive session
	if ctx.GetTerm() != nil {
		return t.SessionRegistry.OpenSession(ch, req, ctx)
	}

	// If this code is running on a Teleport node and PAM is enabled, then open a
	// PAM context.
	var pamContext *pam.PAM
	if ctx.srv.Component() == teleport.ComponentNode {
		conf, err := t.SessionRegistry.srv.GetPAM()
		if err != nil {
			return trace.Wrap(err)
		}

		if conf.Enabled == true {
			// Note, stdout/stderr is discarded here, otherwise MOTD would be printed to
			// the users screen during exec requests.
			pamContext, err = pam.Open(&pam.Config{
				ServiceName: conf.ServiceName,
				Username:    ctx.Identity.Login,
				Stdin:       ch,
				Stderr:      ioutil.Discard,
				Stdout:      ioutil.Discard,
			})
			if err != nil {
				return trace.Wrap(err)
			}
			ctx.Debugf("Opening PAM context for exec request %q.", execRequest.GetCommand())
		}
	}

	// otherwise, regular execution
	result, err := execRequest.Start(ch)
	if err != nil {
		return trace.Wrap(err)
	}
	// if the program failed to start, we should send that result back
	if result != nil {
		ctx.Debugf("Exec request (%v) result: %v", execRequest, result)
		ctx.SendExecResult(*result)
	}

	// in case if result is nil and no error, this means that program is
	// running in the background
	go func() {
		result, err = execRequest.Wait()
		if err != nil {
			ctx.Errorf("Exec request (%v) wait failed: %v", execRequest, err)
		}
		if result != nil {
			ctx.SendExecResult(*result)
		}

		// If this code is running on a Teleport node and PAM is enabled, close the context.
		if ctx.srv.Component() == teleport.ComponentNode {
			conf, err := t.SessionRegistry.srv.GetPAM()
			if err != nil {
				ctx.Errorf("Unable to get PAM configuration from server: %v", err)
				return
			}

			if conf.Enabled == true {
				err = pamContext.Close()
				if err != nil {
					ctx.Errorf("Unable to close PAM context for exec request: %q: %v", execRequest.GetCommand(), err)
					return
				}
				ctx.Debugf("Closing PAM context for exec request: %q.", execRequest.GetCommand())
			}
		}
	}()

	return nil
}
1221937
func Parse(v interface{}) ([]string, error) {
	if command, _, err := generateCommand(v, true); err == nil {
		return command, err
	} else {
		return nil, err
	}
}
796999
func quoteExec(exec []string) string {
	if len(exec) == 0 {
		// existing callers always include at least the binary so this shouldn't occur.
		panic("empty exec")
	}

	var qexec []string
	for i, arg := range exec {
		escArg := execEscape(i, arg)
		qexec = append(qexec, escArg)
	}
	return strings.Join(qexec, " ")
}
949482
func (l *LibcontainerExecutor) Exec(deadline time.Time, cmd string, args []string) ([]byte, int, error) {
	combined := append([]string{cmd}, args...)
	// Capture output
	buf, _ := circbuf.NewBuffer(int64(drivers.CheckBufSize))

	process := &libcontainer.Process{
		Args:   combined,
		Env:    l.command.Env,
		Stdout: buf,
		Stderr: buf,
	}

	err := l.container.Run(process)
	if err != nil {
		return nil, 0, err
	}

	waitCh := make(chan *waitResult)
	defer close(waitCh)
	go l.handleExecWait(waitCh, process)

	select {
	case result := <-waitCh:
		ps := result.ps
		if result.err != nil {
			if exitErr, ok := result.err.(*exec.ExitError); ok {
				ps = exitErr.ProcessState
			} else {
				return nil, 0, result.err
			}
		}
		var exitCode int
		if status, ok := ps.Sys().(syscall.WaitStatus); ok {
			exitCode = status.ExitStatus()
		}
		return buf.Bytes(), exitCode, nil

	case <-time.After(time.Until(deadline)):
		process.Signal(os.Kill)
		return nil, 0, context.DeadlineExceeded
	}

}
429109
func parseDec(s string, start, stop int) (int, error) {
	result := 0
	neg := false
	if s[start] == '-' {
		neg = true
		start++
	}
	for i := start; i < stop; i++ {
		if c := s[i]; '0' <= c && c <= '9' {
			result = 10*result + int(c) - '0'
		} else {
			return 0, fmt.Errorf("invalid character: %q", c)
		}
	}
	if neg {
		result = -result
	}
	return result, nil
}
256711
func parseExpiry(data []byte) (*time.Duration, error) {
	expiry, err := base32ToUint64(data)
	if err != nil {
		return nil, err
	}

	duration := time.Duration(expiry) * time.Second

	return &duration, nil
}
649007
func (c *Client) Exec(cmd string) ([]byte, error) {
	session, err := c.SSHClient.NewSession()
	if err != nil {
		return nil, err
	}
	defer session.Close()

	return session.CombinedOutput(cmd)
}
482543
func (p *parser) parseEscape() (result string, err error) {
	if len(p.s) < p.i+2 || p.s[p.i] != '\\' {
		return "", errors.New("invalid escape sequence")
	}

	start := p.i + 1
	c := p.s[start]
	switch {
	case c == '\r' || c == '\n' || c == '\f':
		return "", errors.New("escaped line ending outside string")
	case hexDigit(c):
		// unicode escape (hex)
		var i int
		for i = start; i < p.i+6 && i < len(p.s) && hexDigit(p.s[i]); i++ {
			// empty
		}
		v, _ := strconv.ParseUint(p.s[start:i], 16, 21)
		if len(p.s) > i {
			switch p.s[i] {
			case '\r':
				i++
				if len(p.s) > i && p.s[i] == '\n' {
					i++
				}
			case ' ', '\t', '\n', '\f':
				i++
			}
		}
		p.i = i
		return string(rune(v)), nil
	}

	// Return the literal character after the backslash.
	result = p.s[start : start+1]
	p.i += 2
	return result, nil
}
67419
func (c *Ceph) exec(command string) (string, error) {
	cmdArgs := []string{"--conf", c.CephConfig, "--name", c.CephUser, "--format", "json"}
	cmdArgs = append(cmdArgs, strings.Split(command, " ")...)

	cmd := exec.Command(c.CephBinary, cmdArgs...)

	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		return "", fmt.Errorf("error running ceph %v: %s", command, err)
	}

	output := out.String()

	// Ceph doesn't sanitize its output, and may return invalid JSON.  Patch this
	// up for them, as having some inaccurate data is better than none.
	output = strings.Replace(output, "-inf", "0", -1)
	output = strings.Replace(output, "inf", "0", -1)

	return output, nil
}
1258792
func (c *DumpCommand) parseOpts(args []string) ([]string, error) {
	if err := c.flags.Parse(args); err != nil {
		return nil, err
	}

	conflictingOptsCount := 0
	if c.v4Only {
		conflictingOptsCount++
	}
	if c.v6Only {
		conflictingOptsCount++
	}
	if c.unixOnly {
		conflictingOptsCount++
	}
	if c.ifOnly {
		conflictingOptsCount++
	}
	if c.ipOnly {
		conflictingOptsCount++
	}
	if conflictingOptsCount > 1 {
		return nil, fmt.Errorf("Conflicting options specified, only one parsing mode may be specified at a time")
	}

	return c.flags.Args(), nil
}
1049091
func (c *TechSupportCommand) parseOpts(args []string) ([]string, error) {
	if err := c.flags.Parse(args); err != nil {
		return nil, err
	}

	switch c.outputMode {
	case "md", "markdown":
		c.outputMode = "md"
	case "raw":
	default:
		return nil, fmt.Errorf(`Invalid output mode %q, supported output types are "md" (default) and "raw"`, c.outputMode)
	}
	return c.flags.Args(), nil
}
1211744
func (p *Init) exec(ctx context.Context, path string, r *ExecConfig) (proc.Process, error) {
	// process exec request
	var spec specs.Process
	if err := json.Unmarshal(r.Spec.Value, &spec); err != nil {
		return nil, err
	}
	spec.Terminal = r.Terminal

	e := &execProcess{
		id:     r.ID,
		path:   path,
		parent: p,
		spec:   spec,
		stdio: proc.Stdio{
			Stdin:    r.Stdin,
			Stdout:   r.Stdout,
			Stderr:   r.Stderr,
			Terminal: r.Terminal,
		},
		waitBlock: make(chan struct{}),
		pid:       &safePid{},
	}
	e.execState = &execCreatedState{p: e}
	return e, nil
}
1100563
func (ts *TomlSource) Parse(cmd *flaeg.Command) (*flaeg.Command, error) {
	ts.fullPath = findFile(ts.filename, ts.dirNFullPath)
	if len(ts.fullPath) < 2 {
		return cmd, nil
	}

	metadata, err := toml.DecodeFile(ts.fullPath, cmd.Config)
	if err != nil {
		return nil, err
	}

	boolFlags, err := flaeg.GetBoolFlags(cmd.Config)
	if err != nil {
		return nil, err
	}

	flgArgs, hasUnderField := generateArgs(metadata, boolFlags)

	err = flaeg.Load(cmd.Config, cmd.DefaultPointersConfig, flgArgs)
	if err != nil && err != flaeg.ErrParserNotFound {
		return nil, err
	}

	if hasUnderField {
		_, err := toml.DecodeFile(ts.fullPath, cmd.Config)
		if err != nil {
			return nil, err
		}
	}

	return cmd, nil
}