main.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. package main
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "flag"
  7. "fmt"
  8. "io"
  9. "net"
  10. "os"
  11. "os/signal"
  12. "strings"
  13. "syscall"
  14. "time"
  15. "golang.org/x/crypto/ssh/terminal"
  16. )
  17. func main() {
  18. addr := flag.String("addr", "127.0.0.1:8282", "DebTik CLI server address")
  19. username := flag.String("u", "", "Username for automatic authentication")
  20. password := flag.String("p", "", "Password for automatic authentication")
  21. jsonOutput := flag.Bool("json", false, "Return a JSON envelope in single-command mode")
  22. passwordStdin := flag.Bool("password-stdin", false, "Read password from standard input (single-command mode)")
  23. timeout := flag.Duration("timeout", 60*time.Second, "Single-command timeout")
  24. cmdFlag := flag.String("c", "", "Execute a single command non-interactively and exit")
  25. flag.Parse()
  26. if *jsonOutput && *cmdFlag == "" {
  27. fmt.Fprintln(os.Stderr, "-json requires -c")
  28. os.Exit(1)
  29. }
  30. if *passwordStdin {
  31. if *cmdFlag == "" || *password != "" {
  32. fmt.Fprintln(os.Stderr, "-password-stdin requires -c and cannot be combined with -p")
  33. os.Exit(1)
  34. }
  35. line, err := bufio.NewReader(os.Stdin).ReadString('\n')
  36. if err != nil && !errors.Is(err, io.EOF) {
  37. fmt.Fprintln(os.Stderr, err)
  38. os.Exit(1)
  39. }
  40. *password = strings.TrimRight(line, "\r\n")
  41. }
  42. if *timeout <= 0 {
  43. fmt.Fprintln(os.Stderr, "-timeout must be positive")
  44. os.Exit(1)
  45. }
  46. conn, err := net.DialTimeout("tcp", *addr, 3*time.Second)
  47. if err != nil {
  48. fmt.Fprintf(os.Stderr, "\033[31mError: Could not connect to DebTik CLI service on %s\033[0m\n", *addr)
  49. fmt.Fprintf(os.Stderr, "Ensure debtik service is active and listening on port 8282.\n")
  50. os.Exit(1)
  51. }
  52. defer conn.Close()
  53. // If one-shot command execution is requested:
  54. if *cmdFlag != "" {
  55. if err := runOneShot(conn, *username, *password, *cmdFlag, *timeout, *jsonOutput); err != nil {
  56. fmt.Fprintln(os.Stderr, err)
  57. os.Exit(1)
  58. }
  59. return
  60. }
  61. // Interactive Mode
  62. if err := runInteractive(conn, *username, *password); err != nil {
  63. fmt.Fprintln(os.Stderr, err)
  64. os.Exit(1)
  65. }
  66. }
  67. func runOneShot(conn net.Conn, username, password, command string, timeout time.Duration, jsonOutput bool) error {
  68. reader := bufio.NewReader(conn)
  69. if username == "" || password == "" {
  70. return fmt.Errorf("single-command mode requires -u and -p")
  71. }
  72. if err := autoLogin(conn, reader, username, password, io.Discard); err != nil {
  73. return err
  74. }
  75. if strings.ContainsAny(command, "\r\n") {
  76. return fmt.Errorf("single-command mode accepts one line")
  77. }
  78. if err := conn.SetDeadline(time.Now().Add(timeout)); err != nil {
  79. return err
  80. }
  81. if _, err := fmt.Fprintf(conn, ":exec-status %s\n", command); err != nil {
  82. return err
  83. }
  84. data, err := io.ReadAll(reader)
  85. if err != nil {
  86. return fmt.Errorf("command failed or timed out: %w", err)
  87. }
  88. const begin = "DEBTIK-EXEC-BEGIN"
  89. const marker = "DEBTIK-EXEC-STATUS:"
  90. response := string(data)
  91. start := strings.Index(response, begin)
  92. index := strings.LastIndex(response, marker)
  93. if start < 0 || index < start+len(begin) {
  94. return fmt.Errorf("server did not return command status; update the server")
  95. }
  96. output := strings.TrimPrefix(response[start+len(begin):index], "\r\n")
  97. output = strings.TrimPrefix(output, "\n")
  98. status := strings.TrimSpace(response[index+len(marker):])
  99. if status != "0" && status != "1" {
  100. return fmt.Errorf("invalid command status")
  101. }
  102. if jsonOutput {
  103. if err := json.NewEncoder(os.Stdout).Encode(struct {
  104. Output string `json:"output"`
  105. Status int `json:"status"`
  106. OK bool `json:"ok"`
  107. }{output, int(status[0] - '0'), status == "0"}); err != nil {
  108. return err
  109. }
  110. } else {
  111. fmt.Print(output)
  112. }
  113. if status != "0" {
  114. return fmt.Errorf("command failed (status %s)", status)
  115. }
  116. return nil
  117. }
  118. func runInteractive(conn net.Conn, username, password string) error {
  119. reader := bufio.NewReader(conn)
  120. if username != "" || password != "" {
  121. if username == "" || password == "" {
  122. return fmt.Errorf("provide both -u and -p")
  123. }
  124. if err := autoLogin(conn, reader, username, password, os.Stdout); err != nil {
  125. return err
  126. }
  127. }
  128. fd := int(os.Stdin.Fd())
  129. if terminal.IsTerminal(fd) {
  130. oldState, err := terminal.MakeRaw(fd)
  131. if err != nil {
  132. return err
  133. }
  134. defer terminal.Restore(fd, oldState)
  135. }
  136. sigChan := make(chan os.Signal, 1)
  137. signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
  138. defer signal.Stop(sigChan)
  139. errChan := make(chan error, 2)
  140. go func() { _, err := io.Copy(os.Stdout, reader); errChan <- err }()
  141. go func() { _, err := io.Copy(conn, os.Stdin); errChan <- err }()
  142. select {
  143. case <-sigChan:
  144. return nil
  145. case err := <-errChan:
  146. if errors.Is(err, io.EOF) {
  147. return nil
  148. }
  149. return err
  150. }
  151. }
  152. func autoLogin(conn net.Conn, reader *bufio.Reader, username, password string, welcome io.Writer) error {
  153. if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil {
  154. return err
  155. }
  156. defer conn.SetDeadline(time.Time{})
  157. for _, prompt := range []struct{ text, reply string }{{"login:", username}, {"password:", password}} {
  158. var received strings.Builder
  159. for received.Len() < 65536 {
  160. ch, err := reader.ReadByte()
  161. if err != nil {
  162. return fmt.Errorf("authentication failed: %w", err)
  163. }
  164. received.WriteByte(ch)
  165. if strings.HasSuffix(strings.ToLower(received.String()), prompt.text) {
  166. if _, err := fmt.Fprintf(conn, "%s\n", prompt.reply); err != nil {
  167. return err
  168. }
  169. break
  170. }
  171. }
  172. if received.Len() >= 65536 {
  173. return fmt.Errorf("invalid login prompt")
  174. }
  175. }
  176. var received strings.Builder
  177. for received.Len() < 65536 {
  178. ch, err := reader.ReadByte()
  179. if err != nil {
  180. return fmt.Errorf("authentication failed: %w", err)
  181. }
  182. received.WriteByte(ch)
  183. text := received.String()
  184. if strings.Contains(strings.ToLower(text), "login failed:") {
  185. return fmt.Errorf("authentication rejected")
  186. }
  187. if strings.HasSuffix(text, "] > ") {
  188. _, err := fmt.Fprint(welcome, text)
  189. return err
  190. }
  191. }
  192. return fmt.Errorf("invalid authentication response")
  193. }