robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

HX Lfix(channel): handle socket accept failure #412404b8c4dfc68

master
30.0 KiB1089 linesraw
1#include <assert.h>
2#include <fcntl.h>
3#include <inttypes.h>
4#include <lauxlib.h>
5#include <stddef.h>
6#include <stdio.h>
7#include <string.h>
8
9#include "klib/kvec.h"
10#include "nvim/api/private/converter.h"
11#include "nvim/api/private/defs.h"
12#include "nvim/api/private/helpers.h"
13#include "nvim/autocmd.h"
14#include "nvim/autocmd_defs.h"
15#include "nvim/buffer_defs.h"
16#include "nvim/channel.h"
17#include "nvim/errors.h"
18#include "nvim/eval.h"
19#include "nvim/eval/encode.h"
20#include "nvim/eval/typval.h"
21#include "nvim/event/loop.h"
22#include "nvim/event/multiqueue.h"
23#include "nvim/event/proc.h"
24#include "nvim/event/rstream.h"
25#include "nvim/event/socket.h"
26#include "nvim/event/stream.h"
27#include "nvim/event/wstream.h"
28#include "nvim/garray.h"
29#include "nvim/gettext_defs.h"
30#include "nvim/globals.h"
31#include "nvim/log.h"
32#include "nvim/lua/executor.h"
33#include "nvim/main.h"
34#include "nvim/mbyte.h"
35#include "nvim/memory.h"
36#include "nvim/memory_defs.h"
37#include "nvim/message.h"
38#include "nvim/msgpack_rpc/channel.h"
39#include "nvim/msgpack_rpc/server.h"
40#include "nvim/os/fs.h"
41#include "nvim/os/os.h"
42#include "nvim/os/os_defs.h"
43#include "nvim/os/shell.h"
44#include "nvim/terminal.h"
45#include "nvim/types_defs.h"
46#include "nvim/ui_client.h"
47
48#ifdef MSWIN
49# include "nvim/os/fs.h"
50# include "nvim/os/os_win_console.h"
51# include "nvim/os/pty_conpty_win.h"
52#endif
53
54static bool did_stdio = false;
55
56/// next free id for a job or rpc channel
57/// 1 is reserved for stdio channel
58/// 2 is reserved for stderr channel
59static uint64_t next_chan_id = CHAN_STDERR + 1;
60
61#include "channel.c.generated.h"
62
63/// Teardown the module
64void channel_teardown(void)
65{
66  Channel *chan;
67  map_foreach_value(&channels, chan, {
68    channel_close(chan->id, kChannelPartAll, NULL);
69  });
70}
71
72#ifdef EXITFREE
73void channel_free_all_mem(void)
74{
75  Channel *chan;
76  map_foreach_value(&channels, chan, {
77    channel_destroy(chan);
78  });
79  map_destroy(uint64_t, &channels);
80
81  callback_free(&on_print);
82}
83#endif
84
85/// Closes a channel
86///
87/// @param id The channel id
88/// @return true if successful, false otherwise
89bool channel_close(uint64_t id, ChannelPart part, const char **error)
90{
91  Channel *chan;
92  Proc *proc;
93
94  const char *dummy;
95  if (!error) {
96    error = &dummy;
97  }
98
99  if (!(chan = find_channel(id))) {
100    if (id < next_chan_id) {
101      // allow double close, even though we can't say what parts was valid.
102      return true;
103    }
104    *error = e_invchan;
105    return false;
106  }
107
108  bool close_main = false;
109  if (part == kChannelPartRpc || part == kChannelPartAll) {
110    close_main = true;
111    if (chan->is_rpc) {
112      rpc_close(chan);
113    } else if (part == kChannelPartRpc) {
114      *error = e_invstream;
115      return false;
116    }
117  } else if ((part == kChannelPartStdin || part == kChannelPartStdout)
118             && chan->is_rpc) {
119    *error = e_invstreamrpc;
120    return false;
121  }
122
123  switch (chan->streamtype) {
124  case kChannelStreamSocket:
125    if (!close_main) {
126      *error = e_invstream;
127      return false;
128    }
129    rstream_may_close(&chan->stream.socket);
130    break;
131
132  case kChannelStreamProc:
133    proc = &chan->stream.proc;
134    if (part == kChannelPartStdin || close_main) {
135      stream_may_close(&proc->in);
136    }
137    if (part == kChannelPartStdout || close_main) {
138      rstream_may_close(&proc->out);
139    }
140    if (part == kChannelPartStderr || part == kChannelPartAll) {
141      rstream_may_close(&proc->err);
142    }
143    if (proc->type == kProcTypePty && part == kChannelPartAll) {
144      pty_proc_close_master(&chan->stream.pty);
145    }
146
147    break;
148
149  case kChannelStreamStdio:
150    if (part == kChannelPartStdin || close_main) {
151      rstream_may_close(&chan->stream.stdio.in);
152    }
153    if (part == kChannelPartStdout || close_main) {
154      stream_may_close(&chan->stream.stdio.out);
155    }
156    if (part == kChannelPartStderr) {
157      *error = e_invstream;
158      return false;
159    }
160    break;
161
162  case kChannelStreamStderr:
163    if (part != kChannelPartAll && part != kChannelPartStderr) {
164      *error = e_invstream;
165      return false;
166    }
167    if (!chan->stream.err.closed) {
168      chan->stream.err.closed = true;
169      // Don't close on exit, in case late error messages
170      if (!exiting) {
171        // Don't close the file descriptor, as that may cause later writes to stderr
172        // to go to an unrelated file. Redirect it to NUL or /dev/null instead.
173#ifdef MSWIN
174        freopen("NUL:", "w", stderr);
175#else
176        freopen("/dev/null", "w", stderr);
177#endif
178      }
179      channel_decref(chan);
180    }
181    break;
182
183  case kChannelStreamInternal:
184    if (!close_main) {
185      *error = e_invstream;
186      return false;
187    }
188    if (chan->term) {
189      api_free_luaref(chan->stream.internal.cb);
190      chan->stream.internal.cb = LUA_NOREF;
191      chan->stream.internal.closed = true;
192      terminal_close(&chan->term, 0);
193      chan->exit_status = 0;
194    } else {
195      channel_decref(chan);
196    }
197    break;
198  }
199
200  return true;
201}
202
203/// Initializes the module
204void channel_init(void)
205{
206  channel_alloc(kChannelStreamStderr);
207  rpc_init();
208}
209
210/// Allocates a channel.
211///
212/// Channel is allocated with refcount 1, which should be decreased
213/// when the underlying stream closes.
214Channel *channel_alloc(ChannelStreamType type)
215  FUNC_ATTR_NONNULL_RET
216{
217  Channel *chan = xcalloc(1, sizeof(*chan));
218  if (type == kChannelStreamStdio) {
219    chan->id = CHAN_STDIO;
220  } else if (type == kChannelStreamStderr) {
221    chan->id = CHAN_STDERR;
222  } else {
223    chan->id = next_chan_id++;
224  }
225  chan->events = multiqueue_new_child(main_loop.events);
226  chan->refcount = 1;
227  chan->exit_status = -1;
228  chan->streamtype = type;
229  chan->detach = false;
230  assert(chan->id <= VARNUMBER_MAX);
231  pmap_put(uint64_t)(&channels, chan->id, chan);
232  return chan;
233}
234
235void channel_create_event(Channel *chan, const char *ext_source)
236{
237#ifdef NVIM_LOG_DEBUG
238  const char *source;
239
240  if (ext_source) {
241    // TODO(bfredl): in a future improved traceback solution,
242    // external events should be included.
243    source = ext_source;
244  } else {
245    eval_fmt_source_name_line(IObuff, sizeof(IObuff));
246    source = IObuff;
247  }
248
249  assert(chan->id <= VARNUMBER_MAX);
250  Arena arena = ARENA_EMPTY;
251  Dict info = channel_info(chan->id, &arena);
252  typval_T tv = TV_INITIAL_VALUE;
253  // TODO(bfredl): do the conversion in one step. Also would be nice
254  // to pretty print top level dict in defined order
255  object_to_vim(DICT_OBJ(info), &tv, NULL);
256  assert(tv.v_type == VAR_DICT);
257  char *str = encode_tv2json(&tv, NULL);
258  ILOG("new channel %" PRIu64 " (%s) : %s", chan->id, source, str);
259  xfree(str);
260  arena_mem_free(arena_finish(&arena));
261
262#else
263  (void)ext_source;
264#endif
265
266  channel_event(chan, EVENT_CHANOPEN);
267}
268
269void channel_incref(Channel *chan)
270{
271  chan->refcount++;
272}
273
274void channel_decref(Channel *chan)
275{
276  if (chan->refcount == 1 && !chan->did_close_event) {
277    chan->did_close_event = true;
278    channel_event(chan, EVENT_CHANCLOSE);
279  }
280
281  if (!(--chan->refcount)) {
282    // delay free, so that libuv is done with the handles
283    multiqueue_put(main_loop.events, free_channel_event, chan);
284  }
285}
286
287void callback_reader_free(CallbackReader *reader)
288{
289  callback_free(&reader->cb);
290  ga_clear(&reader->buffer);
291}
292
293void callback_reader_start(CallbackReader *reader, const char *type)
294{
295  ga_init(&reader->buffer, sizeof(char *), 32);
296  reader->type = type;
297}
298
299static void channel_destroy(Channel *chan)
300{
301  if (chan->is_rpc) {
302    rpc_free(chan);
303  }
304
305  if (chan->streamtype == kChannelStreamProc) {
306    proc_free(&chan->stream.proc);
307  }
308
309  callback_reader_free(&chan->on_data);
310  callback_reader_free(&chan->on_stderr);
311  callback_free(&chan->on_exit);
312
313  multiqueue_free(chan->events);
314  xfree(chan);
315}
316
317static void free_channel_event(void **argv)
318{
319  Channel *chan = argv[0];
320  pmap_del(uint64_t)(&channels, chan->id, NULL);
321  channel_destroy(chan);
322}
323
324static void channel_destroy_early(Channel *chan)
325{
326  if ((chan->id != --next_chan_id)) {
327    abort();
328  }
329  pmap_del(uint64_t)(&channels, chan->id, NULL);
330  chan->id = 0;
331
332  if ((--chan->refcount != 0)) {
333    abort();
334  }
335
336  // uv will keep a reference to handles until next loop tick, so delay free
337  multiqueue_put(main_loop.events, free_channel_event, chan);
338}
339
340static void close_cb(Stream *stream, void *data)
341{
342  channel_decref(data);
343}
344
345/// Starts a job and returns the associated channel
346///
347/// @param[in]  argv  Arguments vector specifying the command to run,
348///                   NULL-terminated
349/// @param[in]  exepath  The path to the executable. If NULL, use `argv[0]`.
350/// @param[in]  on_stdout  Callback to read the job's stdout
351/// @param[in]  on_stderr  Callback to read the job's stderr
352/// @param[in]  on_exit  Callback to receive the job's exit status
353/// @param[in]  pty  True if the job should run attached to a pty
354/// @param[in]  rpc  True to communicate with the job using msgpack-rpc,
355///                  `on_stdout` is ignored
356/// @param[in]  detach  True if the job should not be killed when nvim exits,
357///                     ignored if `pty` is true
358/// @param[in]  stdin_mode  Stdin mode. Either kChannelStdinPipe to open a
359///                         channel for stdin or kChannelStdinNull to leave
360///                         stdin disconnected.
361/// @param[in]  cwd  Initial working directory for the job.  Nvim's working
362///                  directory if `cwd` is NULL
363/// @param[in]  pty_width  Width of the pty, ignored if `pty` is false
364/// @param[in]  pty_height  Height of the pty, ignored if `pty` is false
365/// @param[in]  env  Nvim's configured environment is used if this is NULL,
366///                  otherwise defines all environment variables
367/// @param[out]  status_out  0 for invalid arguments, > 0 for the channel id,
368///                          < 0 if the job can't start
369///
370/// @returns [allocated] channel
371Channel *channel_job_start(char **argv, const char *exepath, CallbackReader on_stdout,
372                           CallbackReader on_stderr, Callback on_exit, bool pty, bool rpc,
373                           bool overlapped, bool detach, ChannelStdinMode stdin_mode,
374                           const char *cwd, uint16_t pty_width, uint16_t pty_height, dict_T *env,
375                           varnumber_T *status_out)
376{
377  Channel *chan = channel_alloc(kChannelStreamProc);
378  chan->on_data = on_stdout;
379  chan->on_stderr = on_stderr;
380  chan->on_exit = on_exit;
381
382  if (pty) {
383    if (detach) {
384      semsg(_(e_invarg2), "terminal/pty job cannot be detached");
385      shell_free_argv(argv);
386      if (env) {
387        tv_dict_free(env);
388      }
389      channel_destroy_early(chan);
390      *status_out = 0;
391      return NULL;
392    }
393    chan->stream.pty = pty_proc_init(&main_loop, chan);
394    if (pty_width > 0) {
395      chan->stream.pty.width = pty_width;
396    }
397    if (pty_height > 0) {
398      chan->stream.pty.height = pty_height;
399    }
400  } else {
401    chan->stream.uv = libuv_proc_init(&main_loop, chan);
402  }
403
404  Proc *proc = &chan->stream.proc;
405  proc->argv = argv;
406  proc->exepath = exepath;
407  proc->cb = channel_proc_exit_cb;
408  proc->state_cb = channel_proc_state_cb;
409  proc->events = chan->events;
410  proc->detach = detach;
411  proc->cwd = cwd;
412  proc->env = env;
413  proc->overlapped = overlapped;
414#ifdef MSWIN
415  // Windows: spawn channel jobs with noinherit (so writes don't leak to TUI #40074).
416  proc->stdio_noinherit = true;
417#endif
418
419  char *cmd = xstrdup(proc_get_exepath(proc));
420  bool has_out, has_err;
421  if (proc->type == kProcTypePty) {
422    has_out = true;
423    has_err = false;
424  } else {
425    has_out = rpc || callback_reader_set(chan->on_data);
426    has_err = callback_reader_set(chan->on_stderr);
427    proc->fwd_err = chan->on_stderr.fwd_err;
428#ifdef MSWIN
429    // DETACHED_PROCESS can't inherit console handles (like ConPTY stderr).
430    // Use a pipe relay: libuv creates a pipe, on_channel_output writes to stderr.
431    if (!has_err && proc->fwd_err && proc->detach) {
432      has_err = true;
433      proc->fwd_err = false;
434    }
435#endif
436  }
437
438  bool has_in = stdin_mode == kChannelStdinPipe;
439
440  int status = proc_spawn(proc, has_in, has_out, has_err);
441  if (status) {
442    semsg(_(e_jobspawn), os_strerror(status), cmd);
443    xfree(cmd);
444    if (proc->env) {
445      tv_dict_free(proc->env);
446    }
447    channel_destroy_early(chan);
448    *status_out = proc->status;
449    return NULL;
450  }
451  xfree(cmd);
452  if (proc->env) {
453    tv_dict_free(proc->env);
454  }
455
456  if (has_in) {
457    wstream_init(&proc->in, 0);
458  }
459  if (has_out) {
460    rstream_init(&proc->out);
461  }
462
463  if (rpc) {
464    // the rpc takes over the in and out streams
465    rpc_start(chan);
466  } else {
467    if (has_out) {
468      callback_reader_start(&chan->on_data, "stdout");
469      rstream_start(&proc->out, on_channel_data, chan);
470    }
471  }
472
473  if (has_err) {
474    callback_reader_start(&chan->on_stderr, "stderr");
475    rstream_init(&proc->err);
476    rstream_start(&proc->err, on_job_stderr, chan);
477  }
478
479  *status_out = (varnumber_T)chan->id;
480  return chan;
481}
482
483uint64_t channel_connect(bool tcp, const char *address, bool rpc, CallbackReader on_output,
484                         int timeout, const char **error)
485{
486  Channel *channel;
487
488  if (!tcp && rpc) {
489    if (server_owns_pipe_address(address)) {
490      // Create a loopback channel. This avoids deadlock if nvim connects to
491      // its own named pipe.
492      channel = channel_alloc(kChannelStreamInternal);
493      channel->stream.internal.cb = LUA_NOREF;
494      rpc_start(channel);
495      goto end;
496    }
497  }
498
499  channel = channel_alloc(kChannelStreamSocket);
500  if (!socket_connect(&main_loop, &channel->stream.socket,
501                      tcp, address, timeout, error)) {
502    // Don't use channel_destroy_early() as new channels may have been allocated
503    // by channel_from_connection() while polling for uv events.
504    channel_decref(channel);
505    return 0;
506  }
507
508  channel->stream.socket.s.internal_close_cb = close_cb;
509  channel->stream.socket.s.internal_data = channel;
510  wstream_init(&channel->stream.socket.s, 0);
511  rstream_init(&channel->stream.socket);
512
513  if (rpc) {
514    rpc_start(channel);
515  } else {
516    channel->on_data = on_output;
517    callback_reader_start(&channel->on_data, "data");
518    rstream_start(&channel->stream.socket, on_channel_data, channel);
519  }
520
521end:
522  channel_create_event(channel, address);
523  return channel->id;
524}
525
526/// Creates an RPC channel from a tcp/pipe socket connection
527///
528/// @param watcher The SocketWatcher ready to accept the connection
529void channel_from_connection(SocketWatcher *watcher)
530{
531  Channel *channel = channel_alloc(kChannelStreamSocket);
532  int result = socket_watcher_accept(watcher, &channel->stream.socket);
533  if (result != 0) {
534    ELOG("Failed to accept connection: %s", uv_strerror(result));
535    channel_destroy_early(channel);
536    return;
537  }
538  channel->stream.socket.s.internal_close_cb = close_cb;
539  channel->stream.socket.s.internal_data = channel;
540  wstream_init(&channel->stream.socket.s, 0);
541  rstream_init(&channel->stream.socket);
542  rpc_start(channel);
543  channel_create_event(channel, watcher->addr);
544}
545
546/// Creates an API channel from stdin/stdout. Used when embedding Nvim.
547uint64_t channel_from_stdio(bool rpc, CallbackReader on_output, const char **error)
548  FUNC_ATTR_NONNULL_ALL
549{
550  if (!headless_mode && !embedded_mode) {
551    *error = _("can only be opened in headless mode");
552    return 0;
553  }
554
555  if (did_stdio) {
556    *error = _("channel was already open");
557    return 0;
558  }
559  did_stdio = true;
560
561  Channel *channel = channel_alloc(kChannelStreamStdio);
562
563  int stdin_dup_fd = STDIN_FILENO;
564  int stdout_dup_fd = STDOUT_FILENO;
565#ifdef MSWIN
566  // Strangely, ConPTY doesn't work if stdin and stdout are pipes. So replace
567  // stdin and stdout with CONIN$ and CONOUT$, respectively.
568  if (embedded_mode && os_has_conpty_working()) {
569    stdin_dup_fd = os_dup_cloexec(STDIN_FILENO);
570    stdout_dup_fd = os_dup_cloexec(STDOUT_FILENO);
571    if (!GetConsoleWindow()) {
572      // Borrow the parent's console so CONOUT$ resolves to the real terminal,
573      // preserving io.stdout rendering (e.g. SIXEL/Kitty images). A replacement
574      // server started by :restart can reuse the current server's console.
575      // Only fall back to a hidden console when the parent has no console.
576      if (!AttachConsole(ATTACH_PARENT_PROCESS)) {
577        ILOG("parent console attach failed: %lu; allocating hidden console", GetLastError());
578        AllocConsole();
579        ShowWindow(GetConsoleWindow(), SW_HIDE);
580      }
581    }
582    os_reattach_console_stdio();
583  }
584#else
585  if (embedded_mode) {
586    // Redirect stdout/stdin (the UI channel) to stderr. Use fnctl(F_DUPFD_CLOEXEC) instead of dup()
587    // to prevent child processes from inheriting the file descriptors, which are used by UIs to
588    // detect when Nvim exits.
589    stdin_dup_fd = fcntl(STDIN_FILENO, F_DUPFD_CLOEXEC, STDERR_FILENO + 1);
590    stdout_dup_fd = fcntl(STDOUT_FILENO, F_DUPFD_CLOEXEC, STDERR_FILENO + 1);
591    dup2(STDERR_FILENO, STDOUT_FILENO);
592    dup2(STDERR_FILENO, STDIN_FILENO);
593  }
594#endif
595  rstream_init_fd(&main_loop, &channel->stream.stdio.in, stdin_dup_fd);
596  wstream_init_fd(&main_loop, &channel->stream.stdio.out, stdout_dup_fd, 0);
597
598  if (rpc) {
599    rpc_start(channel);
600  } else {
601    channel->on_data = on_output;
602    callback_reader_start(&channel->on_data, "stdin");
603    rstream_start(&channel->stream.stdio.in, on_channel_data, channel);
604  }
605
606  return channel->id;
607}
608
609/// @param data will be consumed
610size_t channel_send(uint64_t id, char *data, size_t len, bool data_owned, const char **error)
611  FUNC_ATTR_NONNULL_ALL
612{
613  Channel *chan = find_channel(id);
614  size_t written = 0;
615  if (!chan) {
616    *error = _(e_invchan);
617    goto retfree;
618  }
619
620  if (chan->streamtype == kChannelStreamStderr) {
621    if (chan->stream.err.closed) {
622      *error = _("Can't send data to closed stream");
623      goto retfree;
624    }
625    // unbuffered write
626    ptrdiff_t wres = os_write(STDERR_FILENO, data, len, false);
627    if (wres >= 0) {
628      written = (size_t)wres;
629    }
630    goto retfree;
631  }
632
633  if (chan->streamtype == kChannelStreamInternal) {
634    if (chan->is_rpc) {
635      *error = _("Can't send raw data to rpc channel");
636      goto retfree;
637    }
638    if (!chan->term || chan->stream.internal.closed) {
639      *error = _("Can't send data to closed stream");
640      goto retfree;
641    }
642    terminal_receive(chan->term, data, len);
643    written = len;
644    goto retfree;
645  }
646
647  Stream *in = channel_instream(chan);
648  if (in->closed) {
649    *error = _("Can't send data to closed stream");
650    goto retfree;
651  }
652
653  if (chan->is_rpc) {
654    *error = _("Can't send raw data to rpc channel");
655    goto retfree;
656  }
657
658  // write can be delayed indefinitely, so always use an allocated buffer
659  WBuffer *buf = wstream_new_buffer(data_owned ? data : xmemdup(data, len),
660                                    len, 1, xfree);
661  return wstream_write(in, buf) == 0 ? len : 0;
662
663retfree:
664  if (data_owned) {
665    xfree(data);
666  }
667  return written;
668}
669
670/// Convert binary byte array to a readfile()-style list
671///
672/// @param[in]  buf  Array to convert.
673/// @param[in]  len  Array length.
674///
675/// @return [allocated] Converted list.
676static inline list_T *buffer_to_tv_list(const char *const buf, const size_t len)
677  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_ALWAYS_INLINE
678{
679  list_T *const l = tv_list_alloc(kListLenMayKnow);
680  // Empty buffer should be represented by [''], encode_list_write() thinks
681  // empty list is fine for the case.
682  tv_list_append_string(l, "", 0);
683  if (len > 0) {
684    encode_list_write(l, buf, len);
685  }
686  return l;
687}
688
689size_t on_channel_data(RStream *stream, const char *buf, size_t count, void *data, bool eof)
690{
691  Channel *chan = data;
692  return on_channel_output(stream, chan, buf, count, eof, &chan->on_data);
693}
694
695size_t on_job_stderr(RStream *stream, const char *buf, size_t count, void *data, bool eof)
696{
697  Channel *chan = data;
698  return on_channel_output(stream, chan, buf, count, eof, &chan->on_stderr);
699}
700
701static size_t on_channel_output(RStream *stream, Channel *chan, const char *buf, size_t count,
702                                bool eof, CallbackReader *reader)
703{
704  if (chan->term) {
705    terminal_receive(chan->term, buf, count);
706  }
707
708  if (eof) {
709    reader->eof = true;
710  }
711
712#ifdef MSWIN
713  // Pipe relay for fwd_err on Windows: relay server stderr to stdout.
714  // DETACHED_PROCESS prevents inheriting console handles, so channel_job_start
715  // creates a pipe instead. Write to stdout because ConPTY only captures stdout.
716  // On non-Windows, fwd_err uses UV_INHERIT_FD directly; this path is never reached.
717  if (reader->fwd_err && count > 0) {
718    ptrdiff_t wres = os_write(STDOUT_FILENO, buf, count, false);
719    return (size_t)MAX(wres, 0);
720  }
721#endif
722
723  if (callback_reader_set(*reader)) {
724    ga_concat_len(&reader->buffer, buf, count);
725    schedule_channel_event(chan);
726  }
727
728  return count;
729}
730
731/// schedule the necessary callbacks to be invoked as a deferred event
732static void schedule_channel_event(Channel *chan)
733{
734  if (!chan->callback_scheduled) {
735    if (!chan->callback_busy) {
736      multiqueue_put(chan->events, on_channel_event, chan);
737      channel_incref(chan);
738    }
739    chan->callback_scheduled = true;
740  }
741}
742
743static void on_channel_event(void **args)
744{
745  Channel *chan = (Channel *)args[0];
746
747  chan->callback_busy = true;
748  chan->callback_scheduled = false;
749
750  int exit_status = chan->exit_status;
751  channel_reader_callbacks(chan, &chan->on_data);
752  channel_reader_callbacks(chan, &chan->on_stderr);
753  if (exit_status > -1) {
754    channel_callback_call(chan, NULL);
755    chan->exit_status = -1;
756  }
757
758  chan->callback_busy = false;
759  if (chan->callback_scheduled) {
760    // further callback was deferred to avoid recursion.
761    multiqueue_put(chan->events, on_channel_event, chan);
762    channel_incref(chan);
763  }
764
765  channel_decref(chan);
766}
767
768void channel_reader_callbacks(Channel *chan, CallbackReader *reader)
769{
770  if (reader->buffered) {
771    if (reader->eof) {
772      if (reader->self) {
773        if (tv_dict_find(reader->self, reader->type, -1) == NULL) {
774          list_T *data = buffer_to_tv_list(reader->buffer.ga_data,
775                                           (size_t)reader->buffer.ga_len);
776          tv_dict_add_list(reader->self, reader->type, strlen(reader->type),
777                           data);
778        } else {
779          semsg(_(e_streamkey), reader->type, chan->id);
780        }
781      } else {
782        channel_callback_call(chan, reader);
783      }
784      reader->eof = false;
785    }
786  } else {
787    bool is_eof = reader->eof;
788    if (reader->buffer.ga_len > 0) {
789      channel_callback_call(chan, reader);
790    }
791    // if the stream reached eof, invoke extra callback with no data
792    if (is_eof) {
793      channel_callback_call(chan, reader);
794      reader->eof = false;
795    }
796  }
797}
798
799static void channel_proc_exit_cb(Proc *proc, int status, void *data)
800{
801  Channel *chan = data;
802  if (chan->term) {
803    terminal_close(&chan->term, status);
804  }
805
806  // TODO(justinmk): figure out why rpc_close sometimes(??) isn't called.
807  // Theories:
808  // - EOF not received in receive_msgpack, then doesn't call chan_close_on_err().
809  // - proc_close_handles not tickled by ui_client.c's LOOP_PROCESS_EVENTS?
810  if (!exiting && ui_client_channel_id == chan->id) {
811    // rpc_close_event() could handle this in principle also for processes, but
812    // sometimes it gets called later than this, and we do care about the exit status
813    ui_client_attach_to_restarted_server(proc->status != 0);
814    if (ui_client_channel_id == chan->id) {
815      // If the current embedded server has exited and no new server is started,
816      // the client should exit with the same status.
817      exit_on_closed_chan(status);
818    }
819  }
820
821  // If process did not exit, we only closed the handle of a detached process.
822  bool exited = (status >= 0);
823  if (exited && chan->on_exit.type != kCallbackNone) {
824    schedule_channel_event(chan);
825  }
826  chan->exit_status = exited ? status : chan->exit_status;
827
828  channel_decref(chan);
829}
830
831static void channel_proc_state_cb(Proc *proc, bool suspended, void *data)
832{
833  Channel *chan = data;
834  if (chan->term) {
835    terminal_set_state(chan->term, suspended);
836  }
837}
838
839static void channel_callback_call(Channel *chan, CallbackReader *reader)
840{
841  Callback *cb;
842  typval_T argv[4];
843
844  argv[0].v_type = VAR_NUMBER;
845  argv[0].v_lock = VAR_UNLOCKED;
846  argv[0].vval.v_number = (varnumber_T)chan->id;
847
848  if (reader) {
849    argv[1].v_type = VAR_LIST;
850    argv[1].v_lock = VAR_UNLOCKED;
851    argv[1].vval.v_list = buffer_to_tv_list(reader->buffer.ga_data,
852                                            (size_t)reader->buffer.ga_len);
853    tv_list_ref(argv[1].vval.v_list);
854    ga_clear(&reader->buffer);
855    cb = &reader->cb;
856    argv[2].vval.v_string = (char *)reader->type;
857  } else {
858    argv[1].v_type = VAR_NUMBER;
859    argv[1].v_lock = VAR_UNLOCKED;
860    argv[1].vval.v_number = chan->exit_status;
861    cb = &chan->on_exit;
862    argv[2].vval.v_string = "exit";
863  }
864
865  argv[2].v_type = VAR_STRING;
866  argv[2].v_lock = VAR_UNLOCKED;
867
868  typval_T rettv = TV_INITIAL_VALUE;
869  callback_call(cb, 3, argv, &rettv);
870  tv_clear(&rettv);
871
872  if (reader) {
873    tv_list_unref(argv[1].vval.v_list);
874  }
875}
876
877/// Allocate terminal for channel
878///
879/// Channel `chan` is assumed to be an open pty channel,
880/// and `buf` is assumed to be a new, unmodified buffer.
881void channel_terminal_alloc(buf_T *buf, Channel *chan)
882{
883  TerminalOptions topts = {
884    .data = chan,
885    .width = chan->stream.pty.width,
886    .height = chan->stream.pty.height,
887    .read_pause_cb = term_read_pause,
888    .write_cb = term_write,
889    .resize_cb = term_resize,
890    .resume_cb = term_resume,
891    .close_cb = term_close,
892    .force_crlf = false,
893  };
894  buf->b_p_channel = (OptInt)chan->id;  // 'channel' option
895  channel_incref(chan);
896  chan->term = terminal_alloc(buf, topts);
897}
898
899static void term_read_pause(bool pause, void *data)
900{
901  Channel *chan = data;
902  if (chan->stream.proc.out.s.closed) {
903    return;
904  }
905  if (pause) {
906    rstream_stop_inner(&chan->stream.proc.out);
907  } else {
908    rstream_start_inner(&chan->stream.proc.out);
909  }
910}
911
912static void term_write(const char *buf, size_t size, void *data)
913{
914  Channel *chan = data;
915  if (chan->stream.proc.in.closed) {
916    // If the backing stream was closed abruptly, there may be write events
917    // ahead of the terminal close event. Just ignore the writes.
918    ILOG("write failed: stream is closed");
919    return;
920  }
921  WBuffer *wbuf = wstream_new_buffer(xmemdup(buf, size), size, 1, xfree);
922  wstream_write(&chan->stream.proc.in, wbuf);
923}
924
925static void term_resize(uint16_t width, uint16_t height, void *data)
926{
927  Channel *chan = data;
928  pty_proc_resize(&chan->stream.pty, width, height);
929}
930
931static void term_resume(void *data)
932{
933  Channel *chan = data;
934  pty_proc_resume(&chan->stream.pty);
935}
936
937static inline void term_delayed_free(void **argv)
938{
939  Channel *chan = argv[0];
940  if (chan->stream.proc.in.pending_reqs || chan->stream.proc.out.s.pending_reqs) {
941    multiqueue_put(chan->events, term_delayed_free, chan);
942    return;
943  }
944
945  if (chan->term) {
946    terminal_destroy(&chan->term);
947  }
948  channel_decref(chan);
949}
950
951static void term_close(void *data)
952{
953  Channel *chan = data;
954  proc_stop(&chan->stream.proc);
955  multiqueue_put(chan->events, term_delayed_free, data);
956}
957
958void channel_event(Channel *chan, event_T event)
959{
960  if (has_event(event)) {
961    channel_incref(chan);
962    multiqueue_put(main_loop.events, set_info_event, chan, (void *)(intptr_t)event);
963  }
964}
965
966static void set_info_event(void **argv)
967{
968  Channel *chan = argv[0];
969  event_T event = (event_T)(ptrdiff_t)argv[1];
970
971  save_v_event_T save_v_event;
972  dict_T *dict = get_v_event(&save_v_event);
973  Arena arena = ARENA_EMPTY;
974  Dict info = channel_info(chan->id, &arena);
975  typval_T retval;
976  object_to_vim(DICT_OBJ(info), &retval, NULL);
977  assert(retval.v_type == VAR_DICT);
978  tv_dict_add_dict(dict, S_LEN("info"), retval.vval.v_dict);
979  tv_dict_set_keys_readonly(dict);
980
981  apply_autocmds(event, NULL, NULL, true, curbuf);
982
983  restore_v_event(dict, &save_v_event);
984  arena_mem_free(arena_finish(&arena));
985  channel_decref(chan);
986}
987
988/// Unlike terminal_running(), this returns false immediately after stopping a job.
989/// However, this always returns false for nvim_open_term() terminals.
990bool channel_job_running(uint64_t id)
991{
992  Channel *chan = find_channel(id);
993  return (chan
994          && chan->streamtype == kChannelStreamProc
995          && !proc_is_stopped(&chan->stream.proc));
996}
997
998Dict channel_info(uint64_t id, Arena *arena)
999{
1000  Channel *chan = find_channel(id);
1001  if (!chan) {
1002    return (Dict)ARRAY_DICT_INIT;
1003  }
1004
1005  Dict info = arena_dict(arena, 9);
1006  PUT_C(info, "id", INTEGER_OBJ((Integer)chan->id));
1007
1008  const char *stream_desc, *mode_desc;
1009  switch (chan->streamtype) {
1010  case kChannelStreamProc: {
1011    stream_desc = "job";
1012    if (chan->stream.proc.type == kProcTypePty) {
1013      const char *name = pty_proc_tty_name(&chan->stream.pty);
1014      PUT_C(info, "pty", CSTR_TO_ARENA_OBJ(arena, name));
1015    }
1016
1017    char **args = chan->stream.proc.argv;
1018    Array argv = ARRAY_DICT_INIT;
1019    if (args != NULL) {
1020      size_t n;
1021      for (n = 0; args[n] != NULL; n++) {}
1022      argv = arena_array(arena, n);
1023      for (size_t i = 0; i < n; i++) {
1024        ADD_C(argv, CSTR_AS_OBJ(args[i]));
1025      }
1026    }
1027    PUT_C(info, "argv", ARRAY_OBJ(argv));
1028    break;
1029  }
1030
1031  case kChannelStreamStdio:
1032    stream_desc = "stdio";
1033    break;
1034
1035  case kChannelStreamStderr:
1036    stream_desc = "stderr";
1037    break;
1038
1039  case kChannelStreamInternal:
1040    PUT_C(info, "internal", BOOLEAN_OBJ(true));
1041    FALLTHROUGH;
1042
1043  case kChannelStreamSocket:
1044    stream_desc = "socket";
1045    break;
1046  }
1047  PUT_C(info, "stream", CSTR_AS_OBJ(stream_desc));
1048
1049  if (chan->is_rpc) {
1050    mode_desc = "rpc";
1051    PUT_C(info, "client", DICT_OBJ(chan->rpc.info));
1052  } else if (chan->term) {
1053    mode_desc = "terminal";
1054    PUT_C(info, "buf", BUFFER_OBJ(terminal_buf(chan->term)));
1055    PUT_C(info, "buffer", BUFFER_OBJ(terminal_buf(chan->term)));
1056    PUT_C(info, "exitcode", INTEGER_OBJ(chan->exit_status));
1057  } else {
1058    mode_desc = "bytes";
1059  }
1060  PUT_C(info, "mode", CSTR_AS_OBJ(mode_desc));
1061
1062  return info;
1063}
1064
1065/// Simple int64_t comparison function for use with qsort()
1066static int int64_t_cmp(const void *pa, const void *pb)
1067{
1068  const int64_t a = *(const int64_t *)pa;
1069  const int64_t b = *(const int64_t *)pb;
1070  return a == b ? 0 : a > b ? 1 : -1;
1071}
1072
1073Array channel_all_info(Arena *arena)
1074{
1075  // order the items in the array by channel number, for Determinismâ„¢
1076  kvec_t(int64_t) ids = KV_INITIAL_VALUE;
1077  kv_fixsize_arena(arena, ids, map_size(&channels));
1078  uint64_t id;
1079  map_foreach_key(&channels, id, {
1080    kv_push(ids, (int64_t)id);
1081  });
1082  qsort(ids.items, ids.size, sizeof ids.items[0], int64_t_cmp);
1083
1084  Array ret = arena_array(arena, ids.size);
1085  for (size_t i = 0; i < ids.size; i++) {
1086    ADD_C(ret, DICT_OBJ(channel_info((uint64_t)ids.items[i], arena)));
1087  }
1088  return ret;
1089}