command.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. package commands
  2. import (
  3. "errors"
  4. "flag"
  5. "fmt"
  6. "io"
  7. "strings"
  8. )
  9. // CommandFlags is called before help or command execution to parse command line flags.
  10. // It should return a flag.FlagSet instance and a pointer to the struct that will contain parsed flags
  11. //
  12. // Every call must build a fresh FlagSet and a fresh struct. Nothing may be shared between
  13. // calls: a command runs on more than one surface and on more than one goroutine.
  14. type CommandFlags func() (*flag.FlagSet, any)
  15. // RunFunc computes a command's Result.
  16. //
  17. // fs is the pointer returned by Command.Flags, if there was one; -h, -help, -json and
  18. // -pretty are reserved and handled before Run is called. a is the operands: whatever
  19. // was not consumed as a flag. The Result is rendered by whichever surface asked: Value
  20. // for a command that reports, Did or Failed for one that acts, Nothing for one with
  21. // nothing to say. An error is for a failure of the command itself; a bad argument is
  22. // Failed, so the caller hears why in its own format.
  23. type RunFunc func(fs any, a []string) (Result, error)
  24. // TextFunc renders a Result's Value for a person. See Typed for declaring one against
  25. // the type the command actually returns.
  26. type TextFunc func(v any, w io.Writer) error
  27. type Command struct {
  28. Name Name
  29. ShortDescription string
  30. Help string
  31. // Identity declares that the command reports only what a certificate says about a
  32. // host: its name, addresses, groups and validity. Nothing operational: no underlay
  33. // addresses, no configuration, nothing a command could change. The info API, which
  34. // an operator may open to other users on the host, serves these and help alone; see
  35. // localapi.
  36. Identity bool
  37. Flags CommandFlags
  38. // Run produces the command's Result, leaving presentation to Render.
  39. Run RunFunc
  40. // Text renders a Result's Value for a person. Both surfaces call it, so a command
  41. // reads the same over ssh as it does through the control socket. It never sees an
  42. // outcome: Render prints those itself, the same way for every command. Leaving it
  43. // nil declares that no human rendering of the Value exists yet, which JSONOnly says
  44. // up front; Render then refuses text rather than inventing an interim form for
  45. // people to script against.
  46. Text TextFunc
  47. // JSONOnly declares that the command's Value has no human rendering yet, so a surface
  48. // whose default is text asks for JSON instead, and the schema says so to a client. It
  49. // is a statement that no such form exists, not a fallback. A refusal is still
  50. // rendered as a sentence, since that always has a human form.
  51. JSONOnly bool
  52. // Then, when set, is the second half of a command that acts: Run says what is about
  53. // to happen and Then does it and says how it went, with its Result rendered after
  54. // Run's and deciding the outcome. It exists for a command whose action can cut off
  55. // its own reply: reload restarts the ssh server when the sshd keys changed, which
  56. // ends the session that asked, so Run's line has to be on the wire before the reload
  57. // begins. A surface that answers in one piece, the control socket, runs Then before
  58. // it answers and carries both.
  59. Then func() Result
  60. }
  61. // Failure is the error a surface gets for a refusal the person has already been shown:
  62. // a Run that returned Failed, a command that is not there, a line that would not parse.
  63. // The message it rendered is the whole story, so the surface reports the failure, exit
  64. // status 1 over ssh, and does not log it.
  65. type Failure struct {
  66. Msg string
  67. }
  68. func (f *Failure) Error() string {
  69. return f.Msg
  70. }
  71. // commandFlags returns the FlagSet a command is driven through, on any surface: the
  72. // command's own flags, if it declares any, with the two presentation flags added. own
  73. // reports whether the command declared any of its own, which is what tells a caller
  74. // whether to say a parameter is unknown or that the command takes none at all.
  75. //
  76. // The presentation flags are defined here rather than by each command, because how a
  77. // result is displayed is not a property of the command that produced it. This is also
  78. // the one definition of them: the ssh line parses into it, nebula ctl parses its line
  79. // against the schema derived from it, and help renders from that schema. They are
  80. // command line flags only: a socket request chooses its rendering with the envelope's
  81. // format field, and Invoke refuses them as parameters.
  82. func commandFlags(c *Command) (fl *flag.FlagSet, fs any, own bool) {
  83. if c.Flags != nil {
  84. fl, fs = c.Flags()
  85. }
  86. own = fl != nil
  87. if fl == nil {
  88. fl = flag.NewFlagSet(string(c.Name), flag.ContinueOnError)
  89. }
  90. addPresentationFlags(fl)
  91. // What Parse prints after a bad flag, and for -h: the command's usage as help renders
  92. // it, so a line that went wrong is answered with the same text as `help <command>`.
  93. fl.Usage = func() { _ = WriteCommandHelp(schemaOf(c, fl), fl.Output()) }
  94. return fl, fs, own
  95. }
  96. // addPresentationFlags defines the two presentation flags on fl.
  97. func addPresentationFlags(fl *flag.FlagSet) {
  98. fl.Bool(FlagJSON, false, "outputs as json")
  99. fl.Bool(FlagPretty, false, "pretty prints json, assumes -json")
  100. }
  101. // Flagged fills in c's Flags and Run as a pair: define declares the flags on a fresh F,
  102. // and run is handed that F. The struct the flags fill is the struct Run reads by
  103. // construction, so no Run has to assert the type it was given or decide what to do
  104. // when the assertion fails.
  105. func Flagged[F any](c *Command, define func(*flag.FlagSet, *F), run func(*F, []string) (Result, error)) *Command {
  106. c.Flags = func() (*flag.FlagSet, any) {
  107. fl := flag.NewFlagSet("", flag.ContinueOnError)
  108. s := new(F)
  109. define(fl, s)
  110. return fl, s
  111. }
  112. c.Run = func(fs any, a []string) (Result, error) {
  113. s, ok := fs.(*F)
  114. if !ok {
  115. return Result{}, fmt.Errorf("%s was handed %T for its flags, not %T", c.Name, fs, s)
  116. }
  117. return run(s, a)
  118. }
  119. return c
  120. }
  121. // isPresentationFlag reports whether name is one of the two flags commandFlags adds.
  122. func isPresentationFlag(name string) bool {
  123. return name == FlagJSON || name == FlagPretty
  124. }
  125. // execLine runs an ssh command line against c, reporting problems to w. The line is
  126. // parsed into the command's own FlagSet and Run reads it directly, so a flag.Value whose
  127. // String does not re-parse, flag.Func above all, arrives as the line said. Invoke fills
  128. // the same FlagSet through Set.
  129. func (r *Registry) execLine(c *Command, args []string, w Output) error {
  130. fl, fs, _ := commandFlags(c)
  131. // Parse reports a bad flag to this writer, with the command's usage after it. -h,
  132. // -help and --help take the same path with nothing wrong: the usage is the whole
  133. // answer, and Parse says so with ErrHelp. A -h that is a flag's value or follows --
  134. // is read as the operand it is, since ParseArgs is the one reading of the line.
  135. fl.SetOutput(w.Err)
  136. operands, err := ParseArgs(fl, args)
  137. if err != nil {
  138. if errors.Is(err, flag.ErrHelp) {
  139. return nil
  140. }
  141. return err
  142. }
  143. format := presentationFormat(fl)
  144. // An error from Run is something the command could not do rather than a refusal it
  145. // chose, but the person at the prompt still hears it; the surface logs it too.
  146. res, err := c.Run(fs, operands)
  147. if err != nil {
  148. _, _ = fmt.Fprintln(w.Err, err.Error())
  149. return err
  150. }
  151. // Run's reply goes out first, and then the action, if the command has one, whose
  152. // Result is the outcome. In JSON only the outcome travels: the promise is for a
  153. // person to read, and a program expects one document.
  154. if c.Then == nil || r.formatFor(c, res, format) == FormatText {
  155. if err := r.renderLine(c, res, format, w); err != nil {
  156. return err
  157. }
  158. }
  159. if c.Then != nil {
  160. res = c.Then()
  161. if err := r.renderLine(c, res, format, w); err != nil {
  162. return err
  163. }
  164. }
  165. if !res.OK {
  166. return &Failure{Msg: res.Reason}
  167. }
  168. return nil
  169. }
  170. // formatFor is the format a Result is rendered in. The line wins when it asked for one;
  171. // otherwise the surface that owns the registry decides, from the command and its
  172. // Result, so each surface can keep its own default.
  173. func (r *Registry) formatFor(c *Command, res Result, format Format) Format {
  174. if format == FormatUnset {
  175. return r.defaultFormatFor(c, res)
  176. }
  177. return format
  178. }
  179. // renderLine writes one Result of a command line to w; see formatFor. An empty Result
  180. // writes nothing.
  181. func (r *Registry) renderLine(c *Command, res Result, format Format, w Output) error {
  182. if res.Empty() {
  183. return nil
  184. }
  185. if err := Render(c, res, r.formatFor(c, res, format), w.Out); err != nil {
  186. if errors.Is(err, ErrNoTextRendering) {
  187. _, _ = fmt.Fprintln(w.Err, err.Error())
  188. }
  189. return err
  190. }
  191. return nil
  192. }
  193. // ParseArgs parses args with fl and returns the operands.
  194. //
  195. // It differs from fl.Parse in two ways, and both surfaces parse through here so a line
  196. // means the same typed at an ssh prompt or to nebula ctl.
  197. //
  198. // Flags and operands may come in any order, which is the one way it differs from
  199. // fl.Parse. Parse stops at the first operand, so `print-tunnel 10.0.0.1 -json` would
  200. // reach the command with "-json" as a second operand and the flag silently dropped. Here
  201. // an operand ends nothing: parsing resumes after it, and only "--" ends the flags, with
  202. // everything after it an operand. What counts as a flag is Parse's rule: every argument
  203. // that starts with "-", a negative number included, so one that is meant as an operand
  204. // goes after "--".
  205. func ParseArgs(fl *flag.FlagSet, args []string) ([]string, error) {
  206. operands := make([]string, 0, len(args))
  207. for len(args) > 0 {
  208. // Walk the flags the way Parse will, to the first argument it would not read as a
  209. // flag: an operand or the terminator. Everything before it is Parse's.
  210. end := len(args)
  211. for i := 0; i < len(args); {
  212. a := args[i]
  213. if a == "--" {
  214. if err := fl.Parse(args[:i]); err != nil {
  215. return nil, err
  216. }
  217. return append(operands, args[i+1:]...), nil
  218. }
  219. if len(a) < 2 || a[0] != '-' {
  220. end = i
  221. break
  222. }
  223. f, hasValue := LookupArg(fl, a)
  224. if f == nil {
  225. // An undefined flag: leave it for Parse to report.
  226. i++
  227. continue
  228. }
  229. if hasValue || IsBoolFlag(f) {
  230. i++
  231. } else {
  232. // The flag's value is the next argument, whatever it looks like.
  233. i += 2
  234. }
  235. }
  236. if err := fl.Parse(args[:end]); err != nil {
  237. return nil, err
  238. }
  239. if end == len(args) {
  240. break
  241. }
  242. operands = append(operands, args[end])
  243. args = args[end+1:]
  244. }
  245. return operands, nil
  246. }
  247. // LookupArg reads arg the way Parse does: one or two leading dashes, the flag's name, and
  248. // an optional "=value". f is the flag of fl by that name, nil when fl has none, and
  249. // hasValue reports that the value came with the argument rather than in the one after it.
  250. // It is the one reading of an argument's shape: ParseArgs walks a line with it, and
  251. // nebula ctl lifts its own flags out of a line with it, so the two cannot disagree about
  252. // which word is a flag's value.
  253. func LookupArg(fl *flag.FlagSet, arg string) (f *flag.Flag, hasValue bool) {
  254. name := strings.TrimPrefix(strings.TrimPrefix(arg, "-"), "-")
  255. if eq := strings.IndexByte(name, '='); eq >= 0 {
  256. name, hasValue = name[:eq], true
  257. }
  258. return fl.Lookup(name), hasValue
  259. }
  260. // IsBoolFlag reports whether f is satisfied by its presence alone and never reads the
  261. // argument after it as its value. The flag package marks these with an unexported
  262. // interface, which is the only way to tell.
  263. func IsBoolFlag(f *flag.Flag) bool {
  264. bf, ok := f.Value.(interface{ IsBoolFlag() bool })
  265. return ok && bf.IsBoolFlag()
  266. }