main.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. // License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package at
  3. import (
  4. "bytes"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "os"
  10. "reflect"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "unicode/utf16"
  15. "golang.org/x/sys/unix"
  16. "kitty"
  17. "kitty/tools/cli"
  18. "kitty/tools/crypto"
  19. "kitty/tools/tty"
  20. "kitty/tools/tui"
  21. "kitty/tools/tui/loop"
  22. "kitty/tools/utils"
  23. "kitty/tools/utils/base85"
  24. "kitty/tools/utils/shlex"
  25. )
  26. const lowerhex = "0123456789abcdef"
  27. var ProtocolVersion [3]int = [3]int{0, 26, 0}
  28. type GlobalOptions struct {
  29. to_network, to_address, password string
  30. to_address_is_from_env_var bool
  31. already_setup bool
  32. }
  33. var global_options GlobalOptions
  34. func expand_ansi_c_escapes_in_args(args ...string) (escaped_string, error) {
  35. for i, x := range args {
  36. args[i] = shlex.ExpandANSICEscapes(x)
  37. }
  38. return escaped_string(strings.Join(args, " ")), nil
  39. }
  40. func escape_list_of_strings(args []string) []escaped_string {
  41. ans := make([]escaped_string, len(args))
  42. for i, x := range args {
  43. ans[i] = escaped_string(x)
  44. }
  45. return ans
  46. }
  47. func set_payload_string_field(io_data *rc_io_data, field, data string) {
  48. payload_interface := reflect.ValueOf(&io_data.rc.Payload).Elem()
  49. struct_in_interface := reflect.New(payload_interface.Elem().Type()).Elem()
  50. struct_in_interface.Set(payload_interface.Elem()) // copies the payload to struct_in_interface
  51. struct_in_interface.FieldByName(field).SetString(data)
  52. payload_interface.Set(struct_in_interface) // copies struct_in_interface back to payload
  53. }
  54. func get_pubkey(encoded_key string) (encryption_version string, pubkey []byte, err error) {
  55. if encoded_key == "" {
  56. encoded_key = os.Getenv("KITTY_PUBLIC_KEY")
  57. if encoded_key == "" {
  58. err = fmt.Errorf("Password usage requested but KITTY_PUBLIC_KEY environment variable is not available")
  59. return
  60. }
  61. }
  62. encryption_version, encoded_key, found := strings.Cut(encoded_key, ":")
  63. if !found {
  64. err = fmt.Errorf("KITTY_PUBLIC_KEY environment variable does not have a : in it")
  65. return
  66. }
  67. if encryption_version != kitty.RC_ENCRYPTION_PROTOCOL_VERSION {
  68. err = fmt.Errorf("KITTY_PUBLIC_KEY has unknown version, if you are running on a remote system, update kitty on this system")
  69. return
  70. }
  71. pubkey = make([]byte, base85.DecodedLen(len(encoded_key)))
  72. n, err := base85.Decode(pubkey, []byte(encoded_key))
  73. if err == nil {
  74. pubkey = pubkey[:n]
  75. }
  76. return
  77. }
  78. type escaped_string string
  79. func (s escaped_string) MarshalJSON() ([]byte, error) {
  80. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
  81. // we additionally escape all non-ascii chars so they can be safely transmitted inside an escape code
  82. src := utf16.Encode([]rune(s))
  83. buf := make([]byte, 0, len(src)+128)
  84. a := func(x ...byte) {
  85. buf = append(buf, x...)
  86. }
  87. a('"')
  88. for _, r := range src {
  89. if ' ' <= r && r <= 126 {
  90. if r == '\\' || r == '"' {
  91. buf = append(buf, '\\')
  92. }
  93. buf = append(buf, byte(r))
  94. continue
  95. }
  96. switch r {
  97. case '\n':
  98. a('\\', 'n')
  99. case '\t':
  100. a('\\', 't')
  101. case '\r':
  102. a('\\', 'r')
  103. case '\f':
  104. a('\\', 'f')
  105. case '\b':
  106. a('\\', 'b')
  107. default:
  108. a('\\', 'u')
  109. for s := 12; s >= 0; s -= 4 {
  110. a(lowerhex[r>>uint(s)&0xF])
  111. }
  112. }
  113. }
  114. a('"')
  115. return buf, nil
  116. }
  117. func simple_serializer(rc *utils.RemoteControlCmd) (ans []byte, err error) {
  118. return json.Marshal(rc)
  119. }
  120. type serializer_func func(rc *utils.RemoteControlCmd) ([]byte, error)
  121. func create_serializer(password string, encoded_pubkey string, io_data *rc_io_data) (err error) {
  122. io_data.serializer = simple_serializer
  123. if password != "" {
  124. encryption_version, pubkey, err := get_pubkey(encoded_pubkey)
  125. if err != nil {
  126. return err
  127. }
  128. io_data.serializer = func(rc *utils.RemoteControlCmd) (ans []byte, err error) {
  129. ec, err := crypto.Encrypt_cmd(rc, global_options.password, pubkey, encryption_version)
  130. if err != nil {
  131. return
  132. }
  133. return json.Marshal(ec)
  134. }
  135. if io_data.timeout < 120*time.Second {
  136. io_data.timeout = 120 * time.Second
  137. }
  138. }
  139. return nil
  140. }
  141. type ResponseData struct {
  142. as_str string
  143. is_string bool
  144. }
  145. func (self *ResponseData) UnmarshalJSON(data []byte) error {
  146. if bytes.HasPrefix(data, []byte("\"")) {
  147. self.is_string = true
  148. return json.Unmarshal(data, &self.as_str)
  149. }
  150. if bytes.Equal(data, []byte("true")) {
  151. self.as_str = "True"
  152. } else if bytes.Equal(data, []byte("false")) {
  153. self.as_str = "False"
  154. } else {
  155. self.as_str = string(data)
  156. }
  157. return nil
  158. }
  159. type Response struct {
  160. Ok bool `json:"ok"`
  161. Data ResponseData `json:"data,omitempty"`
  162. Error string `json:"error,omitempty"`
  163. Traceback string `json:"tb,omitempty"`
  164. }
  165. type rc_io_data struct {
  166. cmd *cli.Command
  167. rc *utils.RemoteControlCmd
  168. serializer serializer_func
  169. on_key_event func(lp *loop.Loop, ke *loop.KeyEvent) error
  170. string_response_is_err bool
  171. timeout time.Duration
  172. multiple_payload_generator func(io_data *rc_io_data) (bool, error)
  173. chunks_done bool
  174. }
  175. func (self *rc_io_data) next_chunk() (chunk []byte, err error) {
  176. if self.chunks_done {
  177. return make([]byte, 0), nil
  178. }
  179. if self.multiple_payload_generator != nil {
  180. is_last, err := self.multiple_payload_generator(self)
  181. if err != nil {
  182. return nil, err
  183. }
  184. if is_last {
  185. self.chunks_done = true
  186. }
  187. return self.serializer(self.rc)
  188. }
  189. self.chunks_done = true
  190. return self.serializer(self.rc)
  191. }
  192. func get_response(do_io func(io_data *rc_io_data) ([]byte, error), io_data *rc_io_data) (ans *Response, err error) {
  193. serialized_response, err := do_io(io_data)
  194. if err != nil {
  195. if errors.Is(err, os.ErrDeadlineExceeded) && io_data.rc.Async != "" {
  196. io_data.rc.Payload = nil
  197. io_data.rc.CancelAsync = true
  198. io_data.multiple_payload_generator = nil
  199. io_data.rc.NoResponse = true
  200. io_data.chunks_done = false
  201. _, _ = do_io(io_data)
  202. err = fmt.Errorf("Timed out waiting for a response from kitty")
  203. }
  204. return nil, err
  205. }
  206. if len(serialized_response) == 0 {
  207. if io_data.rc.NoResponse {
  208. res := Response{Ok: true}
  209. ans = &res
  210. return
  211. }
  212. err = fmt.Errorf("Received empty response from kitty")
  213. return
  214. }
  215. var response Response
  216. err = json.Unmarshal(serialized_response, &response)
  217. if err != nil {
  218. err = fmt.Errorf("Invalid response received from kitty, unmarshalling error: %w", err)
  219. return
  220. }
  221. ans = &response
  222. return
  223. }
  224. func send_rc_command(io_data *rc_io_data) (err error) {
  225. err = setup_global_options(io_data.cmd)
  226. if err != nil {
  227. return err
  228. }
  229. wid, err := strconv.Atoi(os.Getenv("KITTY_WINDOW_ID"))
  230. if err == nil && wid > 0 {
  231. io_data.rc.KittyWindowId = uint(wid)
  232. }
  233. err = create_serializer(global_options.password, "", io_data)
  234. if err != nil {
  235. return
  236. }
  237. var response *Response
  238. if global_options.to_network == "" {
  239. response, err = get_response(do_tty_io, io_data)
  240. if err != nil {
  241. return
  242. }
  243. } else {
  244. response, err = get_response(do_socket_io, io_data)
  245. if err != nil {
  246. return
  247. }
  248. }
  249. if err != nil || response == nil {
  250. return err
  251. }
  252. if !response.Ok {
  253. if response.Traceback != "" {
  254. fmt.Fprintln(os.Stderr, response.Traceback)
  255. }
  256. return fmt.Errorf("%s", response.Error)
  257. }
  258. if response.Data.is_string && io_data.string_response_is_err {
  259. return fmt.Errorf("%s", response.Data.as_str)
  260. }
  261. if response.Data.as_str != "" {
  262. fmt.Println(strings.TrimRight(response.Data.as_str, "\n \t"))
  263. }
  264. return
  265. }
  266. func get_password(password string, password_file string, password_env string, use_password string) (ans string, err error) {
  267. if use_password == "never" {
  268. return
  269. }
  270. if password != "" {
  271. ans = password
  272. }
  273. if ans == "" && password_file != "" {
  274. if password_file == "-" {
  275. if tty.IsTerminal(os.Stdin.Fd()) {
  276. ans, err = tui.ReadPassword("Password: ", true)
  277. if err != nil {
  278. return
  279. }
  280. } else {
  281. var q []byte
  282. q, err = io.ReadAll(os.Stdin)
  283. if err == nil {
  284. ans = strings.TrimRight(string(q), " \n\t")
  285. }
  286. ttyf, err := os.Open(tty.Ctermid())
  287. if err == nil {
  288. err = unix.Dup2(int(ttyf.Fd()), int(os.Stdin.Fd())) //nolint ineffassign err is returned indicating duping failed
  289. ttyf.Close()
  290. }
  291. }
  292. } else {
  293. var q []byte
  294. q, err = os.ReadFile(password_file)
  295. if err == nil {
  296. ans = strings.TrimRight(string(q), " \n\t")
  297. } else {
  298. if errors.Is(err, os.ErrNotExist) {
  299. err = nil
  300. }
  301. }
  302. }
  303. if err != nil {
  304. return
  305. }
  306. }
  307. if ans == "" && password_env != "" {
  308. ans = os.Getenv(password_env)
  309. }
  310. if ans == "" && use_password == "always" {
  311. return ans, fmt.Errorf("No password was found")
  312. }
  313. if len(ans) > 1024 {
  314. return ans, fmt.Errorf("Specified password is too long")
  315. }
  316. return ans, nil
  317. }
  318. var all_commands []func(*cli.Command) *cli.Command = make([]func(*cli.Command) *cli.Command, 0, 64)
  319. func register_at_cmd(f func(*cli.Command) *cli.Command) {
  320. all_commands = append(all_commands, f)
  321. }
  322. func setup_global_options(cmd *cli.Command) (err error) {
  323. if global_options.already_setup {
  324. return nil
  325. }
  326. err = cmd.GetOptionValues(&rc_global_opts)
  327. if err != nil {
  328. return err
  329. }
  330. if rc_global_opts.To == "" {
  331. rc_global_opts.To = os.Getenv("KITTY_LISTEN_ON")
  332. global_options.to_address_is_from_env_var = true
  333. }
  334. if rc_global_opts.To != "" {
  335. network, address, err := utils.ParseSocketAddress(rc_global_opts.To)
  336. if err != nil {
  337. return err
  338. }
  339. global_options.to_network = network
  340. global_options.to_address = address
  341. }
  342. q, err := get_password(rc_global_opts.Password, rc_global_opts.PasswordFile, rc_global_opts.PasswordEnv, rc_global_opts.UsePassword)
  343. global_options.password = q
  344. global_options.already_setup = true
  345. return err
  346. }
  347. func EntryPoint(tool_root *cli.Command) *cli.Command {
  348. at_root_command := tool_root.AddSubCommand(&cli.Command{
  349. Name: "@",
  350. Usage: "[global options] [sub-command] [sub-command options] [sub-command args]",
  351. ShortDescription: "Control kitty remotely",
  352. HelpText: "Control kitty by sending it commands. Set the allow_remote_control option in :file:`kitty.conf` for this to work. When run without any sub-commands this will start an interactive shell to control kitty.",
  353. Run: shell_main,
  354. })
  355. add_rc_global_opts(at_root_command)
  356. global_options_group := at_root_command.OptionGroups[0]
  357. for _, reg_func := range all_commands {
  358. c := reg_func(at_root_command)
  359. clone := tool_root.AddClone("", c)
  360. clone.Name = "@" + c.Name
  361. clone.Hidden = true
  362. clone.OptionGroups = append(clone.OptionGroups, global_options_group.Clone(clone))
  363. }
  364. return at_root_command
  365. }