utils.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. // License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package ssh
  3. import (
  4. "fmt"
  5. "io"
  6. "os/exec"
  7. "path/filepath"
  8. "regexp"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "kitty"
  13. "kitty/tools/config"
  14. "kitty/tools/utils"
  15. )
  16. var _ = fmt.Print
  17. var SSHExe = sync.OnceValue(func() string {
  18. return utils.FindExe("ssh")
  19. })
  20. var SSHOptions = sync.OnceValue(func() (ssh_options map[string]string) {
  21. defer func() {
  22. if ssh_options == nil {
  23. ssh_options = map[string]string{
  24. "4": "", "6": "", "A": "", "a": "", "C": "", "f": "", "G": "", "g": "", "K": "", "k": "",
  25. "M": "", "N": "", "n": "", "q": "", "s": "", "T": "", "t": "", "V": "", "v": "", "X": "",
  26. "x": "", "Y": "", "y": "", "B": "bind_interface", "b": "bind_address", "c": "cipher_spec",
  27. "D": "[bind_address:]port", "E": "log_file", "e": "escape_char", "F": "configfile", "I": "pkcs11",
  28. "i": "identity_file", "J": "[user@]host[:port]", "L": "address", "l": "login_name", "m": "mac_spec",
  29. "O": "ctl_cmd", "o": "option", "p": "port", "Q": "query_option", "R": "address",
  30. "S": "ctl_path", "W": "host:port", "w": "local_tun[:remote_tun]",
  31. }
  32. }
  33. }()
  34. cmd := exec.Command(SSHExe())
  35. stderr, err := cmd.StderrPipe()
  36. if err != nil {
  37. return
  38. }
  39. if err = cmd.Start(); err != nil {
  40. return
  41. }
  42. raw, err := io.ReadAll(stderr)
  43. if err != nil {
  44. return
  45. }
  46. text := utils.UnsafeBytesToString(raw)
  47. if strings.Contains(text, "OpenSSL version mismatch.") {
  48. // https://bugzilla.mindrot.org/show_bug.cgi?id=3548
  49. return
  50. }
  51. ssh_options = make(map[string]string, 32)
  52. for {
  53. pos := strings.IndexByte(text, '[')
  54. if pos < 0 {
  55. break
  56. }
  57. num := 1
  58. epos := pos
  59. for num > 0 {
  60. epos++
  61. switch text[epos] {
  62. case '[':
  63. num += 1
  64. case ']':
  65. num -= 1
  66. }
  67. }
  68. q := text[pos+1 : epos]
  69. text = text[epos:]
  70. if len(q) < 2 || !strings.HasPrefix(q, "-") {
  71. continue
  72. }
  73. opt, desc, found := strings.Cut(q, " ")
  74. if found {
  75. ssh_options[opt[1:]] = desc
  76. } else {
  77. for _, ch := range opt[1:] {
  78. ssh_options[string(ch)] = ""
  79. }
  80. }
  81. }
  82. return
  83. })
  84. func GetSSHCLI() (boolean_ssh_args *utils.Set[string], other_ssh_args *utils.Set[string]) {
  85. other_ssh_args, boolean_ssh_args = utils.NewSet[string](32), utils.NewSet[string](32)
  86. for k, v := range SSHOptions() {
  87. k = "-" + k
  88. if v == "" {
  89. boolean_ssh_args.Add(k)
  90. } else {
  91. other_ssh_args.Add(k)
  92. }
  93. }
  94. return
  95. }
  96. func is_extra_arg(arg string, extra_args []string) string {
  97. for _, x := range extra_args {
  98. if arg == x || strings.HasPrefix(arg, x+"=") {
  99. return x
  100. }
  101. }
  102. return ""
  103. }
  104. type ErrInvalidSSHArgs struct {
  105. Msg string
  106. }
  107. func (self *ErrInvalidSSHArgs) Error() string {
  108. return self.Msg
  109. }
  110. func PassthroughArgs() map[string]bool {
  111. return map[string]bool{"-N": true, "-n": true, "-f": true, "-G": true, "-T": true, "-V": true}
  112. }
  113. func ParseSSHArgs(args []string, extra_args ...string) (ssh_args []string, server_args []string, passthrough bool, found_extra_args []string, err error) {
  114. if extra_args == nil {
  115. extra_args = []string{}
  116. }
  117. if len(args) == 0 {
  118. passthrough = true
  119. return
  120. }
  121. passthrough_args := PassthroughArgs()
  122. boolean_ssh_args, other_ssh_args := GetSSHCLI()
  123. ssh_args, server_args, found_extra_args = make([]string, 0, 16), make([]string, 0, 16), make([]string, 0, 16)
  124. expecting_option_val := false
  125. stop_option_processing := false
  126. expecting_extra_val := ""
  127. for _, argument := range args {
  128. if len(server_args) > 1 || stop_option_processing {
  129. server_args = append(server_args, argument)
  130. continue
  131. }
  132. if strings.HasPrefix(argument, "-") && !expecting_option_val {
  133. if argument == "--" {
  134. stop_option_processing = true
  135. continue
  136. }
  137. if len(extra_args) > 0 {
  138. matching_ex := is_extra_arg(argument, extra_args)
  139. if matching_ex != "" {
  140. _, exval, found := strings.Cut(argument, "=")
  141. if found {
  142. found_extra_args = append(found_extra_args, matching_ex, exval)
  143. } else {
  144. expecting_extra_val = matching_ex
  145. expecting_option_val = true
  146. }
  147. continue
  148. }
  149. }
  150. // could be a multi-character option
  151. all_args := []rune(argument[1:])
  152. for i, ch := range all_args {
  153. arg := "-" + string(ch)
  154. if passthrough_args[arg] {
  155. passthrough = true
  156. }
  157. if boolean_ssh_args.Has(arg) {
  158. ssh_args = append(ssh_args, arg)
  159. continue
  160. }
  161. if other_ssh_args.Has(arg) {
  162. ssh_args = append(ssh_args, arg)
  163. if i+1 < len(all_args) {
  164. ssh_args = append(ssh_args, string(all_args[i+1:]))
  165. } else {
  166. expecting_option_val = true
  167. }
  168. break
  169. }
  170. err = &ErrInvalidSSHArgs{Msg: "unknown option -- " + arg[1:]}
  171. return
  172. }
  173. continue
  174. }
  175. if expecting_option_val {
  176. if expecting_extra_val != "" {
  177. found_extra_args = append(found_extra_args, expecting_extra_val, argument)
  178. } else {
  179. ssh_args = append(ssh_args, argument)
  180. }
  181. expecting_option_val = false
  182. continue
  183. }
  184. server_args = append(server_args, argument)
  185. }
  186. if len(server_args) == 0 && !passthrough {
  187. err = &ErrInvalidSSHArgs{Msg: ""}
  188. }
  189. return
  190. }
  191. type SSHVersion struct{ Major, Minor int }
  192. func (self SSHVersion) SupportsAskpassRequire() bool {
  193. return self.Major > 8 || (self.Major == 8 && self.Minor >= 4)
  194. }
  195. var GetSSHVersion = sync.OnceValue(func() SSHVersion {
  196. b, err := exec.Command(SSHExe(), "-V").CombinedOutput()
  197. if err != nil {
  198. return SSHVersion{}
  199. }
  200. m := regexp.MustCompile(`OpenSSH_(\d+).(\d+)`).FindSubmatch(b)
  201. if len(m) == 3 {
  202. maj, _ := strconv.Atoi(utils.UnsafeBytesToString(m[1]))
  203. min, _ := strconv.Atoi(utils.UnsafeBytesToString(m[2]))
  204. return SSHVersion{Major: maj, Minor: min}
  205. }
  206. return SSHVersion{}
  207. })
  208. type KittyOpts struct {
  209. Term, Shell_integration string
  210. }
  211. func read_relevant_kitty_opts(path string) KittyOpts {
  212. ans := KittyOpts{Term: kitty.KittyConfigDefaults.Term, Shell_integration: kitty.KittyConfigDefaults.Shell_integration}
  213. handle_line := func(key, val string) error {
  214. switch key {
  215. case "term":
  216. ans.Term = strings.TrimSpace(val)
  217. case "shell_integration":
  218. ans.Shell_integration = strings.TrimSpace(val)
  219. }
  220. return nil
  221. }
  222. cp := config.ConfigParser{LineHandler: handle_line}
  223. cp.ParseFiles(path)
  224. return ans
  225. }
  226. var RelevantKittyOpts = sync.OnceValue(func() KittyOpts {
  227. return read_relevant_kitty_opts(filepath.Join(utils.ConfigDir(), "kitty.conf"))
  228. })