xref: /vim-8.2.3635/src/channel.c (revision 94688b8a)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  */
8 
9 /*
10  * Implements communication through a socket or any file handle.
11  */
12 
13 #include "vim.h"
14 
15 #if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
16 
17 /* TRUE when netbeans is running with a GUI. */
18 #ifdef FEAT_GUI
19 # define CH_HAS_GUI (gui.in_use || gui.starting)
20 #endif
21 
22 /* Note: when making changes here also adjust configure.ac. */
23 #ifdef WIN32
24 /* WinSock API is separated from C API, thus we can't use read(), write(),
25  * errno... */
26 # define SOCK_ERRNO errno = WSAGetLastError()
27 # undef ECONNREFUSED
28 # define ECONNREFUSED WSAECONNREFUSED
29 # undef EWOULDBLOCK
30 # define EWOULDBLOCK WSAEWOULDBLOCK
31 # undef EINPROGRESS
32 # define EINPROGRESS WSAEINPROGRESS
33 # ifdef EINTR
34 #  undef EINTR
35 # endif
36 # define EINTR WSAEINTR
37 # define sock_write(sd, buf, len) send((SOCKET)sd, buf, len, 0)
38 # define sock_read(sd, buf, len) recv((SOCKET)sd, buf, len, 0)
39 # define sock_close(sd) closesocket((SOCKET)sd)
40 #else
41 # include <netdb.h>
42 # include <netinet/in.h>
43 
44 # include <sys/socket.h>
45 # ifdef HAVE_LIBGEN_H
46 #  include <libgen.h>
47 # endif
48 # define SOCK_ERRNO
49 # define sock_write(sd, buf, len) write(sd, buf, len)
50 # define sock_read(sd, buf, len) read(sd, buf, len)
51 # define sock_close(sd) close(sd)
52 # define fd_read(fd, buf, len) read(fd, buf, len)
53 # define fd_write(sd, buf, len) write(sd, buf, len)
54 # define fd_close(sd) close(sd)
55 #endif
56 
57 static void channel_read(channel_T *channel, ch_part_T part, char *func);
58 
59 /* Whether a redraw is needed for appending a line to a buffer. */
60 static int channel_need_redraw = FALSE;
61 
62 /* Whether we are inside channel_parse_messages() or another situation where it
63  * is safe to invoke callbacks. */
64 static int safe_to_invoke_callback = 0;
65 
66 static char *part_names[] = {"sock", "out", "err", "in"};
67 
68 #ifdef WIN32
69     static int
70 fd_read(sock_T fd, char *buf, size_t len)
71 {
72     HANDLE h = (HANDLE)fd;
73     DWORD nread;
74 
75     if (!ReadFile(h, buf, (DWORD)len, &nread, NULL))
76 	return -1;
77     return (int)nread;
78 }
79 
80     static int
81 fd_write(sock_T fd, char *buf, size_t len)
82 {
83     size_t	todo = len;
84     HANDLE	h = (HANDLE)fd;
85     DWORD	nwrite, size, done = 0;
86     OVERLAPPED	ov;
87 
88     while (todo > 0)
89     {
90 	if (todo > MAX_NAMED_PIPE_SIZE)
91 	    size = MAX_NAMED_PIPE_SIZE;
92 	else
93 	    size = (DWORD)todo;
94 	// If the pipe overflows while the job does not read the data, WriteFile
95 	// will block forever. This abandons the write.
96 	memset(&ov, 0, sizeof(ov));
97 	if (!WriteFile(h, buf + done, size, &nwrite, &ov))
98 	{
99 	    DWORD err = GetLastError();
100 
101 	    if (err != ERROR_IO_PENDING)
102 		return -1;
103 	    if (!GetOverlappedResult(h, &ov, &nwrite, FALSE))
104 		return -1;
105 	    FlushFileBuffers(h);
106 	}
107 	todo -= nwrite;
108 	done += nwrite;
109     }
110     return (int)done;
111 }
112 
113     static void
114 fd_close(sock_T fd)
115 {
116     HANDLE h = (HANDLE)fd;
117 
118     CloseHandle(h);
119 }
120 #endif
121 
122 /* Log file opened with ch_logfile(). */
123 static FILE *log_fd = NULL;
124 #ifdef FEAT_RELTIME
125 static proftime_T log_start;
126 #endif
127 
128     void
129 ch_logfile(char_u *fname, char_u *opt)
130 {
131     FILE   *file = NULL;
132 
133     if (log_fd != NULL)
134 	fclose(log_fd);
135 
136     if (*fname != NUL)
137     {
138 	file = fopen((char *)fname, *opt == 'w' ? "w" : "a");
139 	if (file == NULL)
140 	{
141 	    semsg(_(e_notopen), fname);
142 	    return;
143 	}
144     }
145     log_fd = file;
146 
147     if (log_fd != NULL)
148     {
149 	fprintf(log_fd, "==== start log session ====\n");
150 #ifdef FEAT_RELTIME
151 	profile_start(&log_start);
152 #endif
153     }
154 }
155 
156     int
157 ch_log_active(void)
158 {
159     return log_fd != NULL;
160 }
161 
162     static void
163 ch_log_lead(const char *what, channel_T *ch, ch_part_T part)
164 {
165     if (log_fd != NULL)
166     {
167 #ifdef FEAT_RELTIME
168 	proftime_T log_now;
169 
170 	profile_start(&log_now);
171 	profile_sub(&log_now, &log_start);
172 	fprintf(log_fd, "%s ", profile_msg(&log_now));
173 #endif
174 	if (ch != NULL)
175 	{
176 	    if (part < PART_COUNT)
177 		fprintf(log_fd, "%son %d(%s): ",
178 					   what, ch->ch_id, part_names[part]);
179 	    else
180 		fprintf(log_fd, "%son %d: ", what, ch->ch_id);
181 	}
182 	else
183 	    fprintf(log_fd, "%s: ", what);
184     }
185 }
186 
187 static int did_log_msg = TRUE;
188 
189 #ifndef PROTO  /* prototype is in vim.h */
190     void
191 ch_log(channel_T *ch, const char *fmt, ...)
192 {
193     if (log_fd != NULL)
194     {
195 	va_list ap;
196 
197 	ch_log_lead("", ch, PART_COUNT);
198 	va_start(ap, fmt);
199 	vfprintf(log_fd, fmt, ap);
200 	va_end(ap);
201 	fputc('\n', log_fd);
202 	fflush(log_fd);
203 	did_log_msg = TRUE;
204     }
205 }
206 #endif
207 
208     static void
209 ch_error(channel_T *ch, const char *fmt, ...)
210 #ifdef USE_PRINTF_FORMAT_ATTRIBUTE
211     __attribute__((format(printf, 2, 3)))
212 #endif
213     ;
214 
215     static void
216 ch_error(channel_T *ch, const char *fmt, ...)
217 {
218     if (log_fd != NULL)
219     {
220 	va_list ap;
221 
222 	ch_log_lead("ERR ", ch, PART_COUNT);
223 	va_start(ap, fmt);
224 	vfprintf(log_fd, fmt, ap);
225 	va_end(ap);
226 	fputc('\n', log_fd);
227 	fflush(log_fd);
228 	did_log_msg = TRUE;
229     }
230 }
231 
232 #ifdef _WIN32
233 # undef PERROR
234 # define PERROR(msg) (void)semsg("%s: %s", msg, strerror_win32(errno))
235 
236     static char *
237 strerror_win32(int eno)
238 {
239     static LPVOID msgbuf = NULL;
240     char_u *ptr;
241 
242     if (msgbuf)
243     {
244 	LocalFree(msgbuf);
245 	msgbuf = NULL;
246     }
247     FormatMessage(
248 	FORMAT_MESSAGE_ALLOCATE_BUFFER |
249 	FORMAT_MESSAGE_FROM_SYSTEM |
250 	FORMAT_MESSAGE_IGNORE_INSERTS,
251 	NULL,
252 	eno,
253 	MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
254 	(LPTSTR) &msgbuf,
255 	0,
256 	NULL);
257     if (msgbuf != NULL)
258 	/* chomp \r or \n */
259 	for (ptr = (char_u *)msgbuf; *ptr; ptr++)
260 	    switch (*ptr)
261 	    {
262 		case '\r':
263 		    STRMOVE(ptr, ptr + 1);
264 		    ptr--;
265 		    break;
266 		case '\n':
267 		    if (*(ptr + 1) == '\0')
268 			*ptr = '\0';
269 		    else
270 			*ptr = ' ';
271 		    break;
272 	    }
273     return msgbuf;
274 }
275 #endif
276 
277 /*
278  * The list of all allocated channels.
279  */
280 static channel_T *first_channel = NULL;
281 static int next_ch_id = 0;
282 
283 /*
284  * Allocate a new channel.  The refcount is set to 1.
285  * The channel isn't actually used until it is opened.
286  * Returns NULL if out of memory.
287  */
288     channel_T *
289 add_channel(void)
290 {
291     ch_part_T	part;
292     channel_T	*channel = (channel_T *)alloc_clear((int)sizeof(channel_T));
293 
294     if (channel == NULL)
295 	return NULL;
296 
297     channel->ch_id = next_ch_id++;
298     ch_log(channel, "Created channel");
299 
300     for (part = PART_SOCK; part < PART_COUNT; ++part)
301     {
302 	channel->ch_part[part].ch_fd = INVALID_FD;
303 #ifdef FEAT_GUI_X11
304 	channel->ch_part[part].ch_inputHandler = (XtInputId)NULL;
305 #endif
306 #ifdef FEAT_GUI_GTK
307 	channel->ch_part[part].ch_inputHandler = 0;
308 #endif
309 	channel->ch_part[part].ch_timeout = 2000;
310     }
311 
312     if (first_channel != NULL)
313     {
314 	first_channel->ch_prev = channel;
315 	channel->ch_next = first_channel;
316     }
317     first_channel = channel;
318 
319     channel->ch_refcount = 1;
320     return channel;
321 }
322 
323     int
324 has_any_channel(void)
325 {
326     return first_channel != NULL;
327 }
328 
329 /*
330  * Called when the refcount of a channel is zero.
331  * Return TRUE if "channel" has a callback and the associated job wasn't
332  * killed.
333  */
334     static int
335 channel_still_useful(channel_T *channel)
336 {
337     int has_sock_msg;
338     int	has_out_msg;
339     int	has_err_msg;
340 
341     /* If the job was killed the channel is not expected to work anymore. */
342     if (channel->ch_job_killed && channel->ch_job == NULL)
343 	return FALSE;
344 
345     /* If there is a close callback it may still need to be invoked. */
346     if (channel->ch_close_cb != NULL)
347 	return TRUE;
348 
349     /* If reading from or a buffer it's still useful. */
350     if (channel->ch_part[PART_IN].ch_bufref.br_buf != NULL)
351 	return TRUE;
352 
353     /* If there is no callback then nobody can get readahead.  If the fd is
354      * closed and there is no readahead then the callback won't be called. */
355     has_sock_msg = channel->ch_part[PART_SOCK].ch_fd != INVALID_FD
356 		|| channel->ch_part[PART_SOCK].ch_head.rq_next != NULL
357 		|| channel->ch_part[PART_SOCK].ch_json_head.jq_next != NULL;
358     has_out_msg = channel->ch_part[PART_OUT].ch_fd != INVALID_FD
359 		  || channel->ch_part[PART_OUT].ch_head.rq_next != NULL
360 		  || channel->ch_part[PART_OUT].ch_json_head.jq_next != NULL;
361     has_err_msg = channel->ch_part[PART_ERR].ch_fd != INVALID_FD
362 		  || channel->ch_part[PART_ERR].ch_head.rq_next != NULL
363 		  || channel->ch_part[PART_ERR].ch_json_head.jq_next != NULL;
364     return (channel->ch_callback != NULL && (has_sock_msg
365 		|| has_out_msg || has_err_msg))
366 	    || ((channel->ch_part[PART_OUT].ch_callback != NULL
367 		       || channel->ch_part[PART_OUT].ch_bufref.br_buf != NULL)
368 		    && has_out_msg)
369 	    || ((channel->ch_part[PART_ERR].ch_callback != NULL
370 		       || channel->ch_part[PART_ERR].ch_bufref.br_buf != NULL)
371 		    && has_err_msg);
372 }
373 
374 /*
375  * Return TRUE if "channel" is closeable (i.e. all readable fds are closed).
376  */
377     static int
378 channel_can_close(channel_T *channel)
379 {
380     return channel->ch_to_be_closed == 0;
381 }
382 
383 /*
384  * Close a channel and free all its resources.
385  */
386     static void
387 channel_free_contents(channel_T *channel)
388 {
389     channel_close(channel, TRUE);
390     channel_clear(channel);
391     ch_log(channel, "Freeing channel");
392 }
393 
394     static void
395 channel_free_channel(channel_T *channel)
396 {
397     if (channel->ch_next != NULL)
398 	channel->ch_next->ch_prev = channel->ch_prev;
399     if (channel->ch_prev == NULL)
400 	first_channel = channel->ch_next;
401     else
402 	channel->ch_prev->ch_next = channel->ch_next;
403     vim_free(channel);
404 }
405 
406     static void
407 channel_free(channel_T *channel)
408 {
409     if (!in_free_unref_items)
410     {
411 	if (safe_to_invoke_callback == 0)
412 	    channel->ch_to_be_freed = TRUE;
413 	else
414 	{
415 	    channel_free_contents(channel);
416 	    channel_free_channel(channel);
417 	}
418     }
419 }
420 
421 /*
422  * Close a channel and free all its resources if there is no further action
423  * possible, there is no callback to be invoked or the associated job was
424  * killed.
425  * Return TRUE if the channel was freed.
426  */
427     static int
428 channel_may_free(channel_T *channel)
429 {
430     if (!channel_still_useful(channel))
431     {
432 	channel_free(channel);
433 	return TRUE;
434     }
435     return FALSE;
436 }
437 
438 /*
439  * Decrement the reference count on "channel" and maybe free it when it goes
440  * down to zero.  Don't free it if there is a pending action.
441  * Returns TRUE when the channel is no longer referenced.
442  */
443     int
444 channel_unref(channel_T *channel)
445 {
446     if (channel != NULL && --channel->ch_refcount <= 0)
447 	return channel_may_free(channel);
448     return FALSE;
449 }
450 
451     int
452 free_unused_channels_contents(int copyID, int mask)
453 {
454     int		did_free = FALSE;
455     channel_T	*ch;
456 
457     /* This is invoked from the garbage collector, which only runs at a safe
458      * point. */
459     ++safe_to_invoke_callback;
460 
461     for (ch = first_channel; ch != NULL; ch = ch->ch_next)
462 	if (!channel_still_useful(ch)
463 				 && (ch->ch_copyID & mask) != (copyID & mask))
464 	{
465 	    /* Free the channel and ordinary items it contains, but don't
466 	     * recurse into Lists, Dictionaries etc. */
467 	    channel_free_contents(ch);
468 	    did_free = TRUE;
469 	}
470 
471     --safe_to_invoke_callback;
472     return did_free;
473 }
474 
475     void
476 free_unused_channels(int copyID, int mask)
477 {
478     channel_T	*ch;
479     channel_T	*ch_next;
480 
481     for (ch = first_channel; ch != NULL; ch = ch_next)
482     {
483 	ch_next = ch->ch_next;
484 	if (!channel_still_useful(ch)
485 				 && (ch->ch_copyID & mask) != (copyID & mask))
486 	{
487 	    /* Free the channel struct itself. */
488 	    channel_free_channel(ch);
489 	}
490     }
491 }
492 
493 #if defined(FEAT_GUI) || defined(PROTO)
494 
495 #if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
496     static void
497 channel_read_fd(int fd)
498 {
499     channel_T	*channel;
500     ch_part_T	part;
501 
502     channel = channel_fd2channel(fd, &part);
503     if (channel == NULL)
504 	ch_error(NULL, "Channel for fd %d not found", fd);
505     else
506 	channel_read(channel, part, "channel_read_fd");
507 }
508 #endif
509 
510 /*
511  * Read a command from netbeans.
512  */
513 #ifdef FEAT_GUI_X11
514     static void
515 messageFromServerX11(XtPointer clientData,
516 		  int *unused1 UNUSED,
517 		  XtInputId *unused2 UNUSED)
518 {
519     channel_read_fd((int)(long)clientData);
520 }
521 #endif
522 
523 #ifdef FEAT_GUI_GTK
524 # if GTK_CHECK_VERSION(3,0,0)
525     static gboolean
526 messageFromServerGtk3(GIOChannel *unused1 UNUSED,
527 		  GIOCondition unused2 UNUSED,
528 		  gpointer clientData)
529 {
530     channel_read_fd(GPOINTER_TO_INT(clientData));
531     return TRUE; /* Return FALSE instead in case the event source is to
532 		  * be removed after this function returns. */
533 }
534 # else
535     static void
536 messageFromServerGtk2(gpointer clientData,
537 		  gint unused1 UNUSED,
538 		  GdkInputCondition unused2 UNUSED)
539 {
540     channel_read_fd((int)(long)clientData);
541 }
542 # endif
543 #endif
544 
545     static void
546 channel_gui_register_one(channel_T *channel, ch_part_T part)
547 {
548     if (!CH_HAS_GUI)
549 	return;
550 
551     /* gets stuck in handling events for a not connected channel */
552     if (channel->ch_keep_open)
553 	return;
554 
555 # ifdef FEAT_GUI_X11
556     /* Tell notifier we are interested in being called when there is input on
557      * the editor connection socket. */
558     if (channel->ch_part[part].ch_inputHandler == (XtInputId)NULL)
559     {
560 	ch_log(channel, "Registering part %s with fd %d",
561 		part_names[part], channel->ch_part[part].ch_fd);
562 
563 	channel->ch_part[part].ch_inputHandler = XtAppAddInput(
564 		(XtAppContext)app_context,
565 		channel->ch_part[part].ch_fd,
566 		(XtPointer)(XtInputReadMask + XtInputExceptMask),
567 		messageFromServerX11,
568 		(XtPointer)(long)channel->ch_part[part].ch_fd);
569     }
570 # else
571 #  ifdef FEAT_GUI_GTK
572     /* Tell gdk we are interested in being called when there is input on the
573      * editor connection socket. */
574     if (channel->ch_part[part].ch_inputHandler == 0)
575     {
576 	ch_log(channel, "Registering part %s with fd %d",
577 		part_names[part], channel->ch_part[part].ch_fd);
578 #   if GTK_CHECK_VERSION(3,0,0)
579 	GIOChannel *chnnl = g_io_channel_unix_new(
580 		(gint)channel->ch_part[part].ch_fd);
581 
582 	channel->ch_part[part].ch_inputHandler = g_io_add_watch(
583 		chnnl,
584 		G_IO_IN|G_IO_HUP|G_IO_ERR|G_IO_PRI,
585 		messageFromServerGtk3,
586 		GINT_TO_POINTER(channel->ch_part[part].ch_fd));
587 
588 	g_io_channel_unref(chnnl);
589 #   else
590 	channel->ch_part[part].ch_inputHandler = gdk_input_add(
591 		(gint)channel->ch_part[part].ch_fd,
592 		(GdkInputCondition)
593 			     ((int)GDK_INPUT_READ + (int)GDK_INPUT_EXCEPTION),
594 		messageFromServerGtk2,
595 		(gpointer)(long)channel->ch_part[part].ch_fd);
596 #   endif
597     }
598 #  endif
599 # endif
600 }
601 
602     static void
603 channel_gui_register(channel_T *channel)
604 {
605     if (channel->CH_SOCK_FD != INVALID_FD)
606 	channel_gui_register_one(channel, PART_SOCK);
607     if (channel->CH_OUT_FD != INVALID_FD
608 	    && channel->CH_OUT_FD != channel->CH_SOCK_FD)
609 	channel_gui_register_one(channel, PART_OUT);
610     if (channel->CH_ERR_FD != INVALID_FD
611 	    && channel->CH_ERR_FD != channel->CH_SOCK_FD
612 	    && channel->CH_ERR_FD != channel->CH_OUT_FD)
613 	channel_gui_register_one(channel, PART_ERR);
614 }
615 
616 /*
617  * Register any of our file descriptors with the GUI event handling system.
618  * Called when the GUI has started.
619  */
620     void
621 channel_gui_register_all(void)
622 {
623     channel_T *channel;
624 
625     for (channel = first_channel; channel != NULL; channel = channel->ch_next)
626 	channel_gui_register(channel);
627 }
628 
629     static void
630 channel_gui_unregister_one(channel_T *channel, ch_part_T part)
631 {
632 # ifdef FEAT_GUI_X11
633     if (channel->ch_part[part].ch_inputHandler != (XtInputId)NULL)
634     {
635 	ch_log(channel, "Unregistering part %s", part_names[part]);
636 	XtRemoveInput(channel->ch_part[part].ch_inputHandler);
637 	channel->ch_part[part].ch_inputHandler = (XtInputId)NULL;
638     }
639 # else
640 #  ifdef FEAT_GUI_GTK
641     if (channel->ch_part[part].ch_inputHandler != 0)
642     {
643 	ch_log(channel, "Unregistering part %s", part_names[part]);
644 #   if GTK_CHECK_VERSION(3,0,0)
645 	g_source_remove(channel->ch_part[part].ch_inputHandler);
646 #   else
647 	gdk_input_remove(channel->ch_part[part].ch_inputHandler);
648 #   endif
649 	channel->ch_part[part].ch_inputHandler = 0;
650     }
651 #  endif
652 # endif
653 }
654 
655     static void
656 channel_gui_unregister(channel_T *channel)
657 {
658     ch_part_T	part;
659 
660     for (part = PART_SOCK; part < PART_IN; ++part)
661 	channel_gui_unregister_one(channel, part);
662 }
663 
664 #endif
665 
666 static char *e_cannot_connect = N_("E902: Cannot connect to port");
667 
668 /*
669  * Open a socket channel to "hostname":"port".
670  * "waittime" is the time in msec to wait for the connection.
671  * When negative wait forever.
672  * Returns the channel for success.
673  * Returns NULL for failure.
674  */
675     channel_T *
676 channel_open(
677 	char *hostname,
678 	int port_in,
679 	int waittime,
680 	void (*nb_close_cb)(void))
681 {
682     int			sd = -1;
683     struct sockaddr_in	server;
684     struct hostent	*host;
685 #ifdef WIN32
686     u_short		port = port_in;
687     u_long		val = 1;
688 #else
689     int			port = port_in;
690 #endif
691     channel_T		*channel;
692     int			ret;
693 
694 #ifdef WIN32
695     channel_init_winsock();
696 #endif
697 
698     channel = add_channel();
699     if (channel == NULL)
700     {
701 	ch_error(NULL, "Cannot allocate channel.");
702 	return NULL;
703     }
704 
705     /* Get the server internet address and put into addr structure */
706     /* fill in the socket address structure and connect to server */
707     vim_memset((char *)&server, 0, sizeof(server));
708     server.sin_family = AF_INET;
709     server.sin_port = htons(port);
710     if ((host = gethostbyname(hostname)) == NULL)
711     {
712 	ch_error(channel, "in gethostbyname() in channel_open()");
713 	PERROR(_("E901: gethostbyname() in channel_open()"));
714 	channel_free(channel);
715 	return NULL;
716     }
717     {
718 	char		*p;
719 
720 	/* When using host->h_addr_list[0] directly ubsan warns for it to not
721 	 * be aligned.  First copy the pointer to avoid that. */
722 	memcpy(&p, &host->h_addr_list[0], sizeof(p));
723 	memcpy((char *)&server.sin_addr, p, host->h_length);
724     }
725 
726     /* On Mac and Solaris a zero timeout almost never works.  At least wait
727      * one millisecond. Let's do it for all systems, because we don't know why
728      * this is needed. */
729     if (waittime == 0)
730 	waittime = 1;
731 
732     /*
733      * For Unix we need to call connect() again after connect() failed.
734      * On Win32 one time is sufficient.
735      */
736     while (TRUE)
737     {
738 	long	elapsed_msec = 0;
739 	int	waitnow;
740 
741 	if (sd >= 0)
742 	    sock_close(sd);
743 	sd = socket(AF_INET, SOCK_STREAM, 0);
744 	if (sd == -1)
745 	{
746 	    ch_error(channel, "in socket() in channel_open().");
747 	    PERROR(_("E898: socket() in channel_open()"));
748 	    channel_free(channel);
749 	    return NULL;
750 	}
751 
752 	if (waittime >= 0)
753 	{
754 	    /* Make connect() non-blocking. */
755 	    if (
756 #ifdef _WIN32
757 		ioctlsocket(sd, FIONBIO, &val) < 0
758 #else
759 		fcntl(sd, F_SETFL, O_NONBLOCK) < 0
760 #endif
761 	       )
762 	    {
763 		SOCK_ERRNO;
764 		ch_error(channel,
765 			 "channel_open: Connect failed with errno %d", errno);
766 		sock_close(sd);
767 		channel_free(channel);
768 		return NULL;
769 	    }
770 	}
771 
772 	/* Try connecting to the server. */
773 	ch_log(channel, "Connecting to %s port %d", hostname, port);
774 	ret = connect(sd, (struct sockaddr *)&server, sizeof(server));
775 
776 	if (ret == 0)
777 	    /* The connection could be established. */
778 	    break;
779 
780 	SOCK_ERRNO;
781 	if (waittime < 0 || (errno != EWOULDBLOCK
782 		&& errno != ECONNREFUSED
783 #ifdef EINPROGRESS
784 		&& errno != EINPROGRESS
785 #endif
786 		))
787 	{
788 	    ch_error(channel,
789 			 "channel_open: Connect failed with errno %d", errno);
790 	    PERROR(_(e_cannot_connect));
791 	    sock_close(sd);
792 	    channel_free(channel);
793 	    return NULL;
794 	}
795 
796 	/* Limit the waittime to 50 msec.  If it doesn't work within this
797 	 * time we close the socket and try creating it again. */
798 	waitnow = waittime > 50 ? 50 : waittime;
799 
800 	/* If connect() didn't finish then try using select() to wait for the
801 	 * connection to be made. For Win32 always use select() to wait. */
802 #ifndef WIN32
803 	if (errno != ECONNREFUSED)
804 #endif
805 	{
806 	    struct timeval	tv;
807 	    fd_set		rfds;
808 	    fd_set		wfds;
809 #ifndef WIN32
810 	    int			so_error = 0;
811 	    socklen_t		so_error_len = sizeof(so_error);
812 	    struct timeval	start_tv;
813 	    struct timeval	end_tv;
814 #endif
815 	    FD_ZERO(&rfds);
816 	    FD_SET(sd, &rfds);
817 	    FD_ZERO(&wfds);
818 	    FD_SET(sd, &wfds);
819 
820 	    tv.tv_sec = waitnow / 1000;
821 	    tv.tv_usec = (waitnow % 1000) * 1000;
822 #ifndef WIN32
823 	    gettimeofday(&start_tv, NULL);
824 #endif
825 	    ch_log(channel,
826 		    "Waiting for connection (waiting %d msec)...", waitnow);
827 	    ret = select((int)sd + 1, &rfds, &wfds, NULL, &tv);
828 
829 	    if (ret < 0)
830 	    {
831 		SOCK_ERRNO;
832 		ch_error(channel,
833 			"channel_open: Connect failed with errno %d", errno);
834 		PERROR(_(e_cannot_connect));
835 		sock_close(sd);
836 		channel_free(channel);
837 		return NULL;
838 	    }
839 
840 #ifdef WIN32
841 	    /* On Win32: select() is expected to work and wait for up to
842 	     * "waitnow" msec for the socket to be open. */
843 	    if (FD_ISSET(sd, &wfds))
844 		break;
845 	    elapsed_msec = waitnow;
846 	    if (waittime > 1 && elapsed_msec < waittime)
847 	    {
848 		waittime -= elapsed_msec;
849 		continue;
850 	    }
851 #else
852 	    /* On Linux-like systems: See socket(7) for the behavior
853 	     * After putting the socket in non-blocking mode, connect() will
854 	     * return EINPROGRESS, select() will not wait (as if writing is
855 	     * possible), need to use getsockopt() to check if the socket is
856 	     * actually able to connect.
857 	     * We detect a failure to connect when either read and write fds
858 	     * are set.  Use getsockopt() to find out what kind of failure. */
859 	    if (FD_ISSET(sd, &rfds) || FD_ISSET(sd, &wfds))
860 	    {
861 		ret = getsockopt(sd,
862 			      SOL_SOCKET, SO_ERROR, &so_error, &so_error_len);
863 		if (ret < 0 || (so_error != 0
864 			&& so_error != EWOULDBLOCK
865 			&& so_error != ECONNREFUSED
866 # ifdef EINPROGRESS
867 			&& so_error != EINPROGRESS
868 # endif
869 			))
870 		{
871 		    ch_error(channel,
872 			    "channel_open: Connect failed with errno %d",
873 			    so_error);
874 		    PERROR(_(e_cannot_connect));
875 		    sock_close(sd);
876 		    channel_free(channel);
877 		    return NULL;
878 		}
879 	    }
880 
881 	    if (FD_ISSET(sd, &wfds) && so_error == 0)
882 		/* Did not detect an error, connection is established. */
883 		break;
884 
885 	    gettimeofday(&end_tv, NULL);
886 	    elapsed_msec = (end_tv.tv_sec - start_tv.tv_sec) * 1000
887 			     + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
888 #endif
889 	}
890 
891 #ifndef WIN32
892 	if (waittime > 1 && elapsed_msec < waittime)
893 	{
894 	    /* The port isn't ready but we also didn't get an error.
895 	     * This happens when the server didn't open the socket
896 	     * yet.  Select() may return early, wait until the remaining
897 	     * "waitnow"  and try again. */
898 	    waitnow -= elapsed_msec;
899 	    waittime -= elapsed_msec;
900 	    if (waitnow > 0)
901 	    {
902 		mch_delay((long)waitnow, TRUE);
903 		ui_breakcheck();
904 		waittime -= waitnow;
905 	    }
906 	    if (!got_int)
907 	    {
908 		if (waittime <= 0)
909 		    /* give it one more try */
910 		    waittime = 1;
911 		continue;
912 	    }
913 	    /* we were interrupted, behave as if timed out */
914 	}
915 #endif
916 
917 	/* We timed out. */
918 	ch_error(channel, "Connection timed out");
919 	sock_close(sd);
920 	channel_free(channel);
921 	return NULL;
922     }
923 
924     ch_log(channel, "Connection made");
925 
926     if (waittime >= 0)
927     {
928 #ifdef _WIN32
929 	val = 0;
930 	ioctlsocket(sd, FIONBIO, &val);
931 #else
932 	(void)fcntl(sd, F_SETFL, 0);
933 #endif
934     }
935 
936     channel->CH_SOCK_FD = (sock_T)sd;
937     channel->ch_nb_close_cb = nb_close_cb;
938     channel->ch_hostname = (char *)vim_strsave((char_u *)hostname);
939     channel->ch_port = port_in;
940     channel->ch_to_be_closed |= (1U << PART_SOCK);
941 
942 #ifdef FEAT_GUI
943     channel_gui_register_one(channel, PART_SOCK);
944 #endif
945 
946     return channel;
947 }
948 
949 /*
950  * Implements ch_open().
951  */
952     channel_T *
953 channel_open_func(typval_T *argvars)
954 {
955     char_u	*address;
956     char_u	*p;
957     char	*rest;
958     int		port;
959     jobopt_T    opt;
960     channel_T	*channel = NULL;
961 
962     address = tv_get_string(&argvars[0]);
963     if (argvars[1].v_type != VAR_UNKNOWN
964 	 && (argvars[1].v_type != VAR_DICT || argvars[1].vval.v_dict == NULL))
965     {
966 	emsg(_(e_invarg));
967 	return NULL;
968     }
969 
970     /* parse address */
971     p = vim_strchr(address, ':');
972     if (p == NULL)
973     {
974 	semsg(_(e_invarg2), address);
975 	return NULL;
976     }
977     *p++ = NUL;
978     port = strtol((char *)p, &rest, 10);
979     if (*address == NUL || port <= 0 || *rest != NUL)
980     {
981 	p[-1] = ':';
982 	semsg(_(e_invarg2), address);
983 	return NULL;
984     }
985 
986     /* parse options */
987     clear_job_options(&opt);
988     opt.jo_mode = MODE_JSON;
989     opt.jo_timeout = 2000;
990     if (get_job_options(&argvars[1], &opt,
991 	    JO_MODE_ALL + JO_CB_ALL + JO_WAITTIME + JO_TIMEOUT_ALL, 0) == FAIL)
992 	goto theend;
993     if (opt.jo_timeout < 0)
994     {
995 	emsg(_(e_invarg));
996 	goto theend;
997     }
998 
999     channel = channel_open((char *)address, port, opt.jo_waittime, NULL);
1000     if (channel != NULL)
1001     {
1002 	opt.jo_set = JO_ALL;
1003 	channel_set_options(channel, &opt);
1004     }
1005 theend:
1006     free_job_options(&opt);
1007     return channel;
1008 }
1009 
1010     static void
1011 ch_close_part(channel_T *channel, ch_part_T part)
1012 {
1013     sock_T *fd = &channel->ch_part[part].ch_fd;
1014 
1015     if (*fd != INVALID_FD)
1016     {
1017 	if (part == PART_SOCK)
1018 	    sock_close(*fd);
1019 	else
1020 	{
1021 	    /* When using a pty the same FD is set on multiple parts, only
1022 	     * close it when the last reference is closed. */
1023 	    if ((part == PART_IN || channel->CH_IN_FD != *fd)
1024 		    && (part == PART_OUT || channel->CH_OUT_FD != *fd)
1025 		    && (part == PART_ERR || channel->CH_ERR_FD != *fd))
1026 	    {
1027 #ifdef WIN32
1028 		if (channel->ch_named_pipe)
1029 		    DisconnectNamedPipe((HANDLE)fd);
1030 #endif
1031 		fd_close(*fd);
1032 	    }
1033 	}
1034 	*fd = INVALID_FD;
1035 
1036 	/* channel is closed, may want to end the job if it was the last */
1037 	channel->ch_to_be_closed &= ~(1U << part);
1038     }
1039 }
1040 
1041     void
1042 channel_set_pipes(channel_T *channel, sock_T in, sock_T out, sock_T err)
1043 {
1044     if (in != INVALID_FD)
1045     {
1046 	ch_close_part(channel, PART_IN);
1047 	channel->CH_IN_FD = in;
1048 # if defined(UNIX)
1049 	/* Do not end the job when all output channels are closed, wait until
1050 	 * the job ended. */
1051 	if (mch_isatty(in))
1052 	    channel->ch_to_be_closed |= (1U << PART_IN);
1053 # endif
1054     }
1055     if (out != INVALID_FD)
1056     {
1057 # if defined(FEAT_GUI)
1058 	channel_gui_unregister_one(channel, PART_OUT);
1059 # endif
1060 	ch_close_part(channel, PART_OUT);
1061 	channel->CH_OUT_FD = out;
1062 	channel->ch_to_be_closed |= (1U << PART_OUT);
1063 # if defined(FEAT_GUI)
1064 	channel_gui_register_one(channel, PART_OUT);
1065 # endif
1066     }
1067     if (err != INVALID_FD)
1068     {
1069 # if defined(FEAT_GUI)
1070 	channel_gui_unregister_one(channel, PART_ERR);
1071 # endif
1072 	ch_close_part(channel, PART_ERR);
1073 	channel->CH_ERR_FD = err;
1074 	channel->ch_to_be_closed |= (1U << PART_ERR);
1075 # if defined(FEAT_GUI)
1076 	channel_gui_register_one(channel, PART_ERR);
1077 # endif
1078     }
1079 }
1080 
1081 /*
1082  * Sets the job the channel is associated with and associated options.
1083  * This does not keep a refcount, when the job is freed ch_job is cleared.
1084  */
1085     void
1086 channel_set_job(channel_T *channel, job_T *job, jobopt_T *options)
1087 {
1088     channel->ch_job = job;
1089 
1090     channel_set_options(channel, options);
1091 
1092     if (job->jv_in_buf != NULL)
1093     {
1094 	chanpart_T *in_part = &channel->ch_part[PART_IN];
1095 
1096 	set_bufref(&in_part->ch_bufref, job->jv_in_buf);
1097 	ch_log(channel, "reading from buffer '%s'",
1098 				 (char *)in_part->ch_bufref.br_buf->b_ffname);
1099 	if (options->jo_set & JO_IN_TOP)
1100 	{
1101 	    if (options->jo_in_top == 0 && !(options->jo_set & JO_IN_BOT))
1102 	    {
1103 		/* Special mode: send last-but-one line when appending a line
1104 		 * to the buffer. */
1105 		in_part->ch_bufref.br_buf->b_write_to_channel = TRUE;
1106 		in_part->ch_buf_append = TRUE;
1107 		in_part->ch_buf_top =
1108 			    in_part->ch_bufref.br_buf->b_ml.ml_line_count + 1;
1109 	    }
1110 	    else
1111 		in_part->ch_buf_top = options->jo_in_top;
1112 	}
1113 	else
1114 	    in_part->ch_buf_top = 1;
1115 	if (options->jo_set & JO_IN_BOT)
1116 	    in_part->ch_buf_bot = options->jo_in_bot;
1117 	else
1118 	    in_part->ch_buf_bot = in_part->ch_bufref.br_buf->b_ml.ml_line_count;
1119     }
1120 }
1121 
1122 /*
1123  * Prepare buffer "buf" for writing channel output to.
1124  */
1125 	static void
1126 prepare_buffer(buf_T *buf)
1127 {
1128     buf_T *save_curbuf = curbuf;
1129 
1130     buf_copy_options(buf, BCO_ENTER);
1131     curbuf = buf;
1132 #ifdef FEAT_QUICKFIX
1133     set_option_value((char_u *)"bt", 0L, (char_u *)"nofile", OPT_LOCAL);
1134     set_option_value((char_u *)"bh", 0L, (char_u *)"hide", OPT_LOCAL);
1135 #endif
1136     if (curbuf->b_ml.ml_mfp == NULL)
1137 	ml_open(curbuf);
1138     curbuf = save_curbuf;
1139 }
1140 
1141 /*
1142  * Find a buffer matching "name" or create a new one.
1143  * Returns NULL if there is something very wrong (error already reported).
1144  */
1145     static buf_T *
1146 find_buffer(char_u *name, int err, int msg)
1147 {
1148     buf_T *buf = NULL;
1149     buf_T *save_curbuf = curbuf;
1150 
1151     if (name != NULL && *name != NUL)
1152     {
1153 	buf = buflist_findname(name);
1154 	if (buf == NULL)
1155 	    buf = buflist_findname_exp(name);
1156     }
1157     if (buf == NULL)
1158     {
1159 	buf = buflist_new(name == NULL || *name == NUL ? NULL : name,
1160 				     NULL, (linenr_T)0, BLN_LISTED | BLN_NEW);
1161 	if (buf == NULL)
1162 	    return NULL;
1163 	prepare_buffer(buf);
1164 
1165 	curbuf = buf;
1166 	if (msg)
1167 	    ml_replace(1, (char_u *)(err ? "Reading from channel error..."
1168 				   : "Reading from channel output..."), TRUE);
1169 	changed_bytes(1, 0);
1170 	curbuf = save_curbuf;
1171     }
1172 
1173     return buf;
1174 }
1175 
1176     static void
1177 set_callback(
1178 	char_u **cbp,
1179 	partial_T **pp,
1180 	char_u *callback,
1181 	partial_T *partial)
1182 {
1183     free_callback(*cbp, *pp);
1184     if (callback != NULL && *callback != NUL)
1185     {
1186 	if (partial != NULL)
1187 	    *cbp = partial_name(partial);
1188 	else
1189 	{
1190 	    *cbp = vim_strsave(callback);
1191 	    func_ref(*cbp);
1192 	}
1193     }
1194     else
1195 	*cbp = NULL;
1196     *pp = partial;
1197     if (partial != NULL)
1198 	++partial->pt_refcount;
1199 }
1200 
1201 /*
1202  * Set various properties from an "opt" argument.
1203  */
1204     void
1205 channel_set_options(channel_T *channel, jobopt_T *opt)
1206 {
1207     ch_part_T	part;
1208 
1209     if (opt->jo_set & JO_MODE)
1210 	for (part = PART_SOCK; part < PART_COUNT; ++part)
1211 	    channel->ch_part[part].ch_mode = opt->jo_mode;
1212     if (opt->jo_set & JO_IN_MODE)
1213 	channel->ch_part[PART_IN].ch_mode = opt->jo_in_mode;
1214     if (opt->jo_set & JO_OUT_MODE)
1215 	channel->ch_part[PART_OUT].ch_mode = opt->jo_out_mode;
1216     if (opt->jo_set & JO_ERR_MODE)
1217 	channel->ch_part[PART_ERR].ch_mode = opt->jo_err_mode;
1218     channel->ch_nonblock = opt->jo_noblock;
1219 
1220     if (opt->jo_set & JO_TIMEOUT)
1221 	for (part = PART_SOCK; part < PART_COUNT; ++part)
1222 	    channel->ch_part[part].ch_timeout = opt->jo_timeout;
1223     if (opt->jo_set & JO_OUT_TIMEOUT)
1224 	channel->ch_part[PART_OUT].ch_timeout = opt->jo_out_timeout;
1225     if (opt->jo_set & JO_ERR_TIMEOUT)
1226 	channel->ch_part[PART_ERR].ch_timeout = opt->jo_err_timeout;
1227     if (opt->jo_set & JO_BLOCK_WRITE)
1228 	channel->ch_part[PART_IN].ch_block_write = 1;
1229 
1230     if (opt->jo_set & JO_CALLBACK)
1231 	set_callback(&channel->ch_callback, &channel->ch_partial,
1232 					   opt->jo_callback, opt->jo_partial);
1233     if (opt->jo_set & JO_OUT_CALLBACK)
1234 	set_callback(&channel->ch_part[PART_OUT].ch_callback,
1235 		&channel->ch_part[PART_OUT].ch_partial,
1236 		opt->jo_out_cb, opt->jo_out_partial);
1237     if (opt->jo_set & JO_ERR_CALLBACK)
1238 	set_callback(&channel->ch_part[PART_ERR].ch_callback,
1239 		&channel->ch_part[PART_ERR].ch_partial,
1240 		opt->jo_err_cb, opt->jo_err_partial);
1241     if (opt->jo_set & JO_CLOSE_CALLBACK)
1242 	set_callback(&channel->ch_close_cb, &channel->ch_close_partial,
1243 		opt->jo_close_cb, opt->jo_close_partial);
1244     channel->ch_drop_never = opt->jo_drop_never;
1245 
1246     if ((opt->jo_set & JO_OUT_IO) && opt->jo_io[PART_OUT] == JIO_BUFFER)
1247     {
1248 	buf_T *buf;
1249 
1250 	/* writing output to a buffer. Default mode is NL. */
1251 	if (!(opt->jo_set & JO_OUT_MODE))
1252 	    channel->ch_part[PART_OUT].ch_mode = MODE_NL;
1253 	if (opt->jo_set & JO_OUT_BUF)
1254 	{
1255 	    buf = buflist_findnr(opt->jo_io_buf[PART_OUT]);
1256 	    if (buf == NULL)
1257 		semsg(_(e_nobufnr), (long)opt->jo_io_buf[PART_OUT]);
1258 	}
1259 	else
1260 	{
1261 	    int msg = TRUE;
1262 
1263 	    if (opt->jo_set2 & JO2_OUT_MSG)
1264 		msg = opt->jo_message[PART_OUT];
1265 	    buf = find_buffer(opt->jo_io_name[PART_OUT], FALSE, msg);
1266 	}
1267 	if (buf != NULL)
1268 	{
1269 	    if (opt->jo_set & JO_OUT_MODIFIABLE)
1270 		channel->ch_part[PART_OUT].ch_nomodifiable =
1271 						!opt->jo_modifiable[PART_OUT];
1272 
1273 	    if (!buf->b_p_ma && !channel->ch_part[PART_OUT].ch_nomodifiable)
1274 	    {
1275 		emsg(_(e_modifiable));
1276 	    }
1277 	    else
1278 	    {
1279 		ch_log(channel, "writing out to buffer '%s'",
1280 						       (char *)buf->b_ffname);
1281 		set_bufref(&channel->ch_part[PART_OUT].ch_bufref, buf);
1282 		// if the buffer was deleted or unloaded resurrect it
1283 		if (buf->b_ml.ml_mfp == NULL)
1284 		    prepare_buffer(buf);
1285 	    }
1286 	}
1287     }
1288 
1289     if ((opt->jo_set & JO_ERR_IO) && (opt->jo_io[PART_ERR] == JIO_BUFFER
1290 	 || (opt->jo_io[PART_ERR] == JIO_OUT && (opt->jo_set & JO_OUT_IO)
1291 				       && opt->jo_io[PART_OUT] == JIO_BUFFER)))
1292     {
1293 	buf_T *buf;
1294 
1295 	/* writing err to a buffer. Default mode is NL. */
1296 	if (!(opt->jo_set & JO_ERR_MODE))
1297 	    channel->ch_part[PART_ERR].ch_mode = MODE_NL;
1298 	if (opt->jo_io[PART_ERR] == JIO_OUT)
1299 	    buf = channel->ch_part[PART_OUT].ch_bufref.br_buf;
1300 	else if (opt->jo_set & JO_ERR_BUF)
1301 	{
1302 	    buf = buflist_findnr(opt->jo_io_buf[PART_ERR]);
1303 	    if (buf == NULL)
1304 		semsg(_(e_nobufnr), (long)opt->jo_io_buf[PART_ERR]);
1305 	}
1306 	else
1307 	{
1308 	    int msg = TRUE;
1309 
1310 	    if (opt->jo_set2 & JO2_ERR_MSG)
1311 		msg = opt->jo_message[PART_ERR];
1312 	    buf = find_buffer(opt->jo_io_name[PART_ERR], TRUE, msg);
1313 	}
1314 	if (buf != NULL)
1315 	{
1316 	    if (opt->jo_set & JO_ERR_MODIFIABLE)
1317 		channel->ch_part[PART_ERR].ch_nomodifiable =
1318 						!opt->jo_modifiable[PART_ERR];
1319 	    if (!buf->b_p_ma && !channel->ch_part[PART_ERR].ch_nomodifiable)
1320 	    {
1321 		emsg(_(e_modifiable));
1322 	    }
1323 	    else
1324 	    {
1325 		ch_log(channel, "writing err to buffer '%s'",
1326 						       (char *)buf->b_ffname);
1327 		set_bufref(&channel->ch_part[PART_ERR].ch_bufref, buf);
1328 		// if the buffer was deleted or unloaded resurrect it
1329 		if (buf->b_ml.ml_mfp == NULL)
1330 		    prepare_buffer(buf);
1331 	    }
1332 	}
1333     }
1334 
1335     channel->ch_part[PART_OUT].ch_io = opt->jo_io[PART_OUT];
1336     channel->ch_part[PART_ERR].ch_io = opt->jo_io[PART_ERR];
1337     channel->ch_part[PART_IN].ch_io = opt->jo_io[PART_IN];
1338 }
1339 
1340 /*
1341  * Set the callback for "channel"/"part" for the response with "id".
1342  */
1343     void
1344 channel_set_req_callback(
1345 	channel_T   *channel,
1346 	ch_part_T   part,
1347 	char_u	    *callback,
1348 	partial_T   *partial,
1349 	int	    id)
1350 {
1351     cbq_T *head = &channel->ch_part[part].ch_cb_head;
1352     cbq_T *item = (cbq_T *)alloc((int)sizeof(cbq_T));
1353 
1354     if (item != NULL)
1355     {
1356 	item->cq_partial = partial;
1357 	if (partial != NULL)
1358 	{
1359 	    ++partial->pt_refcount;
1360 	    item->cq_callback = callback;
1361 	}
1362 	else
1363 	{
1364 	    item->cq_callback = vim_strsave(callback);
1365 	    func_ref(item->cq_callback);
1366 	}
1367 	item->cq_seq_nr = id;
1368 	item->cq_prev = head->cq_prev;
1369 	head->cq_prev = item;
1370 	item->cq_next = NULL;
1371 	if (item->cq_prev == NULL)
1372 	    head->cq_next = item;
1373 	else
1374 	    item->cq_prev->cq_next = item;
1375     }
1376 }
1377 
1378     static void
1379 write_buf_line(buf_T *buf, linenr_T lnum, channel_T *channel)
1380 {
1381     char_u  *line = ml_get_buf(buf, lnum, FALSE);
1382     int	    len = (int)STRLEN(line);
1383     char_u  *p;
1384     int	    i;
1385 
1386     /* Need to make a copy to be able to append a NL. */
1387     if ((p = alloc(len + 2)) == NULL)
1388 	return;
1389     memcpy((char *)p, (char *)line, len);
1390 
1391     if (channel->ch_write_text_mode)
1392 	p[len] = CAR;
1393     else
1394     {
1395 	for (i = 0; i < len; ++i)
1396 	    if (p[i] == NL)
1397 		p[i] = NUL;
1398 
1399 	p[len] = NL;
1400     }
1401     p[len + 1] = NUL;
1402     channel_send(channel, PART_IN, p, len + 1, "write_buf_line");
1403     vim_free(p);
1404 }
1405 
1406 /*
1407  * Return TRUE if "channel" can be written to.
1408  * Returns FALSE if the input is closed or the write would block.
1409  */
1410     static int
1411 can_write_buf_line(channel_T *channel)
1412 {
1413     chanpart_T *in_part = &channel->ch_part[PART_IN];
1414 
1415     if (in_part->ch_fd == INVALID_FD)
1416 	return FALSE;  /* pipe was closed */
1417 
1418     /* for testing: block every other attempt to write */
1419     if (in_part->ch_block_write == 1)
1420 	in_part->ch_block_write = -1;
1421     else if (in_part->ch_block_write == -1)
1422 	in_part->ch_block_write = 1;
1423 
1424     /* TODO: Win32 implementation, probably using WaitForMultipleObjects() */
1425 #ifndef WIN32
1426     {
1427 # if defined(HAVE_SELECT)
1428 	struct timeval	tval;
1429 	fd_set		wfds;
1430 	int		ret;
1431 
1432 	FD_ZERO(&wfds);
1433 	FD_SET((int)in_part->ch_fd, &wfds);
1434 	tval.tv_sec = 0;
1435 	tval.tv_usec = 0;
1436 	for (;;)
1437 	{
1438 	    ret = select((int)in_part->ch_fd + 1, NULL, &wfds, NULL, &tval);
1439 #  ifdef EINTR
1440 	    SOCK_ERRNO;
1441 	    if (ret == -1 && errno == EINTR)
1442 		continue;
1443 #  endif
1444 	    if (ret <= 0 || in_part->ch_block_write == 1)
1445 	    {
1446 		if (ret > 0)
1447 		    ch_log(channel, "FAKED Input not ready for writing");
1448 		else
1449 		    ch_log(channel, "Input not ready for writing");
1450 		return FALSE;
1451 	    }
1452 	    break;
1453 	}
1454 # else
1455 	struct pollfd	fds;
1456 
1457 	fds.fd = in_part->ch_fd;
1458 	fds.events = POLLOUT;
1459 	if (poll(&fds, 1, 0) <= 0)
1460 	{
1461 	    ch_log(channel, "Input not ready for writing");
1462 	    return FALSE;
1463 	}
1464 	if (in_part->ch_block_write == 1)
1465 	{
1466 	    ch_log(channel, "FAKED Input not ready for writing");
1467 	    return FALSE;
1468 	}
1469 # endif
1470     }
1471 #endif
1472     return TRUE;
1473 }
1474 
1475 /*
1476  * Write any buffer lines to the input channel.
1477  */
1478     static void
1479 channel_write_in(channel_T *channel)
1480 {
1481     chanpart_T *in_part = &channel->ch_part[PART_IN];
1482     linenr_T    lnum;
1483     buf_T	*buf = in_part->ch_bufref.br_buf;
1484     int		written = 0;
1485 
1486     if (buf == NULL || in_part->ch_buf_append)
1487 	return;  /* no buffer or using appending */
1488     if (!bufref_valid(&in_part->ch_bufref) || buf->b_ml.ml_mfp == NULL)
1489     {
1490 	/* buffer was wiped out or unloaded */
1491 	ch_log(channel, "input buffer has been wiped out");
1492 	in_part->ch_bufref.br_buf = NULL;
1493 	return;
1494     }
1495 
1496     for (lnum = in_part->ch_buf_top; lnum <= in_part->ch_buf_bot
1497 				   && lnum <= buf->b_ml.ml_line_count; ++lnum)
1498     {
1499 	if (!can_write_buf_line(channel))
1500 	    break;
1501 	write_buf_line(buf, lnum, channel);
1502 	++written;
1503     }
1504 
1505     if (written == 1)
1506 	ch_log(channel, "written line %d to channel", (int)lnum - 1);
1507     else if (written > 1)
1508 	ch_log(channel, "written %d lines to channel", written);
1509 
1510     in_part->ch_buf_top = lnum;
1511     if (lnum > buf->b_ml.ml_line_count || lnum > in_part->ch_buf_bot)
1512     {
1513 #if defined(FEAT_TERMINAL)
1514 	/* Send CTRL-D or "eof_chars" to close stdin on MS-Windows. */
1515 	if (channel->ch_job != NULL)
1516 	    term_send_eof(channel);
1517 #endif
1518 
1519 	/* Writing is done, no longer need the buffer. */
1520 	in_part->ch_bufref.br_buf = NULL;
1521 	ch_log(channel, "Finished writing all lines to channel");
1522 
1523 	/* Close the pipe/socket, so that the other side gets EOF. */
1524 	ch_close_part(channel, PART_IN);
1525     }
1526     else
1527 	ch_log(channel, "Still %ld more lines to write",
1528 				   (long)(buf->b_ml.ml_line_count - lnum + 1));
1529 }
1530 
1531 /*
1532  * Handle buffer "buf" being freed, remove it from any channels.
1533  */
1534     void
1535 channel_buffer_free(buf_T *buf)
1536 {
1537     channel_T	*channel;
1538     ch_part_T	part;
1539 
1540     for (channel = first_channel; channel != NULL; channel = channel->ch_next)
1541 	for (part = PART_SOCK; part < PART_COUNT; ++part)
1542 	{
1543 	    chanpart_T  *ch_part = &channel->ch_part[part];
1544 
1545 	    if (ch_part->ch_bufref.br_buf == buf)
1546 	    {
1547 		ch_log(channel, "%s buffer has been wiped out",
1548 							    part_names[part]);
1549 		ch_part->ch_bufref.br_buf = NULL;
1550 	    }
1551 	}
1552 }
1553 
1554 /*
1555  * Write any lines waiting to be written to "channel".
1556  */
1557     static void
1558 channel_write_input(channel_T *channel)
1559 {
1560     chanpart_T	*in_part = &channel->ch_part[PART_IN];
1561 
1562     if (in_part->ch_writeque.wq_next != NULL)
1563 	channel_send(channel, PART_IN, (char_u *)"", 0, "channel_write_input");
1564     else if (in_part->ch_bufref.br_buf != NULL)
1565     {
1566 	if (in_part->ch_buf_append)
1567 	    channel_write_new_lines(in_part->ch_bufref.br_buf);
1568 	else
1569 	    channel_write_in(channel);
1570     }
1571 }
1572 
1573 /*
1574  * Write any lines waiting to be written to a channel.
1575  */
1576     void
1577 channel_write_any_lines(void)
1578 {
1579     channel_T	*channel;
1580 
1581     for (channel = first_channel; channel != NULL; channel = channel->ch_next)
1582 	channel_write_input(channel);
1583 }
1584 
1585 /*
1586  * Write appended lines above the last one in "buf" to the channel.
1587  */
1588     void
1589 channel_write_new_lines(buf_T *buf)
1590 {
1591     channel_T	*channel;
1592     int		found_one = FALSE;
1593 
1594     /* There could be more than one channel for the buffer, loop over all of
1595      * them. */
1596     for (channel = first_channel; channel != NULL; channel = channel->ch_next)
1597     {
1598 	chanpart_T  *in_part = &channel->ch_part[PART_IN];
1599 	linenr_T    lnum;
1600 	int	    written = 0;
1601 
1602 	if (in_part->ch_bufref.br_buf == buf && in_part->ch_buf_append)
1603 	{
1604 	    if (in_part->ch_fd == INVALID_FD)
1605 		continue;  /* pipe was closed */
1606 	    found_one = TRUE;
1607 	    for (lnum = in_part->ch_buf_bot; lnum < buf->b_ml.ml_line_count;
1608 								       ++lnum)
1609 	    {
1610 		if (!can_write_buf_line(channel))
1611 		    break;
1612 		write_buf_line(buf, lnum, channel);
1613 		++written;
1614 	    }
1615 
1616 	    if (written == 1)
1617 		ch_log(channel, "written line %d to channel", (int)lnum - 1);
1618 	    else if (written > 1)
1619 		ch_log(channel, "written %d lines to channel", written);
1620 	    if (lnum < buf->b_ml.ml_line_count)
1621 		ch_log(channel, "Still %ld more lines to write",
1622 				       (long)(buf->b_ml.ml_line_count - lnum));
1623 
1624 	    in_part->ch_buf_bot = lnum;
1625 	}
1626     }
1627     if (!found_one)
1628 	buf->b_write_to_channel = FALSE;
1629 }
1630 
1631 /*
1632  * Invoke the "callback" on channel "channel".
1633  * This does not redraw but sets channel_need_redraw;
1634  */
1635     static void
1636 invoke_callback(channel_T *channel, char_u *callback, partial_T *partial,
1637 							       typval_T *argv)
1638 {
1639     typval_T	rettv;
1640     int		dummy;
1641 
1642     if (safe_to_invoke_callback == 0)
1643 	iemsg("INTERNAL: Invoking callback when it is not safe");
1644 
1645     argv[0].v_type = VAR_CHANNEL;
1646     argv[0].vval.v_channel = channel;
1647 
1648     call_func(callback, (int)STRLEN(callback), &rettv, 2, argv, NULL,
1649 					  0L, 0L, &dummy, TRUE, partial, NULL);
1650     clear_tv(&rettv);
1651     channel_need_redraw = TRUE;
1652 }
1653 
1654 /*
1655  * Return the first node from "channel"/"part" without removing it.
1656  * Returns NULL if there is nothing.
1657  */
1658     readq_T *
1659 channel_peek(channel_T *channel, ch_part_T part)
1660 {
1661     readq_T *head = &channel->ch_part[part].ch_head;
1662 
1663     return head->rq_next;
1664 }
1665 
1666 /*
1667  * Return a pointer to the first NL in "node".
1668  * Skips over NUL characters.
1669  * Returns NULL if there is no NL.
1670  */
1671     char_u *
1672 channel_first_nl(readq_T *node)
1673 {
1674     char_u  *buffer = node->rq_buffer;
1675     long_u  i;
1676 
1677     for (i = 0; i < node->rq_buflen; ++i)
1678 	if (buffer[i] == NL)
1679 	    return buffer + i;
1680     return NULL;
1681 }
1682 
1683 /*
1684  * Return the first buffer from channel "channel"/"part" and remove it.
1685  * The caller must free it.
1686  * Returns NULL if there is nothing.
1687  */
1688     char_u *
1689 channel_get(channel_T *channel, ch_part_T part, int *outlen)
1690 {
1691     readq_T *head = &channel->ch_part[part].ch_head;
1692     readq_T *node = head->rq_next;
1693     char_u *p;
1694 
1695     if (node == NULL)
1696 	return NULL;
1697     if (outlen != NULL)
1698 	*outlen += node->rq_buflen;
1699     /* dispose of the node but keep the buffer */
1700     p = node->rq_buffer;
1701     head->rq_next = node->rq_next;
1702     if (node->rq_next == NULL)
1703 	head->rq_prev = NULL;
1704     else
1705 	node->rq_next->rq_prev = NULL;
1706     vim_free(node);
1707     return p;
1708 }
1709 
1710 /*
1711  * Returns the whole buffer contents concatenated for "channel"/"part".
1712  * Replaces NUL bytes with NL.
1713  */
1714     static char_u *
1715 channel_get_all(channel_T *channel, ch_part_T part, int *outlen)
1716 {
1717     readq_T *head = &channel->ch_part[part].ch_head;
1718     readq_T *node = head->rq_next;
1719     long_u  len = 0;
1720     char_u  *res;
1721     char_u  *p;
1722 
1723     // Concatenate everything into one buffer.
1724     for (node = head->rq_next; node != NULL; node = node->rq_next)
1725 	len += node->rq_buflen;
1726     res = lalloc(len + 1, TRUE);
1727     if (res == NULL)
1728 	return NULL;
1729     p = res;
1730     for (node = head->rq_next; node != NULL; node = node->rq_next)
1731     {
1732 	mch_memmove(p, node->rq_buffer, node->rq_buflen);
1733 	p += node->rq_buflen;
1734     }
1735     *p = NUL;
1736 
1737     // Free all buffers
1738     do
1739     {
1740 	p = channel_get(channel, part, NULL);
1741 	vim_free(p);
1742     } while (p != NULL);
1743 
1744     if (outlen != NULL)
1745     {
1746 	// Returning the length, keep NUL characters.
1747 	*outlen += len;
1748 	return res;
1749     }
1750 
1751     // Turn all NUL into NL, so that the result can be used as a string.
1752     p = res;
1753     while (p < res + len)
1754     {
1755 	if (*p == NUL)
1756 	    *p = NL;
1757 #ifdef WIN32
1758 	else if (*p == 0x1b)
1759 	{
1760 	    // crush the escape sequence OSC 0/1/2: ESC ]0;
1761 	    if (p + 3 < res + len
1762 		    && p[1] == ']'
1763 		    && (p[2] == '0' || p[2] == '1' || p[2] == '2')
1764 		    && p[3] == ';')
1765 	    {
1766 		// '\a' becomes a NL
1767 	        while (p < res + (len - 1) && *p != '\a')
1768 		    ++p;
1769 		// BEL is zero width characters, suppress display mistake
1770 		// ConPTY (after 10.0.18317) requires advance checking
1771 		if (p[-1] == NUL)
1772 		    p[-1] = 0x07;
1773 	    }
1774 	}
1775 #endif
1776 	++p;
1777     }
1778 
1779     return res;
1780 }
1781 
1782 /*
1783  * Consume "len" bytes from the head of "node".
1784  * Caller must check these bytes are available.
1785  */
1786     void
1787 channel_consume(channel_T *channel, ch_part_T part, int len)
1788 {
1789     readq_T *head = &channel->ch_part[part].ch_head;
1790     readq_T *node = head->rq_next;
1791     char_u *buf = node->rq_buffer;
1792 
1793     mch_memmove(buf, buf + len, node->rq_buflen - len);
1794     node->rq_buflen -= len;
1795 }
1796 
1797 /*
1798  * Collapses the first and second buffer for "channel"/"part".
1799  * Returns FAIL if that is not possible.
1800  * When "want_nl" is TRUE collapse more buffers until a NL is found.
1801  */
1802     int
1803 channel_collapse(channel_T *channel, ch_part_T part, int want_nl)
1804 {
1805     readq_T *head = &channel->ch_part[part].ch_head;
1806     readq_T *node = head->rq_next;
1807     readq_T *last_node;
1808     readq_T *n;
1809     char_u  *newbuf;
1810     char_u  *p;
1811     long_u len;
1812 
1813     if (node == NULL || node->rq_next == NULL)
1814 	return FAIL;
1815 
1816     last_node = node->rq_next;
1817     len = node->rq_buflen + last_node->rq_buflen + 1;
1818     if (want_nl)
1819 	while (last_node->rq_next != NULL
1820 		&& channel_first_nl(last_node) == NULL)
1821 	{
1822 	    last_node = last_node->rq_next;
1823 	    len += last_node->rq_buflen;
1824 	}
1825 
1826     p = newbuf = alloc(len);
1827     if (newbuf == NULL)
1828 	return FAIL;	    /* out of memory */
1829     mch_memmove(p, node->rq_buffer, node->rq_buflen);
1830     p += node->rq_buflen;
1831     vim_free(node->rq_buffer);
1832     node->rq_buffer = newbuf;
1833     for (n = node; n != last_node; )
1834     {
1835 	n = n->rq_next;
1836 	mch_memmove(p, n->rq_buffer, n->rq_buflen);
1837 	p += n->rq_buflen;
1838 	vim_free(n->rq_buffer);
1839     }
1840     node->rq_buflen = (long_u)(p - newbuf);
1841 
1842     /* dispose of the collapsed nodes and their buffers */
1843     for (n = node->rq_next; n != last_node; )
1844     {
1845 	n = n->rq_next;
1846 	vim_free(n->rq_prev);
1847     }
1848     node->rq_next = last_node->rq_next;
1849     if (last_node->rq_next == NULL)
1850 	head->rq_prev = node;
1851     else
1852 	last_node->rq_next->rq_prev = node;
1853     vim_free(last_node);
1854     return OK;
1855 }
1856 
1857 /*
1858  * Store "buf[len]" on "channel"/"part".
1859  * When "prepend" is TRUE put in front, otherwise append at the end.
1860  * Returns OK or FAIL.
1861  */
1862     static int
1863 channel_save(channel_T *channel, ch_part_T part, char_u *buf, int len,
1864 						      int prepend, char *lead)
1865 {
1866     readq_T *node;
1867     readq_T *head = &channel->ch_part[part].ch_head;
1868     char_u  *p;
1869     int	    i;
1870 
1871     node = (readq_T *)alloc(sizeof(readq_T));
1872     if (node == NULL)
1873 	return FAIL;	    /* out of memory */
1874     /* A NUL is added at the end, because netbeans code expects that.
1875      * Otherwise a NUL may appear inside the text. */
1876     node->rq_buffer = alloc(len + 1);
1877     if (node->rq_buffer == NULL)
1878     {
1879 	vim_free(node);
1880 	return FAIL;	    /* out of memory */
1881     }
1882 
1883     if (channel->ch_part[part].ch_mode == MODE_NL)
1884     {
1885 	/* Drop any CR before a NL. */
1886 	p = node->rq_buffer;
1887 	for (i = 0; i < len; ++i)
1888 	    if (buf[i] != CAR || i + 1 >= len || buf[i + 1] != NL)
1889 		*p++ = buf[i];
1890 	*p = NUL;
1891 	node->rq_buflen = (long_u)(p - node->rq_buffer);
1892     }
1893     else
1894     {
1895 	mch_memmove(node->rq_buffer, buf, len);
1896 	node->rq_buffer[len] = NUL;
1897 	node->rq_buflen = (long_u)len;
1898     }
1899 
1900     if (prepend)
1901     {
1902 	/* preend node to the head of the queue */
1903 	node->rq_next = head->rq_next;
1904 	node->rq_prev = NULL;
1905 	if (head->rq_next == NULL)
1906 	    head->rq_prev = node;
1907 	else
1908 	    head->rq_next->rq_prev = node;
1909 	head->rq_next = node;
1910     }
1911     else
1912     {
1913 	/* append node to the tail of the queue */
1914 	node->rq_next = NULL;
1915 	node->rq_prev = head->rq_prev;
1916 	if (head->rq_prev == NULL)
1917 	    head->rq_next = node;
1918 	else
1919 	    head->rq_prev->rq_next = node;
1920 	head->rq_prev = node;
1921     }
1922 
1923     if (ch_log_active() && lead != NULL)
1924     {
1925 	ch_log_lead(lead, channel, part);
1926 	fprintf(log_fd, "'");
1927 	vim_ignored = (int)fwrite(buf, len, 1, log_fd);
1928 	fprintf(log_fd, "'\n");
1929     }
1930     return OK;
1931 }
1932 
1933 /*
1934  * Try to fill the buffer of "reader".
1935  * Returns FALSE when nothing was added.
1936  */
1937     static int
1938 channel_fill(js_read_T *reader)
1939 {
1940     channel_T	*channel = (channel_T *)reader->js_cookie;
1941     ch_part_T	part = reader->js_cookie_arg;
1942     char_u	*next = channel_get(channel, part, NULL);
1943     int		keeplen;
1944     int		addlen;
1945     char_u	*p;
1946 
1947     if (next == NULL)
1948 	return FALSE;
1949 
1950     keeplen = reader->js_end - reader->js_buf;
1951     if (keeplen > 0)
1952     {
1953 	/* Prepend unused text. */
1954 	addlen = (int)STRLEN(next);
1955 	p = alloc(keeplen + addlen + 1);
1956 	if (p == NULL)
1957 	{
1958 	    vim_free(next);
1959 	    return FALSE;
1960 	}
1961 	mch_memmove(p, reader->js_buf, keeplen);
1962 	mch_memmove(p + keeplen, next, addlen + 1);
1963 	vim_free(next);
1964 	next = p;
1965     }
1966 
1967     vim_free(reader->js_buf);
1968     reader->js_buf = next;
1969     return TRUE;
1970 }
1971 
1972 /*
1973  * Use the read buffer of "channel"/"part" and parse a JSON message that is
1974  * complete.  The messages are added to the queue.
1975  * Return TRUE if there is more to read.
1976  */
1977     static int
1978 channel_parse_json(channel_T *channel, ch_part_T part)
1979 {
1980     js_read_T	reader;
1981     typval_T	listtv;
1982     jsonq_T	*item;
1983     chanpart_T	*chanpart = &channel->ch_part[part];
1984     jsonq_T	*head = &chanpart->ch_json_head;
1985     int		status;
1986     int		ret;
1987 
1988     if (channel_peek(channel, part) == NULL)
1989 	return FALSE;
1990 
1991     reader.js_buf = channel_get(channel, part, NULL);
1992     reader.js_used = 0;
1993     reader.js_fill = channel_fill;
1994     reader.js_cookie = channel;
1995     reader.js_cookie_arg = part;
1996 
1997     /* When a message is incomplete we wait for a short while for more to
1998      * arrive.  After the delay drop the input, otherwise a truncated string
1999      * or list will make us hang.
2000      * Do not generate error messages, they will be written in a channel log. */
2001     ++emsg_silent;
2002     status = json_decode(&reader, &listtv,
2003 				  chanpart->ch_mode == MODE_JS ? JSON_JS : 0);
2004     --emsg_silent;
2005     if (status == OK)
2006     {
2007 	/* Only accept the response when it is a list with at least two
2008 	 * items. */
2009 	if (listtv.v_type != VAR_LIST || listtv.vval.v_list->lv_len < 2)
2010 	{
2011 	    if (listtv.v_type != VAR_LIST)
2012 		ch_error(channel, "Did not receive a list, discarding");
2013 	    else
2014 		ch_error(channel, "Expected list with two items, got %d",
2015 						  listtv.vval.v_list->lv_len);
2016 	    clear_tv(&listtv);
2017 	}
2018 	else
2019 	{
2020 	    item = (jsonq_T *)alloc((unsigned)sizeof(jsonq_T));
2021 	    if (item == NULL)
2022 		clear_tv(&listtv);
2023 	    else
2024 	    {
2025 		item->jq_no_callback = FALSE;
2026 		item->jq_value = alloc_tv();
2027 		if (item->jq_value == NULL)
2028 		{
2029 		    vim_free(item);
2030 		    clear_tv(&listtv);
2031 		}
2032 		else
2033 		{
2034 		    *item->jq_value = listtv;
2035 		    item->jq_prev = head->jq_prev;
2036 		    head->jq_prev = item;
2037 		    item->jq_next = NULL;
2038 		    if (item->jq_prev == NULL)
2039 			head->jq_next = item;
2040 		    else
2041 			item->jq_prev->jq_next = item;
2042 		}
2043 	    }
2044 	}
2045     }
2046 
2047     if (status == OK)
2048 	chanpart->ch_wait_len = 0;
2049     else if (status == MAYBE)
2050     {
2051 	size_t buflen = STRLEN(reader.js_buf);
2052 
2053 	if (chanpart->ch_wait_len < buflen)
2054 	{
2055 	    /* First time encountering incomplete message or after receiving
2056 	     * more (but still incomplete): set a deadline of 100 msec. */
2057 	    ch_log(channel,
2058 		    "Incomplete message (%d bytes) - wait 100 msec for more",
2059 		    (int)buflen);
2060 	    reader.js_used = 0;
2061 	    chanpart->ch_wait_len = buflen;
2062 #ifdef WIN32
2063 	    chanpart->ch_deadline = GetTickCount() + 100L;
2064 #else
2065 	    gettimeofday(&chanpart->ch_deadline, NULL);
2066 	    chanpart->ch_deadline.tv_usec += 100 * 1000;
2067 	    if (chanpart->ch_deadline.tv_usec > 1000 * 1000)
2068 	    {
2069 		chanpart->ch_deadline.tv_usec -= 1000 * 1000;
2070 		++chanpart->ch_deadline.tv_sec;
2071 	    }
2072 #endif
2073 	}
2074 	else
2075 	{
2076 	    int timeout;
2077 #ifdef WIN32
2078 	    timeout = GetTickCount() > chanpart->ch_deadline;
2079 #else
2080 	    {
2081 		struct timeval now_tv;
2082 
2083 		gettimeofday(&now_tv, NULL);
2084 		timeout = now_tv.tv_sec > chanpart->ch_deadline.tv_sec
2085 		      || (now_tv.tv_sec == chanpart->ch_deadline.tv_sec
2086 			   && now_tv.tv_usec > chanpart->ch_deadline.tv_usec);
2087 	    }
2088 #endif
2089 	    if (timeout)
2090 	    {
2091 		status = FAIL;
2092 		chanpart->ch_wait_len = 0;
2093 		ch_log(channel, "timed out");
2094 	    }
2095 	    else
2096 	    {
2097 		reader.js_used = 0;
2098 		ch_log(channel, "still waiting on incomplete message");
2099 	    }
2100 	}
2101     }
2102 
2103     if (status == FAIL)
2104     {
2105 	ch_error(channel, "Decoding failed - discarding input");
2106 	ret = FALSE;
2107 	chanpart->ch_wait_len = 0;
2108     }
2109     else if (reader.js_buf[reader.js_used] != NUL)
2110     {
2111 	/* Put the unread part back into the channel. */
2112 	channel_save(channel, part, reader.js_buf + reader.js_used,
2113 			(int)(reader.js_end - reader.js_buf) - reader.js_used,
2114 								  TRUE, NULL);
2115 	ret = status == MAYBE ? FALSE: TRUE;
2116     }
2117     else
2118 	ret = FALSE;
2119 
2120     vim_free(reader.js_buf);
2121     return ret;
2122 }
2123 
2124 /*
2125  * Remove "node" from the queue that it is in.  Does not free it.
2126  */
2127     static void
2128 remove_cb_node(cbq_T *head, cbq_T *node)
2129 {
2130     if (node->cq_prev == NULL)
2131 	head->cq_next = node->cq_next;
2132     else
2133 	node->cq_prev->cq_next = node->cq_next;
2134     if (node->cq_next == NULL)
2135 	head->cq_prev = node->cq_prev;
2136     else
2137 	node->cq_next->cq_prev = node->cq_prev;
2138 }
2139 
2140 /*
2141  * Remove "node" from the queue that it is in and free it.
2142  * Caller should have freed or used node->jq_value.
2143  */
2144     static void
2145 remove_json_node(jsonq_T *head, jsonq_T *node)
2146 {
2147     if (node->jq_prev == NULL)
2148 	head->jq_next = node->jq_next;
2149     else
2150 	node->jq_prev->jq_next = node->jq_next;
2151     if (node->jq_next == NULL)
2152 	head->jq_prev = node->jq_prev;
2153     else
2154 	node->jq_next->jq_prev = node->jq_prev;
2155     vim_free(node);
2156 }
2157 
2158 /*
2159  * Get a message from the JSON queue for channel "channel".
2160  * When "id" is positive it must match the first number in the list.
2161  * When "id" is zero or negative jut get the first message.  But not the one
2162  * with id ch_block_id.
2163  * When "without_callback" is TRUE also get messages that were pushed back.
2164  * Return OK when found and return the value in "rettv".
2165  * Return FAIL otherwise.
2166  */
2167     static int
2168 channel_get_json(
2169 	channel_T   *channel,
2170 	ch_part_T   part,
2171 	int	    id,
2172 	int	    without_callback,
2173 	typval_T    **rettv)
2174 {
2175     jsonq_T   *head = &channel->ch_part[part].ch_json_head;
2176     jsonq_T   *item = head->jq_next;
2177 
2178     while (item != NULL)
2179     {
2180 	list_T	    *l = item->jq_value->vval.v_list;
2181 	typval_T    *tv = &l->lv_first->li_tv;
2182 
2183 	if ((without_callback || !item->jq_no_callback)
2184 	    && ((id > 0 && tv->v_type == VAR_NUMBER && tv->vval.v_number == id)
2185 	      || (id <= 0 && (tv->v_type != VAR_NUMBER
2186 		 || tv->vval.v_number == 0
2187 		 || tv->vval.v_number != channel->ch_part[part].ch_block_id))))
2188 	{
2189 	    *rettv = item->jq_value;
2190 	    if (tv->v_type == VAR_NUMBER)
2191 		ch_log(channel, "Getting JSON message %ld",
2192 						      (long)tv->vval.v_number);
2193 	    remove_json_node(head, item);
2194 	    return OK;
2195 	}
2196 	item = item->jq_next;
2197     }
2198     return FAIL;
2199 }
2200 
2201 /*
2202  * Put back "rettv" into the JSON queue, there was no callback for it.
2203  * Takes over the values in "rettv".
2204  */
2205     static void
2206 channel_push_json(channel_T *channel, ch_part_T part, typval_T *rettv)
2207 {
2208     jsonq_T   *head = &channel->ch_part[part].ch_json_head;
2209     jsonq_T   *item = head->jq_next;
2210     jsonq_T   *newitem;
2211 
2212     if (head->jq_prev != NULL && head->jq_prev->jq_no_callback)
2213 	/* last item was pushed back, append to the end */
2214 	item = NULL;
2215     else while (item != NULL && item->jq_no_callback)
2216 	/* append after the last item that was pushed back */
2217 	item = item->jq_next;
2218 
2219     newitem = (jsonq_T *)alloc((unsigned)sizeof(jsonq_T));
2220     if (newitem == NULL)
2221 	clear_tv(rettv);
2222     else
2223     {
2224 	newitem->jq_value = alloc_tv();
2225 	if (newitem->jq_value == NULL)
2226 	{
2227 	    vim_free(newitem);
2228 	    clear_tv(rettv);
2229 	}
2230 	else
2231 	{
2232 	    newitem->jq_no_callback = FALSE;
2233 	    *newitem->jq_value = *rettv;
2234 	    if (item == NULL)
2235 	    {
2236 		/* append to the end */
2237 		newitem->jq_prev = head->jq_prev;
2238 		head->jq_prev = newitem;
2239 		newitem->jq_next = NULL;
2240 		if (newitem->jq_prev == NULL)
2241 		    head->jq_next = newitem;
2242 		else
2243 		    newitem->jq_prev->jq_next = newitem;
2244 	    }
2245 	    else
2246 	    {
2247 		/* append after "item" */
2248 		newitem->jq_prev = item;
2249 		newitem->jq_next = item->jq_next;
2250 		item->jq_next = newitem;
2251 		if (newitem->jq_next == NULL)
2252 		    head->jq_prev = newitem;
2253 		else
2254 		    newitem->jq_next->jq_prev = newitem;
2255 	    }
2256 	}
2257     }
2258 }
2259 
2260 #define CH_JSON_MAX_ARGS 4
2261 
2262 /*
2263  * Execute a command received over "channel"/"part"
2264  * "argv[0]" is the command string.
2265  * "argv[1]" etc. have further arguments, type is VAR_UNKNOWN if missing.
2266  */
2267     static void
2268 channel_exe_cmd(channel_T *channel, ch_part_T part, typval_T *argv)
2269 {
2270     char_u  *cmd = argv[0].vval.v_string;
2271     char_u  *arg;
2272     int	    options = channel->ch_part[part].ch_mode == MODE_JS ? JSON_JS : 0;
2273 
2274     if (argv[1].v_type != VAR_STRING)
2275     {
2276 	ch_error(channel, "received command with non-string argument");
2277 	if (p_verbose > 2)
2278 	    emsg(_("E903: received command with non-string argument"));
2279 	return;
2280     }
2281     arg = argv[1].vval.v_string;
2282     if (arg == NULL)
2283 	arg = (char_u *)"";
2284 
2285     if (STRCMP(cmd, "ex") == 0)
2286     {
2287 	int save_called_emsg = called_emsg;
2288 
2289 	called_emsg = FALSE;
2290 	ch_log(channel, "Executing ex command '%s'", (char *)arg);
2291 	++emsg_silent;
2292 	do_cmdline_cmd(arg);
2293 	--emsg_silent;
2294 	if (called_emsg)
2295 	    ch_log(channel, "Ex command error: '%s'",
2296 					  (char *)get_vim_var_str(VV_ERRMSG));
2297 	called_emsg = save_called_emsg;
2298     }
2299     else if (STRCMP(cmd, "normal") == 0)
2300     {
2301 	exarg_T ea;
2302 
2303 	ch_log(channel, "Executing normal command '%s'", (char *)arg);
2304 	ea.arg = arg;
2305 	ea.addr_count = 0;
2306 	ea.forceit = TRUE; /* no mapping */
2307 	ex_normal(&ea);
2308     }
2309     else if (STRCMP(cmd, "redraw") == 0)
2310     {
2311 	exarg_T ea;
2312 
2313 	ch_log(channel, "redraw");
2314 	ea.forceit = *arg != NUL;
2315 	ex_redraw(&ea);
2316 	showruler(FALSE);
2317 	setcursor();
2318 	out_flush_cursor(TRUE, FALSE);
2319     }
2320     else if (STRCMP(cmd, "expr") == 0 || STRCMP(cmd, "call") == 0)
2321     {
2322 	int is_call = cmd[0] == 'c';
2323 	int id_idx = is_call ? 3 : 2;
2324 
2325 	if (argv[id_idx].v_type != VAR_UNKNOWN
2326 					 && argv[id_idx].v_type != VAR_NUMBER)
2327 	{
2328 	    ch_error(channel, "last argument for expr/call must be a number");
2329 	    if (p_verbose > 2)
2330 		emsg(_("E904: last argument for expr/call must be a number"));
2331 	}
2332 	else if (is_call && argv[2].v_type != VAR_LIST)
2333 	{
2334 	    ch_error(channel, "third argument for call must be a list");
2335 	    if (p_verbose > 2)
2336 		emsg(_("E904: third argument for call must be a list"));
2337 	}
2338 	else
2339 	{
2340 	    typval_T	*tv = NULL;
2341 	    typval_T	res_tv;
2342 	    typval_T	err_tv;
2343 	    char_u	*json = NULL;
2344 
2345 	    /* Don't pollute the display with errors. */
2346 	    ++emsg_skip;
2347 	    if (!is_call)
2348 	    {
2349 		ch_log(channel, "Evaluating expression '%s'", (char *)arg);
2350 		tv = eval_expr(arg, NULL);
2351 	    }
2352 	    else
2353 	    {
2354 		ch_log(channel, "Calling '%s'", (char *)arg);
2355 		if (func_call(arg, &argv[2], NULL, NULL, &res_tv) == OK)
2356 		    tv = &res_tv;
2357 	    }
2358 
2359 	    if (argv[id_idx].v_type == VAR_NUMBER)
2360 	    {
2361 		int id = argv[id_idx].vval.v_number;
2362 
2363 		if (tv != NULL)
2364 		    json = json_encode_nr_expr(id, tv, options | JSON_NL);
2365 		if (tv == NULL || (json != NULL && *json == NUL))
2366 		{
2367 		    /* If evaluation failed or the result can't be encoded
2368 		     * then return the string "ERROR". */
2369 		    vim_free(json);
2370 		    err_tv.v_type = VAR_STRING;
2371 		    err_tv.vval.v_string = (char_u *)"ERROR";
2372 		    json = json_encode_nr_expr(id, &err_tv, options | JSON_NL);
2373 		}
2374 		if (json != NULL)
2375 		{
2376 		    channel_send(channel,
2377 				 part == PART_SOCK ? PART_SOCK : PART_IN,
2378 				 json, (int)STRLEN(json), (char *)cmd);
2379 		    vim_free(json);
2380 		}
2381 	    }
2382 	    --emsg_skip;
2383 	    if (tv == &res_tv)
2384 		clear_tv(tv);
2385 	    else
2386 		free_tv(tv);
2387 	}
2388     }
2389     else if (p_verbose > 2)
2390     {
2391 	ch_error(channel, "Received unknown command: %s", (char *)cmd);
2392 	semsg(_("E905: received unknown command: %s"), cmd);
2393     }
2394 }
2395 
2396 /*
2397  * Invoke the callback at "cbhead".
2398  * Does not redraw but sets channel_need_redraw.
2399  */
2400     static void
2401 invoke_one_time_callback(
2402 	channel_T   *channel,
2403 	cbq_T	    *cbhead,
2404 	cbq_T	    *item,
2405 	typval_T    *argv)
2406 {
2407     ch_log(channel, "Invoking one-time callback %s",
2408 						   (char *)item->cq_callback);
2409     /* Remove the item from the list first, if the callback
2410      * invokes ch_close() the list will be cleared. */
2411     remove_cb_node(cbhead, item);
2412     invoke_callback(channel, item->cq_callback, item->cq_partial, argv);
2413     free_callback(item->cq_callback, item->cq_partial);
2414     vim_free(item);
2415 }
2416 
2417     static void
2418 append_to_buffer(buf_T *buffer, char_u *msg, channel_T *channel, ch_part_T part)
2419 {
2420     bufref_T	save_curbuf = {NULL, 0, 0};
2421     win_T	*save_curwin = NULL;
2422     tabpage_T	*save_curtab = NULL;
2423     linenr_T    lnum = buffer->b_ml.ml_line_count;
2424     int		save_write_to = buffer->b_write_to_channel;
2425     chanpart_T  *ch_part = &channel->ch_part[part];
2426     int		save_p_ma = buffer->b_p_ma;
2427     int		empty = (buffer->b_ml.ml_flags & ML_EMPTY) ? 1 : 0;
2428 
2429     if (!buffer->b_p_ma && !ch_part->ch_nomodifiable)
2430     {
2431 	if (!ch_part->ch_nomod_error)
2432 	{
2433 	    ch_error(channel, "Buffer is not modifiable, cannot append");
2434 	    ch_part->ch_nomod_error = TRUE;
2435 	}
2436 	return;
2437     }
2438 
2439     /* If the buffer is also used as input insert above the last
2440      * line. Don't write these lines. */
2441     if (save_write_to)
2442     {
2443 	--lnum;
2444 	buffer->b_write_to_channel = FALSE;
2445     }
2446 
2447     /* Append to the buffer */
2448     ch_log(channel, "appending line %d to buffer", (int)lnum + 1 - empty);
2449 
2450     buffer->b_p_ma = TRUE;
2451 
2452     /* Save curbuf/curwin/curtab and make "buffer" the current buffer. */
2453     switch_to_win_for_buf(buffer, &save_curwin, &save_curtab, &save_curbuf);
2454 
2455     u_sync(TRUE);
2456     /* ignore undo failure, undo is not very useful here */
2457     vim_ignored = u_save(lnum - empty, lnum + 1);
2458 
2459     if (empty)
2460     {
2461 	/* The buffer is empty, replace the first (dummy) line. */
2462 	ml_replace(lnum, msg, TRUE);
2463 	lnum = 0;
2464     }
2465     else
2466 	ml_append(lnum, msg, 0, FALSE);
2467     appended_lines_mark(lnum, 1L);
2468 
2469     /* Restore curbuf/curwin/curtab */
2470     restore_win_for_buf(save_curwin, save_curtab, &save_curbuf);
2471 
2472     if (ch_part->ch_nomodifiable)
2473 	buffer->b_p_ma = FALSE;
2474     else
2475 	buffer->b_p_ma = save_p_ma;
2476 
2477     if (buffer->b_nwindows > 0)
2478     {
2479 	win_T	*wp;
2480 
2481 	FOR_ALL_WINDOWS(wp)
2482 	{
2483 	    if (wp->w_buffer == buffer
2484 		    && (save_write_to
2485 			? wp->w_cursor.lnum == lnum + 1
2486 			: (wp->w_cursor.lnum == lnum
2487 			    && wp->w_cursor.col == 0)))
2488 	    {
2489 		++wp->w_cursor.lnum;
2490 		save_curwin = curwin;
2491 		curwin = wp;
2492 		curbuf = curwin->w_buffer;
2493 		scroll_cursor_bot(0, FALSE);
2494 		curwin = save_curwin;
2495 		curbuf = curwin->w_buffer;
2496 	    }
2497 	}
2498 	redraw_buf_and_status_later(buffer, VALID);
2499 	channel_need_redraw = TRUE;
2500     }
2501 
2502     if (save_write_to)
2503     {
2504 	channel_T *ch;
2505 
2506 	/* Find channels reading from this buffer and adjust their
2507 	 * next-to-read line number. */
2508 	buffer->b_write_to_channel = TRUE;
2509 	for (ch = first_channel; ch != NULL; ch = ch->ch_next)
2510 	{
2511 	    chanpart_T  *in_part = &ch->ch_part[PART_IN];
2512 
2513 	    if (in_part->ch_bufref.br_buf == buffer)
2514 		in_part->ch_buf_bot = buffer->b_ml.ml_line_count;
2515 	}
2516     }
2517 }
2518 
2519     static void
2520 drop_messages(channel_T *channel, ch_part_T part)
2521 {
2522     char_u *msg;
2523 
2524     while ((msg = channel_get(channel, part, NULL)) != NULL)
2525     {
2526 	ch_log(channel, "Dropping message '%s'", (char *)msg);
2527 	vim_free(msg);
2528     }
2529 }
2530 
2531 /*
2532  * Invoke a callback for "channel"/"part" if needed.
2533  * This does not redraw but sets channel_need_redraw when redraw is needed.
2534  * Return TRUE when a message was handled, there might be another one.
2535  */
2536     static int
2537 may_invoke_callback(channel_T *channel, ch_part_T part)
2538 {
2539     char_u	*msg = NULL;
2540     typval_T	*listtv = NULL;
2541     typval_T	argv[CH_JSON_MAX_ARGS];
2542     int		seq_nr = -1;
2543     chanpart_T	*ch_part = &channel->ch_part[part];
2544     ch_mode_T	ch_mode = ch_part->ch_mode;
2545     cbq_T	*cbhead = &ch_part->ch_cb_head;
2546     cbq_T	*cbitem;
2547     char_u	*callback = NULL;
2548     partial_T	*partial = NULL;
2549     buf_T	*buffer = NULL;
2550     char_u	*p;
2551 
2552     if (channel->ch_nb_close_cb != NULL)
2553 	/* this channel is handled elsewhere (netbeans) */
2554 	return FALSE;
2555 
2556     /* Use a message-specific callback, part callback or channel callback */
2557     for (cbitem = cbhead->cq_next; cbitem != NULL; cbitem = cbitem->cq_next)
2558 	if (cbitem->cq_seq_nr == 0)
2559 	    break;
2560     if (cbitem != NULL)
2561     {
2562 	callback = cbitem->cq_callback;
2563 	partial = cbitem->cq_partial;
2564     }
2565     else if (ch_part->ch_callback != NULL)
2566     {
2567 	callback = ch_part->ch_callback;
2568 	partial = ch_part->ch_partial;
2569     }
2570     else
2571     {
2572 	callback = channel->ch_callback;
2573 	partial = channel->ch_partial;
2574     }
2575 
2576     buffer = ch_part->ch_bufref.br_buf;
2577     if (buffer != NULL && (!bufref_valid(&ch_part->ch_bufref)
2578 					       || buffer->b_ml.ml_mfp == NULL))
2579     {
2580 	/* buffer was wiped out or unloaded */
2581 	ch_log(channel, "%s buffer has been wiped out", part_names[part]);
2582 	ch_part->ch_bufref.br_buf = NULL;
2583 	buffer = NULL;
2584     }
2585 
2586     if (ch_mode == MODE_JSON || ch_mode == MODE_JS)
2587     {
2588 	listitem_T	*item;
2589 	int		argc = 0;
2590 
2591 	/* Get any json message in the queue. */
2592 	if (channel_get_json(channel, part, -1, FALSE, &listtv) == FAIL)
2593 	{
2594 	    /* Parse readahead, return when there is still no message. */
2595 	    channel_parse_json(channel, part);
2596 	    if (channel_get_json(channel, part, -1, FALSE, &listtv) == FAIL)
2597 		return FALSE;
2598 	}
2599 
2600 	for (item = listtv->vval.v_list->lv_first;
2601 			    item != NULL && argc < CH_JSON_MAX_ARGS;
2602 						    item = item->li_next)
2603 	    argv[argc++] = item->li_tv;
2604 	while (argc < CH_JSON_MAX_ARGS)
2605 	    argv[argc++].v_type = VAR_UNKNOWN;
2606 
2607 	if (argv[0].v_type == VAR_STRING)
2608 	{
2609 	    /* ["cmd", arg] or ["cmd", arg, arg] or ["cmd", arg, arg, arg] */
2610 	    channel_exe_cmd(channel, part, argv);
2611 	    free_tv(listtv);
2612 	    return TRUE;
2613 	}
2614 
2615 	if (argv[0].v_type != VAR_NUMBER)
2616 	{
2617 	    ch_error(channel,
2618 		      "Dropping message with invalid sequence number type");
2619 	    free_tv(listtv);
2620 	    return FALSE;
2621 	}
2622 	seq_nr = argv[0].vval.v_number;
2623     }
2624     else if (channel_peek(channel, part) == NULL)
2625     {
2626 	/* nothing to read on RAW or NL channel */
2627 	return FALSE;
2628     }
2629     else
2630     {
2631 	/* If there is no callback or buffer drop the message. */
2632 	if (callback == NULL && buffer == NULL)
2633 	{
2634 	    /* If there is a close callback it may use ch_read() to get the
2635 	     * messages. */
2636 	    if (channel->ch_close_cb == NULL && !channel->ch_drop_never)
2637 		drop_messages(channel, part);
2638 	    return FALSE;
2639 	}
2640 
2641 	if (ch_mode == MODE_NL)
2642 	{
2643 	    char_u  *nl = NULL;
2644 	    char_u  *buf;
2645 	    readq_T *node;
2646 
2647 	    /* See if we have a message ending in NL in the first buffer.  If
2648 	     * not try to concatenate the first and the second buffer. */
2649 	    while (TRUE)
2650 	    {
2651 		node = channel_peek(channel, part);
2652 		nl = channel_first_nl(node);
2653 		if (nl != NULL)
2654 		    break;
2655 		if (channel_collapse(channel, part, TRUE) == FAIL)
2656 		{
2657 		    if (ch_part->ch_fd == INVALID_FD && node->rq_buflen > 0)
2658 			break;
2659 		    return FALSE; /* incomplete message */
2660 		}
2661 	    }
2662 	    buf = node->rq_buffer;
2663 
2664 	    if (nl == NULL)
2665 	    {
2666 		/* Flush remaining message that is missing a NL. */
2667 		char_u	*new_buf;
2668 
2669 		new_buf = vim_realloc(buf, node->rq_buflen + 1);
2670 		if (new_buf == NULL)
2671 		    /* This might fail over and over again, should the message
2672 		     * be dropped? */
2673 		    return FALSE;
2674 		buf = new_buf;
2675 		node->rq_buffer = buf;
2676 		nl = buf + node->rq_buflen++;
2677 		*nl = NUL;
2678 	    }
2679 
2680 	    /* Convert NUL to NL, the internal representation. */
2681 	    for (p = buf; p < nl && p < buf + node->rq_buflen; ++p)
2682 		if (*p == NUL)
2683 		    *p = NL;
2684 
2685 	    if (nl + 1 == buf + node->rq_buflen)
2686 	    {
2687 		/* get the whole buffer, drop the NL */
2688 		msg = channel_get(channel, part, NULL);
2689 		*nl = NUL;
2690 	    }
2691 	    else
2692 	    {
2693 		/* Copy the message into allocated memory (excluding the NL)
2694 		 * and remove it from the buffer (including the NL). */
2695 		msg = vim_strnsave(buf, (int)(nl - buf));
2696 		channel_consume(channel, part, (int)(nl - buf) + 1);
2697 	    }
2698 	}
2699 	else
2700 	{
2701 	    /* For a raw channel we don't know where the message ends, just
2702 	     * get everything we have.
2703 	     * Convert NUL to NL, the internal representation. */
2704 	    msg = channel_get_all(channel, part, NULL);
2705 	}
2706 
2707 	if (msg == NULL)
2708 	    return FALSE; /* out of memory (and avoids Coverity warning) */
2709 
2710 	argv[1].v_type = VAR_STRING;
2711 	argv[1].vval.v_string = msg;
2712     }
2713 
2714     if (seq_nr > 0)
2715     {
2716 	int	done = FALSE;
2717 
2718 	/* JSON or JS mode: invoke the one-time callback with the matching nr */
2719 	for (cbitem = cbhead->cq_next; cbitem != NULL; cbitem = cbitem->cq_next)
2720 	    if (cbitem->cq_seq_nr == seq_nr)
2721 	    {
2722 		invoke_one_time_callback(channel, cbhead, cbitem, argv);
2723 		done = TRUE;
2724 		break;
2725 	    }
2726 	if (!done)
2727 	{
2728 	    if (channel->ch_drop_never)
2729 	    {
2730 		/* message must be read with ch_read() */
2731 		channel_push_json(channel, part, listtv);
2732 		listtv = NULL;
2733 	    }
2734 	    else
2735 		ch_log(channel, "Dropping message %d without callback",
2736 								       seq_nr);
2737 	}
2738     }
2739     else if (callback != NULL || buffer != NULL)
2740     {
2741 	if (buffer != NULL)
2742 	{
2743 	    if (msg == NULL)
2744 		/* JSON or JS mode: re-encode the message. */
2745 		msg = json_encode(listtv, ch_mode);
2746 	    if (msg != NULL)
2747 	    {
2748 #ifdef FEAT_TERMINAL
2749 		if (buffer->b_term != NULL)
2750 		    write_to_term(buffer, msg, channel);
2751 		else
2752 #endif
2753 		    append_to_buffer(buffer, msg, channel, part);
2754 	    }
2755 	}
2756 
2757 	if (callback != NULL)
2758 	{
2759 	    if (cbitem != NULL)
2760 		invoke_one_time_callback(channel, cbhead, cbitem, argv);
2761 	    else
2762 	    {
2763 		/* invoke the channel callback */
2764 		ch_log(channel, "Invoking channel callback %s",
2765 							    (char *)callback);
2766 		invoke_callback(channel, callback, partial, argv);
2767 	    }
2768 	}
2769     }
2770     else
2771 	ch_log(channel, "Dropping message %d", seq_nr);
2772 
2773     if (listtv != NULL)
2774 	free_tv(listtv);
2775     vim_free(msg);
2776 
2777     return TRUE;
2778 }
2779 
2780 #if defined(FEAT_NETBEANS_INTG) || defined(PROTO)
2781 /*
2782  * Return TRUE when channel "channel" is open for writing to.
2783  * Also returns FALSE or invalid "channel".
2784  */
2785     int
2786 channel_can_write_to(channel_T *channel)
2787 {
2788     return channel != NULL && (channel->CH_SOCK_FD != INVALID_FD
2789 			  || channel->CH_IN_FD != INVALID_FD);
2790 }
2791 #endif
2792 
2793 /*
2794  * Return TRUE when channel "channel" is open for reading or writing.
2795  * Also returns FALSE for invalid "channel".
2796  */
2797     int
2798 channel_is_open(channel_T *channel)
2799 {
2800     return channel != NULL && (channel->CH_SOCK_FD != INVALID_FD
2801 			  || channel->CH_IN_FD != INVALID_FD
2802 			  || channel->CH_OUT_FD != INVALID_FD
2803 			  || channel->CH_ERR_FD != INVALID_FD);
2804 }
2805 
2806 /*
2807  * Return TRUE if "channel" has JSON or other typeahead.
2808  */
2809     int
2810 channel_has_readahead(channel_T *channel, ch_part_T part)
2811 {
2812     ch_mode_T	ch_mode = channel->ch_part[part].ch_mode;
2813 
2814     if (ch_mode == MODE_JSON || ch_mode == MODE_JS)
2815     {
2816 	jsonq_T   *head = &channel->ch_part[part].ch_json_head;
2817 	jsonq_T   *item = head->jq_next;
2818 
2819 	return item != NULL;
2820     }
2821     return channel_peek(channel, part) != NULL;
2822 }
2823 
2824 /*
2825  * Return a string indicating the status of the channel.
2826  * If "req_part" is not negative check that part.
2827  */
2828     char *
2829 channel_status(channel_T *channel, int req_part)
2830 {
2831     ch_part_T part;
2832     int has_readahead = FALSE;
2833 
2834     if (channel == NULL)
2835 	 return "fail";
2836     if (req_part == PART_OUT)
2837     {
2838 	if (channel->CH_OUT_FD != INVALID_FD)
2839 	    return "open";
2840 	if (channel_has_readahead(channel, PART_OUT))
2841 	    has_readahead = TRUE;
2842     }
2843     else if (req_part == PART_ERR)
2844     {
2845 	if (channel->CH_ERR_FD != INVALID_FD)
2846 	    return "open";
2847 	if (channel_has_readahead(channel, PART_ERR))
2848 	    has_readahead = TRUE;
2849     }
2850     else
2851     {
2852 	if (channel_is_open(channel))
2853 	    return "open";
2854 	for (part = PART_SOCK; part < PART_IN; ++part)
2855 	    if (channel_has_readahead(channel, part))
2856 	    {
2857 		has_readahead = TRUE;
2858 		break;
2859 	    }
2860     }
2861 
2862     if (has_readahead)
2863 	return "buffered";
2864     return "closed";
2865 }
2866 
2867     static void
2868 channel_part_info(channel_T *channel, dict_T *dict, char *name, ch_part_T part)
2869 {
2870     chanpart_T *chanpart = &channel->ch_part[part];
2871     char	namebuf[20];  /* longest is "sock_timeout" */
2872     size_t	tail;
2873     char	*status;
2874     char	*s = "";
2875 
2876     vim_strncpy((char_u *)namebuf, (char_u *)name, 4);
2877     STRCAT(namebuf, "_");
2878     tail = STRLEN(namebuf);
2879 
2880     STRCPY(namebuf + tail, "status");
2881     if (chanpart->ch_fd != INVALID_FD)
2882 	status = "open";
2883     else if (channel_has_readahead(channel, part))
2884 	status = "buffered";
2885     else
2886 	status = "closed";
2887     dict_add_string(dict, namebuf, (char_u *)status);
2888 
2889     STRCPY(namebuf + tail, "mode");
2890     switch (chanpart->ch_mode)
2891     {
2892 	case MODE_NL: s = "NL"; break;
2893 	case MODE_RAW: s = "RAW"; break;
2894 	case MODE_JSON: s = "JSON"; break;
2895 	case MODE_JS: s = "JS"; break;
2896     }
2897     dict_add_string(dict, namebuf, (char_u *)s);
2898 
2899     STRCPY(namebuf + tail, "io");
2900     if (part == PART_SOCK)
2901 	s = "socket";
2902     else switch (chanpart->ch_io)
2903     {
2904 	case JIO_NULL: s = "null"; break;
2905 	case JIO_PIPE: s = "pipe"; break;
2906 	case JIO_FILE: s = "file"; break;
2907 	case JIO_BUFFER: s = "buffer"; break;
2908 	case JIO_OUT: s = "out"; break;
2909     }
2910     dict_add_string(dict, namebuf, (char_u *)s);
2911 
2912     STRCPY(namebuf + tail, "timeout");
2913     dict_add_number(dict, namebuf, chanpart->ch_timeout);
2914 }
2915 
2916     void
2917 channel_info(channel_T *channel, dict_T *dict)
2918 {
2919     dict_add_number(dict, "id", channel->ch_id);
2920     dict_add_string(dict, "status", (char_u *)channel_status(channel, -1));
2921 
2922     if (channel->ch_hostname != NULL)
2923     {
2924 	dict_add_string(dict, "hostname", (char_u *)channel->ch_hostname);
2925 	dict_add_number(dict, "port", channel->ch_port);
2926 	channel_part_info(channel, dict, "sock", PART_SOCK);
2927     }
2928     else
2929     {
2930 	channel_part_info(channel, dict, "out", PART_OUT);
2931 	channel_part_info(channel, dict, "err", PART_ERR);
2932 	channel_part_info(channel, dict, "in", PART_IN);
2933     }
2934 }
2935 
2936 /*
2937  * Close channel "channel".
2938  * Trigger the close callback if "invoke_close_cb" is TRUE.
2939  * Does not clear the buffers.
2940  */
2941     void
2942 channel_close(channel_T *channel, int invoke_close_cb)
2943 {
2944     ch_log(channel, "Closing channel");
2945 
2946 #ifdef FEAT_GUI
2947     channel_gui_unregister(channel);
2948 #endif
2949 
2950     ch_close_part(channel, PART_SOCK);
2951     ch_close_part(channel, PART_IN);
2952     ch_close_part(channel, PART_OUT);
2953     ch_close_part(channel, PART_ERR);
2954 
2955     if (invoke_close_cb)
2956     {
2957 	ch_part_T	part;
2958 
2959 	/* Invoke callbacks and flush buffers before the close callback. */
2960 	if (channel->ch_close_cb != NULL)
2961 	    ch_log(channel,
2962 		     "Invoking callbacks and flushing buffers before closing");
2963 	for (part = PART_SOCK; part < PART_IN; ++part)
2964 	{
2965 	    if (channel->ch_close_cb != NULL
2966 			    || channel->ch_part[part].ch_bufref.br_buf != NULL)
2967 	    {
2968 		/* Increment the refcount to avoid the channel being freed
2969 		 * halfway. */
2970 		++channel->ch_refcount;
2971 		if (channel->ch_close_cb == NULL)
2972 		    ch_log(channel, "flushing %s buffers before closing",
2973 							     part_names[part]);
2974 		while (may_invoke_callback(channel, part))
2975 		    ;
2976 		--channel->ch_refcount;
2977 	    }
2978 	}
2979 
2980 	if (channel->ch_close_cb != NULL)
2981 	{
2982 	      typval_T	argv[1];
2983 	      typval_T	rettv;
2984 	      int		dummy;
2985 
2986 	      /* Increment the refcount to avoid the channel being freed
2987 	       * halfway. */
2988 	      ++channel->ch_refcount;
2989 	      ch_log(channel, "Invoking close callback %s",
2990 						(char *)channel->ch_close_cb);
2991 	      argv[0].v_type = VAR_CHANNEL;
2992 	      argv[0].vval.v_channel = channel;
2993 	      call_func(channel->ch_close_cb, (int)STRLEN(channel->ch_close_cb),
2994 			   &rettv, 1, argv, NULL, 0L, 0L, &dummy, TRUE,
2995 			   channel->ch_close_partial, NULL);
2996 	      clear_tv(&rettv);
2997 	      channel_need_redraw = TRUE;
2998 
2999 	      /* the callback is only called once */
3000 	      free_callback(channel->ch_close_cb, channel->ch_close_partial);
3001 	      channel->ch_close_cb = NULL;
3002 	      channel->ch_close_partial = NULL;
3003 
3004 	      if (channel_need_redraw)
3005 	      {
3006 		  channel_need_redraw = FALSE;
3007 		  redraw_after_callback(TRUE);
3008 	      }
3009 
3010 	      if (!channel->ch_drop_never)
3011 		  /* any remaining messages are useless now */
3012 		  for (part = PART_SOCK; part < PART_IN; ++part)
3013 		      drop_messages(channel, part);
3014 
3015 	      --channel->ch_refcount;
3016 	}
3017     }
3018 
3019     channel->ch_nb_close_cb = NULL;
3020 
3021 #ifdef FEAT_TERMINAL
3022     term_channel_closed(channel);
3023 #endif
3024 }
3025 
3026 /*
3027  * Close the "in" part channel "channel".
3028  */
3029     void
3030 channel_close_in(channel_T *channel)
3031 {
3032     ch_close_part(channel, PART_IN);
3033 }
3034 
3035     static void
3036 remove_from_writeque(writeq_T *wq, writeq_T *entry)
3037 {
3038     ga_clear(&entry->wq_ga);
3039     wq->wq_next = entry->wq_next;
3040     if (wq->wq_next == NULL)
3041 	wq->wq_prev = NULL;
3042     else
3043 	wq->wq_next->wq_prev = NULL;
3044     vim_free(entry);
3045 }
3046 
3047 /*
3048  * Clear the read buffer on "channel"/"part".
3049  */
3050     static void
3051 channel_clear_one(channel_T *channel, ch_part_T part)
3052 {
3053     chanpart_T *ch_part = &channel->ch_part[part];
3054     jsonq_T *json_head = &ch_part->ch_json_head;
3055     cbq_T   *cb_head = &ch_part->ch_cb_head;
3056 
3057     while (channel_peek(channel, part) != NULL)
3058 	vim_free(channel_get(channel, part, NULL));
3059 
3060     while (cb_head->cq_next != NULL)
3061     {
3062 	cbq_T *node = cb_head->cq_next;
3063 
3064 	remove_cb_node(cb_head, node);
3065 	free_callback(node->cq_callback, node->cq_partial);
3066 	vim_free(node);
3067     }
3068 
3069     while (json_head->jq_next != NULL)
3070     {
3071 	free_tv(json_head->jq_next->jq_value);
3072 	remove_json_node(json_head, json_head->jq_next);
3073     }
3074 
3075     free_callback(ch_part->ch_callback, ch_part->ch_partial);
3076     ch_part->ch_callback = NULL;
3077     ch_part->ch_partial = NULL;
3078 
3079     while (ch_part->ch_writeque.wq_next != NULL)
3080 	remove_from_writeque(&ch_part->ch_writeque,
3081 						 ch_part->ch_writeque.wq_next);
3082 }
3083 
3084 /*
3085  * Clear all the read buffers on "channel".
3086  */
3087     void
3088 channel_clear(channel_T *channel)
3089 {
3090     ch_log(channel, "Clearing channel");
3091     VIM_CLEAR(channel->ch_hostname);
3092     channel_clear_one(channel, PART_SOCK);
3093     channel_clear_one(channel, PART_OUT);
3094     channel_clear_one(channel, PART_ERR);
3095     channel_clear_one(channel, PART_IN);
3096     free_callback(channel->ch_callback, channel->ch_partial);
3097     channel->ch_callback = NULL;
3098     channel->ch_partial = NULL;
3099     free_callback(channel->ch_close_cb, channel->ch_close_partial);
3100     channel->ch_close_cb = NULL;
3101     channel->ch_close_partial = NULL;
3102 }
3103 
3104 #if defined(EXITFREE) || defined(PROTO)
3105     void
3106 channel_free_all(void)
3107 {
3108     channel_T *channel;
3109 
3110     ch_log(NULL, "channel_free_all()");
3111     for (channel = first_channel; channel != NULL; channel = channel->ch_next)
3112 	channel_clear(channel);
3113 }
3114 #endif
3115 
3116 
3117 /* Sent when the netbeans channel is found closed when reading. */
3118 #define DETACH_MSG_RAW "DETACH\n"
3119 
3120 /* Buffer size for reading incoming messages. */
3121 #define MAXMSGSIZE 4096
3122 
3123 #if defined(HAVE_SELECT)
3124 /*
3125  * Add write fds where we are waiting for writing to be possible.
3126  */
3127     static int
3128 channel_fill_wfds(int maxfd_arg, fd_set *wfds)
3129 {
3130     int		maxfd = maxfd_arg;
3131     channel_T	*ch;
3132 
3133     for (ch = first_channel; ch != NULL; ch = ch->ch_next)
3134     {
3135 	chanpart_T  *in_part = &ch->ch_part[PART_IN];
3136 
3137 	if (in_part->ch_fd != INVALID_FD
3138 		&& (in_part->ch_bufref.br_buf != NULL
3139 		    || in_part->ch_writeque.wq_next != NULL))
3140 	{
3141 	    FD_SET((int)in_part->ch_fd, wfds);
3142 	    if ((int)in_part->ch_fd >= maxfd)
3143 		maxfd = (int)in_part->ch_fd + 1;
3144 	}
3145     }
3146     return maxfd;
3147 }
3148 #else
3149 /*
3150  * Add write fds where we are waiting for writing to be possible.
3151  */
3152     static int
3153 channel_fill_poll_write(int nfd_in, struct pollfd *fds)
3154 {
3155     int		nfd = nfd_in;
3156     channel_T	*ch;
3157 
3158     for (ch = first_channel; ch != NULL; ch = ch->ch_next)
3159     {
3160 	chanpart_T  *in_part = &ch->ch_part[PART_IN];
3161 
3162 	if (in_part->ch_fd != INVALID_FD
3163 		&& (in_part->ch_bufref.br_buf != NULL
3164 		    || in_part->ch_writeque.wq_next != NULL))
3165 	{
3166 	    in_part->ch_poll_idx = nfd;
3167 	    fds[nfd].fd = in_part->ch_fd;
3168 	    fds[nfd].events = POLLOUT;
3169 	    ++nfd;
3170 	}
3171 	else
3172 	    in_part->ch_poll_idx = -1;
3173     }
3174     return nfd;
3175 }
3176 #endif
3177 
3178 typedef enum {
3179     CW_READY,
3180     CW_NOT_READY,
3181     CW_ERROR
3182 } channel_wait_result;
3183 
3184 /*
3185  * Check for reading from "fd" with "timeout" msec.
3186  * Return CW_READY when there is something to read.
3187  * Return CW_NOT_READY when there is nothing to read.
3188  * Return CW_ERROR when there is an error.
3189  */
3190     static channel_wait_result
3191 channel_wait(channel_T *channel, sock_T fd, int timeout)
3192 {
3193     if (timeout > 0)
3194 	ch_log(channel, "Waiting for up to %d msec", timeout);
3195 
3196 # ifdef WIN32
3197     if (fd != channel->CH_SOCK_FD)
3198     {
3199 	DWORD	nread;
3200 	int	sleep_time;
3201 	DWORD	deadline = GetTickCount() + timeout;
3202 	int	delay = 1;
3203 
3204 	/* reading from a pipe, not a socket */
3205 	while (TRUE)
3206 	{
3207 	    int r = PeekNamedPipe((HANDLE)fd, NULL, 0, NULL, &nread, NULL);
3208 
3209 	    if (r && nread > 0)
3210 		return CW_READY;
3211 
3212 	    if (channel->ch_named_pipe)
3213 	    {
3214 		DisconnectNamedPipe((HANDLE)fd);
3215 		ConnectNamedPipe((HANDLE)fd, NULL);
3216 	    }
3217 	    else if (r == 0)
3218 		return CW_ERROR;
3219 
3220 	    /* perhaps write some buffer lines */
3221 	    channel_write_any_lines();
3222 
3223 	    sleep_time = deadline - GetTickCount();
3224 	    if (sleep_time <= 0)
3225 		break;
3226 	    /* Wait for a little while.  Very short at first, up to 10 msec
3227 	     * after looping a few times. */
3228 	    if (sleep_time > delay)
3229 		sleep_time = delay;
3230 	    Sleep(sleep_time);
3231 	    delay = delay * 2;
3232 	    if (delay > 10)
3233 		delay = 10;
3234 	}
3235     }
3236     else
3237 #endif
3238     {
3239 #if defined(HAVE_SELECT)
3240 	struct timeval	tval;
3241 	fd_set		rfds;
3242 	fd_set		wfds;
3243 	int		ret;
3244 	int		maxfd;
3245 
3246 	tval.tv_sec = timeout / 1000;
3247 	tval.tv_usec = (timeout % 1000) * 1000;
3248 	for (;;)
3249 	{
3250 	    FD_ZERO(&rfds);
3251 	    FD_SET((int)fd, &rfds);
3252 
3253 	    /* Write lines to a pipe when a pipe can be written to.  Need to
3254 	     * set this every time, some buffers may be done. */
3255 	    maxfd = (int)fd + 1;
3256 	    FD_ZERO(&wfds);
3257 	    maxfd = channel_fill_wfds(maxfd, &wfds);
3258 
3259 	    ret = select(maxfd, &rfds, &wfds, NULL, &tval);
3260 # ifdef EINTR
3261 	    SOCK_ERRNO;
3262 	    if (ret == -1 && errno == EINTR)
3263 		continue;
3264 # endif
3265 	    if (ret > 0)
3266 	    {
3267 		if (FD_ISSET(fd, &rfds))
3268 		    return CW_READY;
3269 		channel_write_any_lines();
3270 		continue;
3271 	    }
3272 	    break;
3273 	}
3274 #else
3275 	for (;;)
3276 	{
3277 	    struct pollfd   fds[MAX_OPEN_CHANNELS + 1];
3278 	    int		    nfd = 1;
3279 
3280 	    fds[0].fd = fd;
3281 	    fds[0].events = POLLIN;
3282 	    nfd = channel_fill_poll_write(nfd, fds);
3283 	    if (poll(fds, nfd, timeout) > 0)
3284 	    {
3285 		if (fds[0].revents & POLLIN)
3286 		    return CW_READY;
3287 		channel_write_any_lines();
3288 		continue;
3289 	    }
3290 	    break;
3291 	}
3292 #endif
3293     }
3294     return CW_NOT_READY;
3295 }
3296 
3297     static void
3298 ch_close_part_on_error(
3299 	channel_T *channel, ch_part_T part, int is_err, char *func)
3300 {
3301     char	msg[] = "%s(): Read %s from ch_part[%d], closing";
3302 
3303     if (is_err)
3304 	/* Do not call emsg(), most likely the other end just exited. */
3305 	ch_error(channel, msg, func, "error", part);
3306     else
3307 	ch_log(channel, msg, func, "EOF", part);
3308 
3309     /* Queue a "DETACH" netbeans message in the command queue in order to
3310      * terminate the netbeans session later. Do not end the session here
3311      * directly as we may be running in the context of a call to
3312      * netbeans_parse_messages():
3313      *	netbeans_parse_messages
3314      *	    -> autocmd triggered while processing the netbeans cmd
3315      *		-> ui_breakcheck
3316      *		    -> gui event loop or select loop
3317      *			-> channel_read()
3318      * Only send "DETACH" for a netbeans channel.
3319      */
3320     if (channel->ch_nb_close_cb != NULL)
3321 	channel_save(channel, PART_SOCK, (char_u *)DETACH_MSG_RAW,
3322 			      (int)STRLEN(DETACH_MSG_RAW), FALSE, "PUT ");
3323 
3324     /* When reading is not possible close this part of the channel.  Don't
3325      * close the channel yet, there may be something to read on another part.
3326      * When stdout and stderr use the same FD we get the error only on one of
3327      * them, also close the other. */
3328     if (part == PART_OUT || part == PART_ERR)
3329     {
3330 	ch_part_T other = part == PART_OUT ? PART_ERR : PART_OUT;
3331 
3332 	if (channel->ch_part[part].ch_fd == channel->ch_part[other].ch_fd)
3333 	    ch_close_part(channel, other);
3334     }
3335     ch_close_part(channel, part);
3336 
3337 #ifdef FEAT_GUI
3338     /* Stop listening to GUI events right away. */
3339     channel_gui_unregister_one(channel, part);
3340 #endif
3341 }
3342 
3343     static void
3344 channel_close_now(channel_T *channel)
3345 {
3346     ch_log(channel, "Closing channel because all readable fds are closed");
3347     if (channel->ch_nb_close_cb != NULL)
3348 	(*channel->ch_nb_close_cb)();
3349     channel_close(channel, TRUE);
3350 }
3351 
3352 /*
3353  * Read from channel "channel" for as long as there is something to read.
3354  * "part" is PART_SOCK, PART_OUT or PART_ERR.
3355  * The data is put in the read queue.  No callbacks are invoked here.
3356  */
3357     static void
3358 channel_read(channel_T *channel, ch_part_T part, char *func)
3359 {
3360     static char_u	*buf = NULL;
3361     int			len = 0;
3362     int			readlen = 0;
3363     sock_T		fd;
3364     int			use_socket = FALSE;
3365 
3366     fd = channel->ch_part[part].ch_fd;
3367     if (fd == INVALID_FD)
3368     {
3369 	ch_error(channel, "channel_read() called while %s part is closed",
3370 							    part_names[part]);
3371 	return;
3372     }
3373     use_socket = fd == channel->CH_SOCK_FD;
3374 
3375     /* Allocate a buffer to read into. */
3376     if (buf == NULL)
3377     {
3378 	buf = alloc(MAXMSGSIZE);
3379 	if (buf == NULL)
3380 	    return;	/* out of memory! */
3381     }
3382 
3383     /* Keep on reading for as long as there is something to read.
3384      * Use select() or poll() to avoid blocking on a message that is exactly
3385      * MAXMSGSIZE long. */
3386     for (;;)
3387     {
3388 	if (channel_wait(channel, fd, 0) != CW_READY)
3389 	    break;
3390 	if (use_socket)
3391 	    len = sock_read(fd, (char *)buf, MAXMSGSIZE);
3392 	else
3393 	    len = fd_read(fd, (char *)buf, MAXMSGSIZE);
3394 	if (len <= 0)
3395 	    break;	/* error or nothing more to read */
3396 
3397 	/* Store the read message in the queue. */
3398 	channel_save(channel, part, buf, len, FALSE, "RECV ");
3399 	readlen += len;
3400 	if (len < MAXMSGSIZE)
3401 	    break;	/* did read everything that's available */
3402     }
3403 
3404     /* Reading a disconnection (readlen == 0), or an error. */
3405     if (readlen <= 0)
3406     {
3407 	if (!channel->ch_keep_open)
3408 	    ch_close_part_on_error(channel, part, (len < 0), func);
3409     }
3410 #if defined(CH_HAS_GUI) && defined(FEAT_GUI_GTK)
3411     else if (CH_HAS_GUI && gtk_main_level() > 0)
3412 	/* signal the main loop that there is something to read */
3413 	gtk_main_quit();
3414 #endif
3415 }
3416 
3417 /*
3418  * Read from RAW or NL "channel"/"part".  Blocks until there is something to
3419  * read or the timeout expires.
3420  * When "raw" is TRUE don't block waiting on a NL.
3421  * Returns what was read in allocated memory.
3422  * Returns NULL in case of error or timeout.
3423  */
3424     static char_u *
3425 channel_read_block(
3426 	channel_T *channel, ch_part_T part, int timeout, int raw, int *outlen)
3427 {
3428     char_u	*buf;
3429     char_u	*msg;
3430     ch_mode_T	mode = channel->ch_part[part].ch_mode;
3431     sock_T	fd = channel->ch_part[part].ch_fd;
3432     char_u	*nl;
3433     readq_T	*node;
3434 
3435     ch_log(channel, "Blocking %s read, timeout: %d msec",
3436 				     mode == MODE_RAW ? "RAW" : "NL", timeout);
3437 
3438     while (TRUE)
3439     {
3440 	node = channel_peek(channel, part);
3441 	if (node != NULL)
3442 	{
3443 	    if (mode == MODE_RAW || (mode == MODE_NL
3444 					   && channel_first_nl(node) != NULL))
3445 		/* got a complete message */
3446 		break;
3447 	    if (channel_collapse(channel, part, mode == MODE_NL) == OK)
3448 		continue;
3449 	    /* If not blocking or nothing more is coming then return what we
3450 	     * have. */
3451 	    if (raw || fd == INVALID_FD)
3452 		break;
3453 	}
3454 
3455 	/* Wait for up to the channel timeout. */
3456 	if (fd == INVALID_FD)
3457 	    return NULL;
3458 	if (channel_wait(channel, fd, timeout) != CW_READY)
3459 	{
3460 	    ch_log(channel, "Timed out");
3461 	    return NULL;
3462 	}
3463 	channel_read(channel, part, "channel_read_block");
3464     }
3465 
3466     /* We have a complete message now. */
3467     if (mode == MODE_RAW || outlen != NULL)
3468     {
3469 	msg = channel_get_all(channel, part, outlen);
3470     }
3471     else
3472     {
3473 	char_u *p;
3474 
3475 	buf = node->rq_buffer;
3476 	nl = channel_first_nl(node);
3477 
3478 	/* Convert NUL to NL, the internal representation. */
3479 	for (p = buf; (nl == NULL || p < nl) && p < buf + node->rq_buflen; ++p)
3480 	    if (*p == NUL)
3481 		*p = NL;
3482 
3483 	if (nl == NULL)
3484 	{
3485 	    /* must be a closed channel with missing NL */
3486 	    msg = channel_get(channel, part, NULL);
3487 	}
3488 	else if (nl + 1 == buf + node->rq_buflen)
3489 	{
3490 	    /* get the whole buffer */
3491 	    msg = channel_get(channel, part, NULL);
3492 	    *nl = NUL;
3493 	}
3494 	else
3495 	{
3496 	    /* Copy the message into allocated memory and remove it from the
3497 	     * buffer. */
3498 	    msg = vim_strnsave(buf, (int)(nl - buf));
3499 	    channel_consume(channel, part, (int)(nl - buf) + 1);
3500 	}
3501     }
3502     if (ch_log_active())
3503 	ch_log(channel, "Returning %d bytes", (int)STRLEN(msg));
3504     return msg;
3505 }
3506 
3507 /*
3508  * Read one JSON message with ID "id" from "channel"/"part" and store the
3509  * result in "rettv".
3510  * When "id" is -1 accept any message;
3511  * Blocks until the message is received or the timeout is reached.
3512  */
3513     static int
3514 channel_read_json_block(
3515 	channel_T   *channel,
3516 	ch_part_T   part,
3517 	int	    timeout_arg,
3518 	int	    id,
3519 	typval_T    **rettv)
3520 {
3521     int		more;
3522     sock_T	fd;
3523     int		timeout;
3524     chanpart_T	*chanpart = &channel->ch_part[part];
3525 
3526     ch_log(channel, "Reading JSON");
3527     if (id != -1)
3528 	chanpart->ch_block_id = id;
3529     for (;;)
3530     {
3531 	more = channel_parse_json(channel, part);
3532 
3533 	/* search for message "id" */
3534 	if (channel_get_json(channel, part, id, TRUE, rettv) == OK)
3535 	{
3536 	    chanpart->ch_block_id = 0;
3537 	    return OK;
3538 	}
3539 
3540 	if (!more)
3541 	{
3542 	    /* Handle any other messages in the queue.  If done some more
3543 	     * messages may have arrived. */
3544 	    if (channel_parse_messages())
3545 		continue;
3546 
3547 	    /* Wait for up to the timeout.  If there was an incomplete message
3548 	     * use the deadline for that. */
3549 	    timeout = timeout_arg;
3550 	    if (chanpart->ch_wait_len > 0)
3551 	    {
3552 #ifdef WIN32
3553 		timeout = chanpart->ch_deadline - GetTickCount() + 1;
3554 #else
3555 		{
3556 		    struct timeval now_tv;
3557 
3558 		    gettimeofday(&now_tv, NULL);
3559 		    timeout = (chanpart->ch_deadline.tv_sec
3560 						       - now_tv.tv_sec) * 1000
3561 			+ (chanpart->ch_deadline.tv_usec
3562 						     - now_tv.tv_usec) / 1000
3563 			+ 1;
3564 		}
3565 #endif
3566 		if (timeout < 0)
3567 		{
3568 		    /* Something went wrong, channel_parse_json() didn't
3569 		     * discard message.  Cancel waiting. */
3570 		    chanpart->ch_wait_len = 0;
3571 		    timeout = timeout_arg;
3572 		}
3573 		else if (timeout > timeout_arg)
3574 		    timeout = timeout_arg;
3575 	    }
3576 	    fd = chanpart->ch_fd;
3577 	    if (fd == INVALID_FD
3578 			    || channel_wait(channel, fd, timeout) != CW_READY)
3579 	    {
3580 		if (timeout == timeout_arg)
3581 		{
3582 		    if (fd != INVALID_FD)
3583 			ch_log(channel, "Timed out");
3584 		    break;
3585 		}
3586 	    }
3587 	    else
3588 		channel_read(channel, part, "channel_read_json_block");
3589 	}
3590     }
3591     chanpart->ch_block_id = 0;
3592     return FAIL;
3593 }
3594 
3595 /*
3596  * Common for ch_read() and ch_readraw().
3597  */
3598     void
3599 common_channel_read(typval_T *argvars, typval_T *rettv, int raw, int blob)
3600 {
3601     channel_T	*channel;
3602     ch_part_T	part = PART_COUNT;
3603     jobopt_T	opt;
3604     int		mode;
3605     int		timeout;
3606     int		id = -1;
3607     typval_T	*listtv = NULL;
3608 
3609     /* return an empty string by default */
3610     rettv->v_type = VAR_STRING;
3611     rettv->vval.v_string = NULL;
3612 
3613     clear_job_options(&opt);
3614     if (get_job_options(&argvars[1], &opt, JO_TIMEOUT + JO_PART + JO_ID, 0)
3615 								      == FAIL)
3616 	goto theend;
3617 
3618     if (opt.jo_set & JO_PART)
3619 	part = opt.jo_part;
3620     channel = get_channel_arg(&argvars[0], TRUE, TRUE, part);
3621     if (channel != NULL)
3622     {
3623 	if (part == PART_COUNT)
3624 	    part = channel_part_read(channel);
3625 	mode = channel_get_mode(channel, part);
3626 	timeout = channel_get_timeout(channel, part);
3627 	if (opt.jo_set & JO_TIMEOUT)
3628 	    timeout = opt.jo_timeout;
3629 
3630 	if (blob)
3631 	{
3632 	    int	    outlen = 0;
3633 	    char_u  *p = channel_read_block(channel, part,
3634 						       timeout, TRUE, &outlen);
3635 	    if (p != NULL)
3636 	    {
3637 		blob_T	*b = blob_alloc();
3638 
3639 		if (b != NULL)
3640 		{
3641 		    b->bv_ga.ga_len = outlen;
3642 		    if (ga_grow(&b->bv_ga, outlen) == FAIL)
3643 			blob_free(b);
3644 		    else
3645 		    {
3646 			memcpy(b->bv_ga.ga_data, p, outlen);
3647 			rettv_blob_set(rettv, b);
3648 		    }
3649 		}
3650 		vim_free(p);
3651 	    }
3652 	}
3653 	else if (raw || mode == MODE_RAW || mode == MODE_NL)
3654 	    rettv->vval.v_string = channel_read_block(channel, part,
3655 							 timeout, raw, NULL);
3656 	else
3657 	{
3658 	    if (opt.jo_set & JO_ID)
3659 		id = opt.jo_id;
3660 	    channel_read_json_block(channel, part, timeout, id, &listtv);
3661 	    if (listtv != NULL)
3662 	    {
3663 		*rettv = *listtv;
3664 		vim_free(listtv);
3665 	    }
3666 	    else
3667 	    {
3668 		rettv->v_type = VAR_SPECIAL;
3669 		rettv->vval.v_number = VVAL_NONE;
3670 	    }
3671 	}
3672     }
3673 
3674 theend:
3675     free_job_options(&opt);
3676 }
3677 
3678 # if defined(WIN32) || defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK) \
3679 	|| defined(PROTO)
3680 /*
3681  * Lookup the channel from the socket.  Set "partp" to the fd index.
3682  * Returns NULL when the socket isn't found.
3683  */
3684     channel_T *
3685 channel_fd2channel(sock_T fd, ch_part_T *partp)
3686 {
3687     channel_T	*channel;
3688     ch_part_T	part;
3689 
3690     if (fd != INVALID_FD)
3691 	for (channel = first_channel; channel != NULL;
3692 						   channel = channel->ch_next)
3693 	{
3694 	    for (part = PART_SOCK; part < PART_IN; ++part)
3695 		if (channel->ch_part[part].ch_fd == fd)
3696 		{
3697 		    *partp = part;
3698 		    return channel;
3699 		}
3700 	}
3701     return NULL;
3702 }
3703 # endif
3704 
3705 # if defined(WIN32) || defined(FEAT_GUI) || defined(PROTO)
3706 /*
3707  * Check the channels for anything that is ready to be read.
3708  * The data is put in the read queue.
3709  * if "only_keep_open" is TRUE only check channels where ch_keep_open is set.
3710  */
3711     void
3712 channel_handle_events(int only_keep_open)
3713 {
3714     channel_T	*channel;
3715     ch_part_T	part;
3716     sock_T	fd;
3717 
3718     for (channel = first_channel; channel != NULL; channel = channel->ch_next)
3719     {
3720 	if (only_keep_open && !channel->ch_keep_open)
3721 	    continue;
3722 
3723 	/* check the socket and pipes */
3724 	for (part = PART_SOCK; part < PART_IN; ++part)
3725 	{
3726 	    fd = channel->ch_part[part].ch_fd;
3727 	    if (fd != INVALID_FD)
3728 	    {
3729 		int r = channel_wait(channel, fd, 0);
3730 
3731 		if (r == CW_READY)
3732 		    channel_read(channel, part, "channel_handle_events");
3733 		else if (r == CW_ERROR)
3734 		    ch_close_part_on_error(channel, part, TRUE,
3735 						     "channel_handle_events");
3736 	    }
3737 	}
3738     }
3739 }
3740 # endif
3741 
3742 # if defined(FEAT_GUI) || defined(PROTO)
3743 /*
3744  * Return TRUE when there is any channel with a keep_open flag.
3745  */
3746     int
3747 channel_any_keep_open()
3748 {
3749     channel_T	*channel;
3750 
3751     for (channel = first_channel; channel != NULL; channel = channel->ch_next)
3752 	if (channel->ch_keep_open)
3753 	    return TRUE;
3754     return FALSE;
3755 }
3756 # endif
3757 
3758 /*
3759  * Set "channel"/"part" to non-blocking.
3760  * Only works for sockets and pipes.
3761  */
3762     void
3763 channel_set_nonblock(channel_T *channel, ch_part_T part)
3764 {
3765     chanpart_T *ch_part = &channel->ch_part[part];
3766     int		fd = ch_part->ch_fd;
3767 
3768     if (fd != INVALID_FD)
3769     {
3770 #ifdef _WIN32
3771 	u_long	val = 1;
3772 
3773 	ioctlsocket(fd, FIONBIO, &val);
3774 #else
3775 	(void)fcntl(fd, F_SETFL, O_NONBLOCK);
3776 #endif
3777 	ch_part->ch_nonblocking = TRUE;
3778     }
3779 }
3780 
3781 /*
3782  * Write "buf" (NUL terminated string) to "channel"/"part".
3783  * When "fun" is not NULL an error message might be given.
3784  * Return FAIL or OK.
3785  */
3786     int
3787 channel_send(
3788 	channel_T *channel,
3789 	ch_part_T part,
3790 	char_u	  *buf_arg,
3791 	int	  len_arg,
3792 	char	  *fun)
3793 {
3794     int		res;
3795     sock_T	fd;
3796     chanpart_T	*ch_part = &channel->ch_part[part];
3797     int		did_use_queue = FALSE;
3798 
3799     fd = ch_part->ch_fd;
3800     if (fd == INVALID_FD)
3801     {
3802 	if (!channel->ch_error && fun != NULL)
3803 	{
3804 	    ch_error(channel, "%s(): write while not connected", fun);
3805 	    semsg(_("E630: %s(): write while not connected"), fun);
3806 	}
3807 	channel->ch_error = TRUE;
3808 	return FAIL;
3809     }
3810 
3811     if (channel->ch_nonblock && !ch_part->ch_nonblocking)
3812 	channel_set_nonblock(channel, part);
3813 
3814     if (ch_log_active())
3815     {
3816 	ch_log_lead("SEND ", channel, part);
3817 	fprintf(log_fd, "'");
3818 	vim_ignored = (int)fwrite(buf_arg, len_arg, 1, log_fd);
3819 	fprintf(log_fd, "'\n");
3820 	fflush(log_fd);
3821 	did_log_msg = TRUE;
3822     }
3823 
3824     for (;;)
3825     {
3826 	writeq_T    *wq = &ch_part->ch_writeque;
3827 	char_u	    *buf;
3828 	int	    len;
3829 
3830 	if (wq->wq_next != NULL)
3831 	{
3832 	    /* first write what was queued */
3833 	    buf = wq->wq_next->wq_ga.ga_data;
3834 	    len = wq->wq_next->wq_ga.ga_len;
3835 	    did_use_queue = TRUE;
3836 	}
3837 	else
3838 	{
3839 	    if (len_arg == 0)
3840 		/* nothing to write, called from channel_select_check() */
3841 		return OK;
3842 	    buf = buf_arg;
3843 	    len = len_arg;
3844 	}
3845 
3846 	if (part == PART_SOCK)
3847 	    res = sock_write(fd, (char *)buf, len);
3848 	else
3849 	{
3850 	    res = fd_write(fd, (char *)buf, len);
3851 #ifdef WIN32
3852 	    if (channel->ch_named_pipe && res < 0)
3853 	    {
3854 		DisconnectNamedPipe((HANDLE)fd);
3855 		ConnectNamedPipe((HANDLE)fd, NULL);
3856 	    }
3857 #endif
3858 	}
3859 	if (res < 0 && (errno == EWOULDBLOCK
3860 #ifdef EAGAIN
3861 			|| errno == EAGAIN
3862 #endif
3863 		    ))
3864 	    res = 0; /* nothing got written */
3865 
3866 	if (res >= 0 && ch_part->ch_nonblocking)
3867 	{
3868 	    writeq_T *entry = wq->wq_next;
3869 
3870 	    if (did_use_queue)
3871 		ch_log(channel, "Sent %d bytes now", res);
3872 	    if (res == len)
3873 	    {
3874 		/* Wrote all the buf[len] bytes. */
3875 		if (entry != NULL)
3876 		{
3877 		    /* Remove the entry from the write queue. */
3878 		    remove_from_writeque(wq, entry);
3879 		    continue;
3880 		}
3881 		if (did_use_queue)
3882 		    ch_log(channel, "Write queue empty");
3883 	    }
3884 	    else
3885 	    {
3886 		/* Wrote only buf[res] bytes, can't write more now. */
3887 		if (entry != NULL)
3888 		{
3889 		    if (res > 0)
3890 		    {
3891 			/* Remove the bytes that were written. */
3892 			mch_memmove(entry->wq_ga.ga_data,
3893 				    (char *)entry->wq_ga.ga_data + res,
3894 				    len - res);
3895 			entry->wq_ga.ga_len -= res;
3896 		    }
3897 		    buf = buf_arg;
3898 		    len = len_arg;
3899 		}
3900 		else
3901 		{
3902 		    buf += res;
3903 		    len -= res;
3904 		}
3905 		ch_log(channel, "Adding %d bytes to the write queue", len);
3906 
3907 		/* Append the not written bytes of the argument to the write
3908 		 * buffer.  Limit entries to 4000 bytes. */
3909 		if (wq->wq_prev != NULL
3910 			&& wq->wq_prev->wq_ga.ga_len + len < 4000)
3911 		{
3912 		    writeq_T *last = wq->wq_prev;
3913 
3914 		    /* append to the last entry */
3915 		    if (ga_grow(&last->wq_ga, len) == OK)
3916 		    {
3917 			mch_memmove((char *)last->wq_ga.ga_data
3918 							  + last->wq_ga.ga_len,
3919 				    buf, len);
3920 			last->wq_ga.ga_len += len;
3921 		    }
3922 		}
3923 		else
3924 		{
3925 		    writeq_T *last = (writeq_T *)alloc((int)sizeof(writeq_T));
3926 
3927 		    if (last != NULL)
3928 		    {
3929 			last->wq_prev = wq->wq_prev;
3930 			last->wq_next = NULL;
3931 			if (wq->wq_prev == NULL)
3932 			    wq->wq_next = last;
3933 			else
3934 			    wq->wq_prev->wq_next = last;
3935 			wq->wq_prev = last;
3936 			ga_init2(&last->wq_ga, 1, 1000);
3937 			if (ga_grow(&last->wq_ga, len) == OK)
3938 			{
3939 			    mch_memmove(last->wq_ga.ga_data, buf, len);
3940 			    last->wq_ga.ga_len = len;
3941 			}
3942 		    }
3943 		}
3944 	    }
3945 	}
3946 	else if (res != len)
3947 	{
3948 	    if (!channel->ch_error && fun != NULL)
3949 	    {
3950 		ch_error(channel, "%s(): write failed", fun);
3951 		semsg(_("E631: %s(): write failed"), fun);
3952 	    }
3953 	    channel->ch_error = TRUE;
3954 	    return FAIL;
3955 	}
3956 
3957 	channel->ch_error = FALSE;
3958 	return OK;
3959     }
3960 }
3961 
3962 /*
3963  * Common for "ch_sendexpr()" and "ch_sendraw()".
3964  * Returns the channel if the caller should read the response.
3965  * Sets "part_read" to the read fd.
3966  * Otherwise returns NULL.
3967  */
3968     static channel_T *
3969 send_common(
3970 	typval_T    *argvars,
3971 	char_u	    *text,
3972 	int	    len,
3973 	int	    id,
3974 	int	    eval,
3975 	jobopt_T    *opt,
3976 	char	    *fun,
3977 	ch_part_T   *part_read)
3978 {
3979     channel_T	*channel;
3980     ch_part_T	part_send;
3981 
3982     clear_job_options(opt);
3983     channel = get_channel_arg(&argvars[0], TRUE, FALSE, 0);
3984     if (channel == NULL)
3985 	return NULL;
3986     part_send = channel_part_send(channel);
3987     *part_read = channel_part_read(channel);
3988 
3989     if (get_job_options(&argvars[2], opt, JO_CALLBACK + JO_TIMEOUT, 0) == FAIL)
3990 	return NULL;
3991 
3992     /* Set the callback. An empty callback means no callback and not reading
3993      * the response. With "ch_evalexpr()" and "ch_evalraw()" a callback is not
3994      * allowed. */
3995     if (opt->jo_callback != NULL && *opt->jo_callback != NUL)
3996     {
3997 	if (eval)
3998 	{
3999 	    semsg(_("E917: Cannot use a callback with %s()"), fun);
4000 	    return NULL;
4001 	}
4002 	channel_set_req_callback(channel, *part_read,
4003 				       opt->jo_callback, opt->jo_partial, id);
4004     }
4005 
4006     if (channel_send(channel, part_send, text, len, fun) == OK
4007 						  && opt->jo_callback == NULL)
4008 	return channel;
4009     return NULL;
4010 }
4011 
4012 /*
4013  * common for "ch_evalexpr()" and "ch_sendexpr()"
4014  */
4015     void
4016 ch_expr_common(typval_T *argvars, typval_T *rettv, int eval)
4017 {
4018     char_u	*text;
4019     typval_T	*listtv;
4020     channel_T	*channel;
4021     int		id;
4022     ch_mode_T	ch_mode;
4023     ch_part_T	part_send;
4024     ch_part_T	part_read;
4025     jobopt_T    opt;
4026     int		timeout;
4027 
4028     /* return an empty string by default */
4029     rettv->v_type = VAR_STRING;
4030     rettv->vval.v_string = NULL;
4031 
4032     channel = get_channel_arg(&argvars[0], TRUE, FALSE, 0);
4033     if (channel == NULL)
4034 	return;
4035     part_send = channel_part_send(channel);
4036 
4037     ch_mode = channel_get_mode(channel, part_send);
4038     if (ch_mode == MODE_RAW || ch_mode == MODE_NL)
4039     {
4040 	emsg(_("E912: cannot use ch_evalexpr()/ch_sendexpr() with a raw or nl channel"));
4041 	return;
4042     }
4043 
4044     id = ++channel->ch_last_msg_id;
4045     text = json_encode_nr_expr(id, &argvars[1],
4046 				 (ch_mode == MODE_JS ? JSON_JS : 0) | JSON_NL);
4047     if (text == NULL)
4048 	return;
4049 
4050     channel = send_common(argvars, text, (int)STRLEN(text), id, eval, &opt,
4051 			    eval ? "ch_evalexpr" : "ch_sendexpr", &part_read);
4052     vim_free(text);
4053     if (channel != NULL && eval)
4054     {
4055 	if (opt.jo_set & JO_TIMEOUT)
4056 	    timeout = opt.jo_timeout;
4057 	else
4058 	    timeout = channel_get_timeout(channel, part_read);
4059 	if (channel_read_json_block(channel, part_read, timeout, id, &listtv)
4060 									== OK)
4061 	{
4062 	    list_T *list = listtv->vval.v_list;
4063 
4064 	    /* Move the item from the list and then change the type to
4065 	     * avoid the value being freed. */
4066 	    *rettv = list->lv_last->li_tv;
4067 	    list->lv_last->li_tv.v_type = VAR_NUMBER;
4068 	    free_tv(listtv);
4069 	}
4070     }
4071     free_job_options(&opt);
4072 }
4073 
4074 /*
4075  * common for "ch_evalraw()" and "ch_sendraw()"
4076  */
4077     void
4078 ch_raw_common(typval_T *argvars, typval_T *rettv, int eval)
4079 {
4080     char_u	buf[NUMBUFLEN];
4081     char_u	*text;
4082     int		len;
4083     channel_T	*channel;
4084     ch_part_T	part_read;
4085     jobopt_T    opt;
4086     int		timeout;
4087 
4088     /* return an empty string by default */
4089     rettv->v_type = VAR_STRING;
4090     rettv->vval.v_string = NULL;
4091 
4092     if (argvars[1].v_type == VAR_BLOB)
4093     {
4094 	text = argvars[1].vval.v_blob->bv_ga.ga_data;
4095 	len = argvars[1].vval.v_blob->bv_ga.ga_len;
4096     }
4097     else
4098     {
4099 	text = tv_get_string_buf(&argvars[1], buf);
4100 	len = (int)STRLEN(text);
4101     }
4102     channel = send_common(argvars, text, len, 0, eval, &opt,
4103 			      eval ? "ch_evalraw" : "ch_sendraw", &part_read);
4104     if (channel != NULL && eval)
4105     {
4106 	if (opt.jo_set & JO_TIMEOUT)
4107 	    timeout = opt.jo_timeout;
4108 	else
4109 	    timeout = channel_get_timeout(channel, part_read);
4110 	rettv->vval.v_string = channel_read_block(channel, part_read,
4111 							timeout, TRUE, NULL);
4112     }
4113     free_job_options(&opt);
4114 }
4115 
4116 # define KEEP_OPEN_TIME 20  /* msec */
4117 
4118 # if (defined(UNIX) && !defined(HAVE_SELECT)) || defined(PROTO)
4119 /*
4120  * Add open channels to the poll struct.
4121  * Return the adjusted struct index.
4122  * The type of "fds" is hidden to avoid problems with the function proto.
4123  */
4124     int
4125 channel_poll_setup(int nfd_in, void *fds_in, int *towait)
4126 {
4127     int		nfd = nfd_in;
4128     channel_T	*channel;
4129     struct	pollfd *fds = fds_in;
4130     ch_part_T	part;
4131 
4132     for (channel = first_channel; channel != NULL; channel = channel->ch_next)
4133     {
4134 	for (part = PART_SOCK; part < PART_IN; ++part)
4135 	{
4136 	    chanpart_T	*ch_part = &channel->ch_part[part];
4137 
4138 	    if (ch_part->ch_fd != INVALID_FD)
4139 	    {
4140 		if (channel->ch_keep_open)
4141 		{
4142 		    /* For unknown reason poll() returns immediately for a
4143 		     * keep-open channel.  Instead of adding it to the fds add
4144 		     * a short timeout and check, like polling. */
4145 		    if (*towait < 0 || *towait > KEEP_OPEN_TIME)
4146 			*towait = KEEP_OPEN_TIME;
4147 		}
4148 		else
4149 		{
4150 		    ch_part->ch_poll_idx = nfd;
4151 		    fds[nfd].fd = ch_part->ch_fd;
4152 		    fds[nfd].events = POLLIN;
4153 		    nfd++;
4154 		}
4155 	    }
4156 	    else
4157 		channel->ch_part[part].ch_poll_idx = -1;
4158 	}
4159     }
4160 
4161     nfd = channel_fill_poll_write(nfd, fds);
4162 
4163     return nfd;
4164 }
4165 
4166 /*
4167  * The type of "fds" is hidden to avoid problems with the function proto.
4168  */
4169     int
4170 channel_poll_check(int ret_in, void *fds_in)
4171 {
4172     int		ret = ret_in;
4173     channel_T	*channel;
4174     struct	pollfd *fds = fds_in;
4175     ch_part_T	part;
4176     int		idx;
4177     chanpart_T	*in_part;
4178 
4179     for (channel = first_channel; channel != NULL; channel = channel->ch_next)
4180     {
4181 	for (part = PART_SOCK; part < PART_IN; ++part)
4182 	{
4183 	    idx = channel->ch_part[part].ch_poll_idx;
4184 
4185 	    if (ret > 0 && idx != -1 && (fds[idx].revents & POLLIN))
4186 	    {
4187 		channel_read(channel, part, "channel_poll_check");
4188 		--ret;
4189 	    }
4190 	    else if (channel->ch_part[part].ch_fd != INVALID_FD
4191 						      && channel->ch_keep_open)
4192 	    {
4193 		/* polling a keep-open channel */
4194 		channel_read(channel, part, "channel_poll_check_keep_open");
4195 	    }
4196 	}
4197 
4198 	in_part = &channel->ch_part[PART_IN];
4199 	idx = in_part->ch_poll_idx;
4200 	if (ret > 0 && idx != -1 && (fds[idx].revents & POLLOUT))
4201 	{
4202 	    channel_write_input(channel);
4203 	    --ret;
4204 	}
4205     }
4206 
4207     return ret;
4208 }
4209 # endif /* UNIX && !HAVE_SELECT */
4210 
4211 # if (!defined(WIN32) && defined(HAVE_SELECT)) || defined(PROTO)
4212 
4213 /*
4214  * The "fd_set" type is hidden to avoid problems with the function proto.
4215  */
4216     int
4217 channel_select_setup(
4218 	int maxfd_in,
4219 	void *rfds_in,
4220 	void *wfds_in,
4221 	struct timeval *tv,
4222 	struct timeval **tvp)
4223 {
4224     int		maxfd = maxfd_in;
4225     channel_T	*channel;
4226     fd_set	*rfds = rfds_in;
4227     fd_set	*wfds = wfds_in;
4228     ch_part_T	part;
4229 
4230     for (channel = first_channel; channel != NULL; channel = channel->ch_next)
4231     {
4232 	for (part = PART_SOCK; part < PART_IN; ++part)
4233 	{
4234 	    sock_T fd = channel->ch_part[part].ch_fd;
4235 
4236 	    if (fd != INVALID_FD)
4237 	    {
4238 		if (channel->ch_keep_open)
4239 		{
4240 		    /* For unknown reason select() returns immediately for a
4241 		     * keep-open channel.  Instead of adding it to the rfds add
4242 		     * a short timeout and check, like polling. */
4243 		    if (*tvp == NULL || tv->tv_sec > 0
4244 					|| tv->tv_usec > KEEP_OPEN_TIME * 1000)
4245 		    {
4246 			*tvp = tv;
4247 			tv->tv_sec = 0;
4248 			tv->tv_usec = KEEP_OPEN_TIME * 1000;
4249 		    }
4250 		}
4251 		else
4252 		{
4253 		    FD_SET((int)fd, rfds);
4254 		    if (maxfd < (int)fd)
4255 			maxfd = (int)fd;
4256 		}
4257 	    }
4258 	}
4259     }
4260 
4261     maxfd = channel_fill_wfds(maxfd, wfds);
4262 
4263     return maxfd;
4264 }
4265 
4266 /*
4267  * The "fd_set" type is hidden to avoid problems with the function proto.
4268  */
4269     int
4270 channel_select_check(int ret_in, void *rfds_in, void *wfds_in)
4271 {
4272     int		ret = ret_in;
4273     channel_T	*channel;
4274     fd_set	*rfds = rfds_in;
4275     fd_set	*wfds = wfds_in;
4276     ch_part_T	part;
4277     chanpart_T	*in_part;
4278 
4279     for (channel = first_channel; channel != NULL; channel = channel->ch_next)
4280     {
4281 	for (part = PART_SOCK; part < PART_IN; ++part)
4282 	{
4283 	    sock_T fd = channel->ch_part[part].ch_fd;
4284 
4285 	    if (ret > 0 && fd != INVALID_FD && FD_ISSET(fd, rfds))
4286 	    {
4287 		channel_read(channel, part, "channel_select_check");
4288 		FD_CLR(fd, rfds);
4289 		--ret;
4290 	    }
4291 	    else if (fd != INVALID_FD && channel->ch_keep_open)
4292 	    {
4293 		/* polling a keep-open channel */
4294 		channel_read(channel, part, "channel_select_check_keep_open");
4295 	    }
4296 	}
4297 
4298 	in_part = &channel->ch_part[PART_IN];
4299 	if (ret > 0 && in_part->ch_fd != INVALID_FD
4300 					    && FD_ISSET(in_part->ch_fd, wfds))
4301 	{
4302 	    /* Clear the flag first, ch_fd may change in channel_write_input(). */
4303 	    FD_CLR(in_part->ch_fd, wfds);
4304 	    channel_write_input(channel);
4305 	    --ret;
4306 	}
4307     }
4308 
4309     return ret;
4310 }
4311 # endif /* !WIN32 && HAVE_SELECT */
4312 
4313 /*
4314  * Execute queued up commands.
4315  * Invoked from the main loop when it's safe to execute received commands.
4316  * Return TRUE when something was done.
4317  */
4318     int
4319 channel_parse_messages(void)
4320 {
4321     channel_T	*channel = first_channel;
4322     int		ret = FALSE;
4323     int		r;
4324     ch_part_T	part = PART_SOCK;
4325 #ifdef ELAPSED_FUNC
4326     elapsed_T	start_tv;
4327 
4328     ELAPSED_INIT(start_tv);
4329 #endif
4330 
4331     ++safe_to_invoke_callback;
4332 
4333     /* Only do this message when another message was given, otherwise we get
4334      * lots of them. */
4335     if (did_log_msg)
4336     {
4337 	ch_log(NULL, "looking for messages on channels");
4338 	did_log_msg = FALSE;
4339     }
4340     while (channel != NULL)
4341     {
4342 	if (channel_can_close(channel))
4343 	{
4344 	    channel->ch_to_be_closed = (1U << PART_COUNT);
4345 	    channel_close_now(channel);
4346 	    /* channel may have been freed, start over */
4347 	    channel = first_channel;
4348 	    continue;
4349 	}
4350 	if (channel->ch_to_be_freed || channel->ch_killing)
4351 	{
4352 	    channel_free(channel);
4353 	    /* channel has been freed, start over */
4354 	    channel = first_channel;
4355 	    continue;
4356 	}
4357 	if (channel->ch_refcount == 0 && !channel_still_useful(channel))
4358 	{
4359 	    /* channel is no longer useful, free it */
4360 	    channel_free(channel);
4361 	    channel = first_channel;
4362 	    part = PART_SOCK;
4363 	    continue;
4364 	}
4365 	if (channel->ch_part[part].ch_fd != INVALID_FD
4366 				      || channel_has_readahead(channel, part))
4367 	{
4368 	    /* Increase the refcount, in case the handler causes the channel
4369 	     * to be unreferenced or closed. */
4370 	    ++channel->ch_refcount;
4371 	    r = may_invoke_callback(channel, part);
4372 	    if (r == OK)
4373 		ret = TRUE;
4374 	    if (channel_unref(channel) || (r == OK
4375 #ifdef ELAPSED_FUNC
4376 			/* Limit the time we loop here to 100 msec, otherwise
4377 			 * Vim becomes unresponsive when the callback takes
4378 			 * more than a bit of time. */
4379 			&& ELAPSED_FUNC(start_tv) < 100L
4380 #endif
4381 			))
4382 	    {
4383 		/* channel was freed or something was done, start over */
4384 		channel = first_channel;
4385 		part = PART_SOCK;
4386 		continue;
4387 	    }
4388 	}
4389 	if (part < PART_ERR)
4390 	    ++part;
4391 	else
4392 	{
4393 	    channel = channel->ch_next;
4394 	    part = PART_SOCK;
4395 	}
4396     }
4397 
4398     if (channel_need_redraw)
4399     {
4400 	channel_need_redraw = FALSE;
4401 	redraw_after_callback(TRUE);
4402     }
4403 
4404     --safe_to_invoke_callback;
4405 
4406     return ret;
4407 }
4408 
4409 /*
4410  * Return TRUE if any channel has readahead.  That means we should not block on
4411  * waiting for input.
4412  */
4413     int
4414 channel_any_readahead(void)
4415 {
4416     channel_T	*channel = first_channel;
4417     ch_part_T	part = PART_SOCK;
4418 
4419     while (channel != NULL)
4420     {
4421 	if (channel_has_readahead(channel, part))
4422 	    return TRUE;
4423 	if (part < PART_ERR)
4424 	    ++part;
4425 	else
4426 	{
4427 	    channel = channel->ch_next;
4428 	    part = PART_SOCK;
4429 	}
4430     }
4431     return FALSE;
4432 }
4433 
4434 /*
4435  * Mark references to lists used in channels.
4436  */
4437     int
4438 set_ref_in_channel(int copyID)
4439 {
4440     int		abort = FALSE;
4441     channel_T	*channel;
4442     typval_T	tv;
4443 
4444     for (channel = first_channel; channel != NULL; channel = channel->ch_next)
4445 	if (channel_still_useful(channel))
4446 	{
4447 	    tv.v_type = VAR_CHANNEL;
4448 	    tv.vval.v_channel = channel;
4449 	    abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4450 	}
4451     return abort;
4452 }
4453 
4454 /*
4455  * Return the "part" to write to for "channel".
4456  */
4457     ch_part_T
4458 channel_part_send(channel_T *channel)
4459 {
4460     if (channel->CH_SOCK_FD == INVALID_FD)
4461 	return PART_IN;
4462     return PART_SOCK;
4463 }
4464 
4465 /*
4466  * Return the default "part" to read from for "channel".
4467  */
4468     ch_part_T
4469 channel_part_read(channel_T *channel)
4470 {
4471     if (channel->CH_SOCK_FD == INVALID_FD)
4472 	return PART_OUT;
4473     return PART_SOCK;
4474 }
4475 
4476 /*
4477  * Return the mode of "channel"/"part"
4478  * If "channel" is invalid returns MODE_JSON.
4479  */
4480     ch_mode_T
4481 channel_get_mode(channel_T *channel, ch_part_T part)
4482 {
4483     if (channel == NULL)
4484 	return MODE_JSON;
4485     return channel->ch_part[part].ch_mode;
4486 }
4487 
4488 /*
4489  * Return the timeout of "channel"/"part"
4490  */
4491     int
4492 channel_get_timeout(channel_T *channel, ch_part_T part)
4493 {
4494     return channel->ch_part[part].ch_timeout;
4495 }
4496 
4497     static int
4498 handle_mode(typval_T *item, jobopt_T *opt, ch_mode_T *modep, int jo)
4499 {
4500     char_u	*val = tv_get_string(item);
4501 
4502     opt->jo_set |= jo;
4503     if (STRCMP(val, "nl") == 0)
4504 	*modep = MODE_NL;
4505     else if (STRCMP(val, "raw") == 0)
4506 	*modep = MODE_RAW;
4507     else if (STRCMP(val, "js") == 0)
4508 	*modep = MODE_JS;
4509     else if (STRCMP(val, "json") == 0)
4510 	*modep = MODE_JSON;
4511     else
4512     {
4513 	semsg(_(e_invarg2), val);
4514 	return FAIL;
4515     }
4516     return OK;
4517 }
4518 
4519     static int
4520 handle_io(typval_T *item, ch_part_T part, jobopt_T *opt)
4521 {
4522     char_u	*val = tv_get_string(item);
4523 
4524     opt->jo_set |= JO_OUT_IO << (part - PART_OUT);
4525     if (STRCMP(val, "null") == 0)
4526 	opt->jo_io[part] = JIO_NULL;
4527     else if (STRCMP(val, "pipe") == 0)
4528 	opt->jo_io[part] = JIO_PIPE;
4529     else if (STRCMP(val, "file") == 0)
4530 	opt->jo_io[part] = JIO_FILE;
4531     else if (STRCMP(val, "buffer") == 0)
4532 	opt->jo_io[part] = JIO_BUFFER;
4533     else if (STRCMP(val, "out") == 0 && part == PART_ERR)
4534 	opt->jo_io[part] = JIO_OUT;
4535     else
4536     {
4537 	semsg(_(e_invarg2), val);
4538 	return FAIL;
4539     }
4540     return OK;
4541 }
4542 
4543 /*
4544  * Clear a jobopt_T before using it.
4545  */
4546     void
4547 clear_job_options(jobopt_T *opt)
4548 {
4549     vim_memset(opt, 0, sizeof(jobopt_T));
4550 }
4551 
4552 /*
4553  * Free any members of a jobopt_T.
4554  */
4555     void
4556 free_job_options(jobopt_T *opt)
4557 {
4558     if (opt->jo_partial != NULL)
4559 	partial_unref(opt->jo_partial);
4560     else if (opt->jo_callback != NULL)
4561 	func_unref(opt->jo_callback);
4562     if (opt->jo_out_partial != NULL)
4563 	partial_unref(opt->jo_out_partial);
4564     else if (opt->jo_out_cb != NULL)
4565 	func_unref(opt->jo_out_cb);
4566     if (opt->jo_err_partial != NULL)
4567 	partial_unref(opt->jo_err_partial);
4568     else if (opt->jo_err_cb != NULL)
4569 	func_unref(opt->jo_err_cb);
4570     if (opt->jo_close_partial != NULL)
4571 	partial_unref(opt->jo_close_partial);
4572     else if (opt->jo_close_cb != NULL)
4573 	func_unref(opt->jo_close_cb);
4574     if (opt->jo_exit_partial != NULL)
4575 	partial_unref(opt->jo_exit_partial);
4576     else if (opt->jo_exit_cb != NULL)
4577 	func_unref(opt->jo_exit_cb);
4578     if (opt->jo_env != NULL)
4579 	dict_unref(opt->jo_env);
4580 }
4581 
4582 /*
4583  * Get the PART_ number from the first character of an option name.
4584  */
4585     static int
4586 part_from_char(int c)
4587 {
4588     return c == 'i' ? PART_IN : c == 'o' ? PART_OUT: PART_ERR;
4589 }
4590 
4591 /*
4592  * Get the option entries from the dict in "tv", parse them and put the result
4593  * in "opt".
4594  * Only accept JO_ options in "supported" and JO2_ options in "supported2".
4595  * If an option value is invalid return FAIL.
4596  */
4597     int
4598 get_job_options(typval_T *tv, jobopt_T *opt, int supported, int supported2)
4599 {
4600     typval_T	*item;
4601     char_u	*val;
4602     dict_T	*dict;
4603     int		todo;
4604     hashitem_T	*hi;
4605     ch_part_T	part;
4606 
4607     if (tv->v_type == VAR_UNKNOWN)
4608 	return OK;
4609     if (tv->v_type != VAR_DICT)
4610     {
4611 	emsg(_(e_dictreq));
4612 	return FAIL;
4613     }
4614     dict = tv->vval.v_dict;
4615     if (dict == NULL)
4616 	return OK;
4617 
4618     todo = (int)dict->dv_hashtab.ht_used;
4619     for (hi = dict->dv_hashtab.ht_array; todo > 0; ++hi)
4620 	if (!HASHITEM_EMPTY(hi))
4621 	{
4622 	    item = &dict_lookup(hi)->di_tv;
4623 
4624 	    if (STRCMP(hi->hi_key, "mode") == 0)
4625 	    {
4626 		if (!(supported & JO_MODE))
4627 		    break;
4628 		if (handle_mode(item, opt, &opt->jo_mode, JO_MODE) == FAIL)
4629 		    return FAIL;
4630 	    }
4631 	    else if (STRCMP(hi->hi_key, "in_mode") == 0)
4632 	    {
4633 		if (!(supported & JO_IN_MODE))
4634 		    break;
4635 		if (handle_mode(item, opt, &opt->jo_in_mode, JO_IN_MODE)
4636 								      == FAIL)
4637 		    return FAIL;
4638 	    }
4639 	    else if (STRCMP(hi->hi_key, "out_mode") == 0)
4640 	    {
4641 		if (!(supported & JO_OUT_MODE))
4642 		    break;
4643 		if (handle_mode(item, opt, &opt->jo_out_mode, JO_OUT_MODE)
4644 								      == FAIL)
4645 		    return FAIL;
4646 	    }
4647 	    else if (STRCMP(hi->hi_key, "err_mode") == 0)
4648 	    {
4649 		if (!(supported & JO_ERR_MODE))
4650 		    break;
4651 		if (handle_mode(item, opt, &opt->jo_err_mode, JO_ERR_MODE)
4652 								      == FAIL)
4653 		    return FAIL;
4654 	    }
4655 	    else if (STRCMP(hi->hi_key, "noblock") == 0)
4656 	    {
4657 		if (!(supported & JO_MODE))
4658 		    break;
4659 		opt->jo_noblock = tv_get_number(item);
4660 	    }
4661 	    else if (STRCMP(hi->hi_key, "in_io") == 0
4662 		    || STRCMP(hi->hi_key, "out_io") == 0
4663 		    || STRCMP(hi->hi_key, "err_io") == 0)
4664 	    {
4665 		if (!(supported & JO_OUT_IO))
4666 		    break;
4667 		if (handle_io(item, part_from_char(*hi->hi_key), opt) == FAIL)
4668 		    return FAIL;
4669 	    }
4670 	    else if (STRCMP(hi->hi_key, "in_name") == 0
4671 		    || STRCMP(hi->hi_key, "out_name") == 0
4672 		    || STRCMP(hi->hi_key, "err_name") == 0)
4673 	    {
4674 		part = part_from_char(*hi->hi_key);
4675 
4676 		if (!(supported & JO_OUT_IO))
4677 		    break;
4678 		opt->jo_set |= JO_OUT_NAME << (part - PART_OUT);
4679 		opt->jo_io_name[part] =
4680 		       tv_get_string_buf_chk(item, opt->jo_io_name_buf[part]);
4681 	    }
4682 	    else if (STRCMP(hi->hi_key, "pty") == 0)
4683 	    {
4684 		if (!(supported & JO_MODE))
4685 		    break;
4686 		opt->jo_pty = tv_get_number(item);
4687 	    }
4688 	    else if (STRCMP(hi->hi_key, "in_buf") == 0
4689 		    || STRCMP(hi->hi_key, "out_buf") == 0
4690 		    || STRCMP(hi->hi_key, "err_buf") == 0)
4691 	    {
4692 		part = part_from_char(*hi->hi_key);
4693 
4694 		if (!(supported & JO_OUT_IO))
4695 		    break;
4696 		opt->jo_set |= JO_OUT_BUF << (part - PART_OUT);
4697 		opt->jo_io_buf[part] = tv_get_number(item);
4698 		if (opt->jo_io_buf[part] <= 0)
4699 		{
4700 		    semsg(_(e_invargNval), hi->hi_key, tv_get_string(item));
4701 		    return FAIL;
4702 		}
4703 		if (buflist_findnr(opt->jo_io_buf[part]) == NULL)
4704 		{
4705 		    semsg(_(e_nobufnr), (long)opt->jo_io_buf[part]);
4706 		    return FAIL;
4707 		}
4708 	    }
4709 	    else if (STRCMP(hi->hi_key, "out_modifiable") == 0
4710 		    || STRCMP(hi->hi_key, "err_modifiable") == 0)
4711 	    {
4712 		part = part_from_char(*hi->hi_key);
4713 
4714 		if (!(supported & JO_OUT_IO))
4715 		    break;
4716 		opt->jo_set |= JO_OUT_MODIFIABLE << (part - PART_OUT);
4717 		opt->jo_modifiable[part] = tv_get_number(item);
4718 	    }
4719 	    else if (STRCMP(hi->hi_key, "out_msg") == 0
4720 		    || STRCMP(hi->hi_key, "err_msg") == 0)
4721 	    {
4722 		part = part_from_char(*hi->hi_key);
4723 
4724 		if (!(supported & JO_OUT_IO))
4725 		    break;
4726 		opt->jo_set2 |= JO2_OUT_MSG << (part - PART_OUT);
4727 		opt->jo_message[part] = tv_get_number(item);
4728 	    }
4729 	    else if (STRCMP(hi->hi_key, "in_top") == 0
4730 		    || STRCMP(hi->hi_key, "in_bot") == 0)
4731 	    {
4732 		linenr_T *lp;
4733 
4734 		if (!(supported & JO_OUT_IO))
4735 		    break;
4736 		if (hi->hi_key[3] == 't')
4737 		{
4738 		    lp = &opt->jo_in_top;
4739 		    opt->jo_set |= JO_IN_TOP;
4740 		}
4741 		else
4742 		{
4743 		    lp = &opt->jo_in_bot;
4744 		    opt->jo_set |= JO_IN_BOT;
4745 		}
4746 		*lp = tv_get_number(item);
4747 		if (*lp < 0)
4748 		{
4749 		    semsg(_(e_invargNval), hi->hi_key, tv_get_string(item));
4750 		    return FAIL;
4751 		}
4752 	    }
4753 	    else if (STRCMP(hi->hi_key, "channel") == 0)
4754 	    {
4755 		if (!(supported & JO_OUT_IO))
4756 		    break;
4757 		opt->jo_set |= JO_CHANNEL;
4758 		if (item->v_type != VAR_CHANNEL)
4759 		{
4760 		    semsg(_(e_invargval), "channel");
4761 		    return FAIL;
4762 		}
4763 		opt->jo_channel = item->vval.v_channel;
4764 	    }
4765 	    else if (STRCMP(hi->hi_key, "callback") == 0)
4766 	    {
4767 		if (!(supported & JO_CALLBACK))
4768 		    break;
4769 		opt->jo_set |= JO_CALLBACK;
4770 		opt->jo_callback = get_callback(item, &opt->jo_partial);
4771 		if (opt->jo_callback == NULL)
4772 		{
4773 		    semsg(_(e_invargval), "callback");
4774 		    return FAIL;
4775 		}
4776 	    }
4777 	    else if (STRCMP(hi->hi_key, "out_cb") == 0)
4778 	    {
4779 		if (!(supported & JO_OUT_CALLBACK))
4780 		    break;
4781 		opt->jo_set |= JO_OUT_CALLBACK;
4782 		opt->jo_out_cb = get_callback(item, &opt->jo_out_partial);
4783 		if (opt->jo_out_cb == NULL)
4784 		{
4785 		    semsg(_(e_invargval), "out_cb");
4786 		    return FAIL;
4787 		}
4788 	    }
4789 	    else if (STRCMP(hi->hi_key, "err_cb") == 0)
4790 	    {
4791 		if (!(supported & JO_ERR_CALLBACK))
4792 		    break;
4793 		opt->jo_set |= JO_ERR_CALLBACK;
4794 		opt->jo_err_cb = get_callback(item, &opt->jo_err_partial);
4795 		if (opt->jo_err_cb == NULL)
4796 		{
4797 		    semsg(_(e_invargval), "err_cb");
4798 		    return FAIL;
4799 		}
4800 	    }
4801 	    else if (STRCMP(hi->hi_key, "close_cb") == 0)
4802 	    {
4803 		if (!(supported & JO_CLOSE_CALLBACK))
4804 		    break;
4805 		opt->jo_set |= JO_CLOSE_CALLBACK;
4806 		opt->jo_close_cb = get_callback(item, &opt->jo_close_partial);
4807 		if (opt->jo_close_cb == NULL)
4808 		{
4809 		    semsg(_(e_invargval), "close_cb");
4810 		    return FAIL;
4811 		}
4812 	    }
4813 	    else if (STRCMP(hi->hi_key, "drop") == 0)
4814 	    {
4815 		int never = FALSE;
4816 		val = tv_get_string(item);
4817 
4818 		if (STRCMP(val, "never") == 0)
4819 		    never = TRUE;
4820 		else if (STRCMP(val, "auto") != 0)
4821 		{
4822 		    semsg(_(e_invargNval), "drop", val);
4823 		    return FAIL;
4824 		}
4825 		opt->jo_drop_never = never;
4826 	    }
4827 	    else if (STRCMP(hi->hi_key, "exit_cb") == 0)
4828 	    {
4829 		if (!(supported & JO_EXIT_CB))
4830 		    break;
4831 		opt->jo_set |= JO_EXIT_CB;
4832 		opt->jo_exit_cb = get_callback(item, &opt->jo_exit_partial);
4833 		if (opt->jo_exit_cb == NULL)
4834 		{
4835 		    semsg(_(e_invargval), "exit_cb");
4836 		    return FAIL;
4837 		}
4838 	    }
4839 #ifdef FEAT_TERMINAL
4840 	    else if (STRCMP(hi->hi_key, "term_name") == 0)
4841 	    {
4842 		if (!(supported2 & JO2_TERM_NAME))
4843 		    break;
4844 		opt->jo_set2 |= JO2_TERM_NAME;
4845 		opt->jo_term_name = tv_get_string_chk(item);
4846 		if (opt->jo_term_name == NULL)
4847 		{
4848 		    semsg(_(e_invargval), "term_name");
4849 		    return FAIL;
4850 		}
4851 	    }
4852 	    else if (STRCMP(hi->hi_key, "term_finish") == 0)
4853 	    {
4854 		if (!(supported2 & JO2_TERM_FINISH))
4855 		    break;
4856 		val = tv_get_string(item);
4857 		if (STRCMP(val, "open") != 0 && STRCMP(val, "close") != 0)
4858 		{
4859 		    semsg(_(e_invargNval), "term_finish", val);
4860 		    return FAIL;
4861 		}
4862 		opt->jo_set2 |= JO2_TERM_FINISH;
4863 		opt->jo_term_finish = *val;
4864 	    }
4865 	    else if (STRCMP(hi->hi_key, "term_opencmd") == 0)
4866 	    {
4867 		char_u *p;
4868 
4869 		if (!(supported2 & JO2_TERM_OPENCMD))
4870 		    break;
4871 		opt->jo_set2 |= JO2_TERM_OPENCMD;
4872 		p = opt->jo_term_opencmd = tv_get_string_chk(item);
4873 		if (p != NULL)
4874 		{
4875 		    /* Must have %d and no other %. */
4876 		    p = vim_strchr(p, '%');
4877 		    if (p != NULL && (p[1] != 'd'
4878 					    || vim_strchr(p + 2, '%') != NULL))
4879 			p = NULL;
4880 		}
4881 		if (p == NULL)
4882 		{
4883 		    semsg(_(e_invargval), "term_opencmd");
4884 		    return FAIL;
4885 		}
4886 	    }
4887 	    else if (STRCMP(hi->hi_key, "eof_chars") == 0)
4888 	    {
4889 		char_u *p;
4890 
4891 		if (!(supported2 & JO2_EOF_CHARS))
4892 		    break;
4893 		opt->jo_set2 |= JO2_EOF_CHARS;
4894 		p = opt->jo_eof_chars = tv_get_string_chk(item);
4895 		if (p == NULL)
4896 		{
4897 		    semsg(_(e_invargval), "eof_chars");
4898 		    return FAIL;
4899 		}
4900 	    }
4901 	    else if (STRCMP(hi->hi_key, "term_rows") == 0)
4902 	    {
4903 		if (!(supported2 & JO2_TERM_ROWS))
4904 		    break;
4905 		opt->jo_set2 |= JO2_TERM_ROWS;
4906 		opt->jo_term_rows = tv_get_number(item);
4907 	    }
4908 	    else if (STRCMP(hi->hi_key, "term_cols") == 0)
4909 	    {
4910 		if (!(supported2 & JO2_TERM_COLS))
4911 		    break;
4912 		opt->jo_set2 |= JO2_TERM_COLS;
4913 		opt->jo_term_cols = tv_get_number(item);
4914 	    }
4915 	    else if (STRCMP(hi->hi_key, "vertical") == 0)
4916 	    {
4917 		if (!(supported2 & JO2_VERTICAL))
4918 		    break;
4919 		opt->jo_set2 |= JO2_VERTICAL;
4920 		opt->jo_vertical = tv_get_number(item);
4921 	    }
4922 	    else if (STRCMP(hi->hi_key, "curwin") == 0)
4923 	    {
4924 		if (!(supported2 & JO2_CURWIN))
4925 		    break;
4926 		opt->jo_set2 |= JO2_CURWIN;
4927 		opt->jo_curwin = tv_get_number(item);
4928 	    }
4929 	    else if (STRCMP(hi->hi_key, "hidden") == 0)
4930 	    {
4931 		if (!(supported2 & JO2_HIDDEN))
4932 		    break;
4933 		opt->jo_set2 |= JO2_HIDDEN;
4934 		opt->jo_hidden = tv_get_number(item);
4935 	    }
4936 	    else if (STRCMP(hi->hi_key, "norestore") == 0)
4937 	    {
4938 		if (!(supported2 & JO2_NORESTORE))
4939 		    break;
4940 		opt->jo_set2 |= JO2_NORESTORE;
4941 		opt->jo_term_norestore = tv_get_number(item);
4942 	    }
4943 	    else if (STRCMP(hi->hi_key, "term_kill") == 0)
4944 	    {
4945 		if (!(supported2 & JO2_TERM_KILL))
4946 		    break;
4947 		opt->jo_set2 |= JO2_TERM_KILL;
4948 		opt->jo_term_kill = tv_get_string_chk(item);
4949 	    }
4950 	    else if (STRCMP(hi->hi_key, "term_mode") == 0)
4951 	    {
4952 		char_u *p;
4953 
4954 		if (!(supported2 & JO2_TERM_MODE))
4955 		    break;
4956 		opt->jo_set2 |= JO2_TERM_MODE;
4957 		p = tv_get_string_chk(item);
4958 		if (p == NULL)
4959 		{
4960 		    semsg(_(e_invargval), "term_mode");
4961 		    return FAIL;
4962 		}
4963 		// Allow empty string, "winpty", "conpty".
4964 		if (!(*p == NUL || STRCMP(p, "winpty") == 0
4965 					          || STRCMP(p, "conpty") == 0))
4966 		{
4967 		    semsg(_(e_invargval), "term_mode");
4968 		    return FAIL;
4969 		}
4970 		opt->jo_term_mode = p[0];
4971 	    }
4972 # if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
4973 	    else if (STRCMP(hi->hi_key, "ansi_colors") == 0)
4974 	    {
4975 		int		n = 0;
4976 		listitem_T	*li;
4977 		long_u		rgb[16];
4978 
4979 		if (!(supported2 & JO2_ANSI_COLORS))
4980 		    break;
4981 
4982 		if (item == NULL || item->v_type != VAR_LIST
4983 			|| item->vval.v_list == NULL)
4984 		{
4985 		    semsg(_(e_invargval), "ansi_colors");
4986 		    return FAIL;
4987 		}
4988 
4989 		li = item->vval.v_list->lv_first;
4990 		for (; li != NULL && n < 16; li = li->li_next, n++)
4991 		{
4992 		    char_u	*color_name;
4993 		    guicolor_T	guicolor;
4994 
4995 		    color_name = tv_get_string_chk(&li->li_tv);
4996 		    if (color_name == NULL)
4997 			return FAIL;
4998 
4999 		    guicolor = GUI_GET_COLOR(color_name);
5000 		    if (guicolor == INVALCOLOR)
5001 			return FAIL;
5002 
5003 		    rgb[n] = GUI_MCH_GET_RGB(guicolor);
5004 		}
5005 
5006 		if (n != 16 || li != NULL)
5007 		{
5008 		    semsg(_(e_invargval), "ansi_colors");
5009 		    return FAIL;
5010 		}
5011 
5012 		opt->jo_set2 |= JO2_ANSI_COLORS;
5013 		memcpy(opt->jo_ansi_colors, rgb, sizeof(rgb));
5014 	    }
5015 # endif
5016 #endif
5017 	    else if (STRCMP(hi->hi_key, "env") == 0)
5018 	    {
5019 		if (!(supported2 & JO2_ENV))
5020 		    break;
5021 		if (item->v_type != VAR_DICT)
5022 		{
5023 		    semsg(_(e_invargval), "env");
5024 		    return FAIL;
5025 		}
5026 		opt->jo_set2 |= JO2_ENV;
5027 		opt->jo_env = item->vval.v_dict;
5028 		if (opt->jo_env != NULL)
5029 		    ++opt->jo_env->dv_refcount;
5030 	    }
5031 	    else if (STRCMP(hi->hi_key, "cwd") == 0)
5032 	    {
5033 		if (!(supported2 & JO2_CWD))
5034 		    break;
5035 		opt->jo_cwd = tv_get_string_buf_chk(item, opt->jo_cwd_buf);
5036 		if (opt->jo_cwd == NULL || !mch_isdir(opt->jo_cwd)
5037 #ifndef WIN32  // Win32 directories don't have the concept of "executable"
5038 				|| mch_access((char *)opt->jo_cwd, X_OK) != 0
5039 #endif
5040 				)
5041 		{
5042 		    semsg(_(e_invargval), "cwd");
5043 		    return FAIL;
5044 		}
5045 		opt->jo_set2 |= JO2_CWD;
5046 	    }
5047 	    else if (STRCMP(hi->hi_key, "waittime") == 0)
5048 	    {
5049 		if (!(supported & JO_WAITTIME))
5050 		    break;
5051 		opt->jo_set |= JO_WAITTIME;
5052 		opt->jo_waittime = tv_get_number(item);
5053 	    }
5054 	    else if (STRCMP(hi->hi_key, "timeout") == 0)
5055 	    {
5056 		if (!(supported & JO_TIMEOUT))
5057 		    break;
5058 		opt->jo_set |= JO_TIMEOUT;
5059 		opt->jo_timeout = tv_get_number(item);
5060 	    }
5061 	    else if (STRCMP(hi->hi_key, "out_timeout") == 0)
5062 	    {
5063 		if (!(supported & JO_OUT_TIMEOUT))
5064 		    break;
5065 		opt->jo_set |= JO_OUT_TIMEOUT;
5066 		opt->jo_out_timeout = tv_get_number(item);
5067 	    }
5068 	    else if (STRCMP(hi->hi_key, "err_timeout") == 0)
5069 	    {
5070 		if (!(supported & JO_ERR_TIMEOUT))
5071 		    break;
5072 		opt->jo_set |= JO_ERR_TIMEOUT;
5073 		opt->jo_err_timeout = tv_get_number(item);
5074 	    }
5075 	    else if (STRCMP(hi->hi_key, "part") == 0)
5076 	    {
5077 		if (!(supported & JO_PART))
5078 		    break;
5079 		opt->jo_set |= JO_PART;
5080 		val = tv_get_string(item);
5081 		if (STRCMP(val, "err") == 0)
5082 		    opt->jo_part = PART_ERR;
5083 		else if (STRCMP(val, "out") == 0)
5084 		    opt->jo_part = PART_OUT;
5085 		else
5086 		{
5087 		    semsg(_(e_invargNval), "part", val);
5088 		    return FAIL;
5089 		}
5090 	    }
5091 	    else if (STRCMP(hi->hi_key, "id") == 0)
5092 	    {
5093 		if (!(supported & JO_ID))
5094 		    break;
5095 		opt->jo_set |= JO_ID;
5096 		opt->jo_id = tv_get_number(item);
5097 	    }
5098 	    else if (STRCMP(hi->hi_key, "stoponexit") == 0)
5099 	    {
5100 		if (!(supported & JO_STOPONEXIT))
5101 		    break;
5102 		opt->jo_set |= JO_STOPONEXIT;
5103 		opt->jo_stoponexit = tv_get_string_buf_chk(item,
5104 							     opt->jo_soe_buf);
5105 		if (opt->jo_stoponexit == NULL)
5106 		{
5107 		    semsg(_(e_invargval), "stoponexit");
5108 		    return FAIL;
5109 		}
5110 	    }
5111 	    else if (STRCMP(hi->hi_key, "block_write") == 0)
5112 	    {
5113 		if (!(supported & JO_BLOCK_WRITE))
5114 		    break;
5115 		opt->jo_set |= JO_BLOCK_WRITE;
5116 		opt->jo_block_write = tv_get_number(item);
5117 	    }
5118 	    else
5119 		break;
5120 	    --todo;
5121 	}
5122     if (todo > 0)
5123     {
5124 	semsg(_(e_invarg2), hi->hi_key);
5125 	return FAIL;
5126     }
5127 
5128     return OK;
5129 }
5130 
5131 /*
5132  * Get the channel from the argument.
5133  * Returns NULL if the handle is invalid.
5134  * When "check_open" is TRUE check that the channel can be used.
5135  * When "reading" is TRUE "check_open" considers typeahead useful.
5136  * "part" is used to check typeahead, when PART_COUNT use the default part.
5137  */
5138     channel_T *
5139 get_channel_arg(typval_T *tv, int check_open, int reading, ch_part_T part)
5140 {
5141     channel_T	*channel = NULL;
5142     int		has_readahead = FALSE;
5143 
5144     if (tv->v_type == VAR_JOB)
5145     {
5146 	if (tv->vval.v_job != NULL)
5147 	    channel = tv->vval.v_job->jv_channel;
5148     }
5149     else if (tv->v_type == VAR_CHANNEL)
5150     {
5151 	channel = tv->vval.v_channel;
5152     }
5153     else
5154     {
5155 	semsg(_(e_invarg2), tv_get_string(tv));
5156 	return NULL;
5157     }
5158     if (channel != NULL && reading)
5159 	has_readahead = channel_has_readahead(channel,
5160 		       part != PART_COUNT ? part : channel_part_read(channel));
5161 
5162     if (check_open && (channel == NULL || (!channel_is_open(channel)
5163 					     && !(reading && has_readahead))))
5164     {
5165 	emsg(_("E906: not an open channel"));
5166 	return NULL;
5167     }
5168     return channel;
5169 }
5170 
5171 static job_T *first_job = NULL;
5172 
5173     static void
5174 job_free_contents(job_T *job)
5175 {
5176     int		i;
5177 
5178     ch_log(job->jv_channel, "Freeing job");
5179     if (job->jv_channel != NULL)
5180     {
5181 	/* The link from the channel to the job doesn't count as a reference,
5182 	 * thus don't decrement the refcount of the job.  The reference from
5183 	 * the job to the channel does count the reference, decrement it and
5184 	 * NULL the reference.  We don't set ch_job_killed, unreferencing the
5185 	 * job doesn't mean it stops running. */
5186 	job->jv_channel->ch_job = NULL;
5187 	channel_unref(job->jv_channel);
5188     }
5189     mch_clear_job(job);
5190 
5191     vim_free(job->jv_tty_in);
5192     vim_free(job->jv_tty_out);
5193     vim_free(job->jv_stoponexit);
5194 #ifdef UNIX
5195     vim_free(job->jv_termsig);
5196 #endif
5197     free_callback(job->jv_exit_cb, job->jv_exit_partial);
5198     if (job->jv_argv != NULL)
5199     {
5200 	for (i = 0; job->jv_argv[i] != NULL; i++)
5201 	    vim_free(job->jv_argv[i]);
5202 	vim_free(job->jv_argv);
5203     }
5204 }
5205 
5206 /*
5207  * Remove "job" from the list of jobs.
5208  */
5209     static void
5210 job_unlink(job_T *job)
5211 {
5212     if (job->jv_next != NULL)
5213 	job->jv_next->jv_prev = job->jv_prev;
5214     if (job->jv_prev == NULL)
5215 	first_job = job->jv_next;
5216     else
5217 	job->jv_prev->jv_next = job->jv_next;
5218 }
5219 
5220     static void
5221 job_free_job(job_T *job)
5222 {
5223     job_unlink(job);
5224     vim_free(job);
5225 }
5226 
5227     static void
5228 job_free(job_T *job)
5229 {
5230     if (!in_free_unref_items)
5231     {
5232 	job_free_contents(job);
5233 	job_free_job(job);
5234     }
5235 }
5236 
5237 job_T *jobs_to_free = NULL;
5238 
5239 /*
5240  * Put "job" in a list to be freed later, when it's no longer referenced.
5241  */
5242     static void
5243 job_free_later(job_T *job)
5244 {
5245     job_unlink(job);
5246     job->jv_next = jobs_to_free;
5247     jobs_to_free = job;
5248 }
5249 
5250     static void
5251 free_jobs_to_free_later(void)
5252 {
5253     job_T *job;
5254 
5255     while (jobs_to_free != NULL)
5256     {
5257 	job = jobs_to_free;
5258 	jobs_to_free = job->jv_next;
5259 	job_free_contents(job);
5260 	vim_free(job);
5261     }
5262 }
5263 
5264 #if defined(EXITFREE) || defined(PROTO)
5265     void
5266 job_free_all(void)
5267 {
5268     while (first_job != NULL)
5269 	job_free(first_job);
5270     free_jobs_to_free_later();
5271 
5272 # ifdef FEAT_TERMINAL
5273     free_unused_terminals();
5274 # endif
5275 }
5276 #endif
5277 
5278 /*
5279  * Return TRUE if we need to check if the process of "job" has ended.
5280  */
5281     static int
5282 job_need_end_check(job_T *job)
5283 {
5284     return job->jv_status == JOB_STARTED
5285 		   && (job->jv_stoponexit != NULL || job->jv_exit_cb != NULL);
5286 }
5287 
5288 /*
5289  * Return TRUE if the channel of "job" is still useful.
5290  */
5291     static int
5292 job_channel_still_useful(job_T *job)
5293 {
5294     return job->jv_channel != NULL && channel_still_useful(job->jv_channel);
5295 }
5296 
5297 /*
5298  * Return TRUE if the channel of "job" is closeable.
5299  */
5300     static int
5301 job_channel_can_close(job_T *job)
5302 {
5303     return job->jv_channel != NULL && channel_can_close(job->jv_channel);
5304 }
5305 
5306 /*
5307  * Return TRUE if the job should not be freed yet.  Do not free the job when
5308  * it has not ended yet and there is a "stoponexit" flag, an exit callback
5309  * or when the associated channel will do something with the job output.
5310  */
5311     static int
5312 job_still_useful(job_T *job)
5313 {
5314     return job_need_end_check(job) || job_channel_still_useful(job);
5315 }
5316 
5317 #if defined(GUI_MAY_FORK) || defined(PROTO)
5318 /*
5319  * Return TRUE when there is any running job that we care about.
5320  */
5321     int
5322 job_any_running()
5323 {
5324     job_T	*job;
5325 
5326     for (job = first_job; job != NULL; job = job->jv_next)
5327 	if (job_still_useful(job))
5328 	{
5329 	    ch_log(NULL, "GUI not forking because a job is running");
5330 	    return TRUE;
5331 	}
5332     return FALSE;
5333 }
5334 #endif
5335 
5336 #if !defined(USE_ARGV) || defined(PROTO)
5337 /*
5338  * Escape one argument for an external command.
5339  * Returns the escaped string in allocated memory.  NULL when out of memory.
5340  */
5341     static char_u *
5342 win32_escape_arg(char_u *arg)
5343 {
5344     int		slen, dlen;
5345     int		escaping = 0;
5346     int		i;
5347     char_u	*s, *d;
5348     char_u	*escaped_arg;
5349     int		has_spaces = FALSE;
5350 
5351     /* First count the number of extra bytes required. */
5352     slen = (int)STRLEN(arg);
5353     dlen = slen;
5354     for (s = arg; *s != NUL; MB_PTR_ADV(s))
5355     {
5356 	if (*s == '"' || *s == '\\')
5357 	    ++dlen;
5358 	if (*s == ' ' || *s == '\t')
5359 	    has_spaces = TRUE;
5360     }
5361 
5362     if (has_spaces)
5363 	dlen += 2;
5364 
5365     if (dlen == slen)
5366 	return vim_strsave(arg);
5367 
5368     /* Allocate memory for the result and fill it. */
5369     escaped_arg = alloc(dlen + 1);
5370     if (escaped_arg == NULL)
5371 	return NULL;
5372     memset(escaped_arg, 0, dlen+1);
5373 
5374     d = escaped_arg;
5375 
5376     if (has_spaces)
5377 	*d++ = '"';
5378 
5379     for (s = arg; *s != NUL;)
5380     {
5381 	switch (*s)
5382 	{
5383 	    case '"':
5384 		for (i = 0; i < escaping; i++)
5385 		    *d++ = '\\';
5386 		escaping = 0;
5387 		*d++ = '\\';
5388 		*d++ = *s++;
5389 		break;
5390 	    case '\\':
5391 		escaping++;
5392 		*d++ = *s++;
5393 		break;
5394 	    default:
5395 		escaping = 0;
5396 		MB_COPY_CHAR(s, d);
5397 		break;
5398 	}
5399     }
5400 
5401     /* add terminating quote and finish with a NUL */
5402     if (has_spaces)
5403     {
5404 	for (i = 0; i < escaping; i++)
5405 	    *d++ = '\\';
5406 	*d++ = '"';
5407     }
5408     *d = NUL;
5409 
5410     return escaped_arg;
5411 }
5412 
5413 /*
5414  * Build a command line from a list, taking care of escaping.
5415  * The result is put in gap->ga_data.
5416  * Returns FAIL when out of memory.
5417  */
5418     int
5419 win32_build_cmd(list_T *l, garray_T *gap)
5420 {
5421     listitem_T  *li;
5422     char_u	*s;
5423 
5424     for (li = l->lv_first; li != NULL; li = li->li_next)
5425     {
5426 	s = tv_get_string_chk(&li->li_tv);
5427 	if (s == NULL)
5428 	    return FAIL;
5429 	s = win32_escape_arg(s);
5430 	if (s == NULL)
5431 	    return FAIL;
5432 	ga_concat(gap, s);
5433 	vim_free(s);
5434 	if (li->li_next != NULL)
5435 	    ga_append(gap, ' ');
5436     }
5437     return OK;
5438 }
5439 #endif
5440 
5441 /*
5442  * NOTE: Must call job_cleanup() only once right after the status of "job"
5443  * changed to JOB_ENDED (i.e. after job_status() returned "dead" first or
5444  * mch_detect_ended_job() returned non-NULL).
5445  * If the job is no longer used it will be removed from the list of jobs, and
5446  * deleted a bit later.
5447  */
5448     void
5449 job_cleanup(job_T *job)
5450 {
5451     if (job->jv_status != JOB_ENDED)
5452 	return;
5453 
5454     /* Ready to cleanup the job. */
5455     job->jv_status = JOB_FINISHED;
5456 
5457     /* When only channel-in is kept open, close explicitly. */
5458     if (job->jv_channel != NULL)
5459 	ch_close_part(job->jv_channel, PART_IN);
5460 
5461     if (job->jv_exit_cb != NULL)
5462     {
5463 	typval_T	argv[3];
5464 	typval_T	rettv;
5465 	int		dummy;
5466 
5467 	/* Invoke the exit callback. Make sure the refcount is > 0. */
5468 	ch_log(job->jv_channel, "Invoking exit callback %s", job->jv_exit_cb);
5469 	++job->jv_refcount;
5470 	argv[0].v_type = VAR_JOB;
5471 	argv[0].vval.v_job = job;
5472 	argv[1].v_type = VAR_NUMBER;
5473 	argv[1].vval.v_number = job->jv_exitval;
5474 	call_func(job->jv_exit_cb, (int)STRLEN(job->jv_exit_cb),
5475 	    &rettv, 2, argv, NULL, 0L, 0L, &dummy, TRUE,
5476 	    job->jv_exit_partial, NULL);
5477 	clear_tv(&rettv);
5478 	--job->jv_refcount;
5479 	channel_need_redraw = TRUE;
5480     }
5481 
5482     if (job->jv_channel != NULL
5483 	 && job->jv_channel->ch_anonymous_pipe && !job->jv_channel->ch_killing)
5484     {
5485 	++safe_to_invoke_callback;
5486 	channel_free_contents(job->jv_channel);
5487 	job->jv_channel->ch_job = NULL;
5488 	job->jv_channel = NULL;
5489 	--safe_to_invoke_callback;
5490     }
5491 
5492     // Do not free the job in case the close callback of the associated channel
5493     // isn't invoked yet and may get information by job_info().
5494     if (job->jv_refcount == 0 && !job_channel_still_useful(job))
5495 	// The job was already unreferenced and the associated channel was
5496 	// detached, now that it ended it can be freed. However, a caller might
5497 	// still use it, thus free it a bit later.
5498 	job_free_later(job);
5499 }
5500 
5501 /*
5502  * Mark references in jobs that are still useful.
5503  */
5504     int
5505 set_ref_in_job(int copyID)
5506 {
5507     int		abort = FALSE;
5508     job_T	*job;
5509     typval_T	tv;
5510 
5511     for (job = first_job; job != NULL; job = job->jv_next)
5512 	if (job_still_useful(job))
5513 	{
5514 	    tv.v_type = VAR_JOB;
5515 	    tv.vval.v_job = job;
5516 	    abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
5517 	}
5518     return abort;
5519 }
5520 
5521 /*
5522  * Dereference "job".  Note that after this "job" may have been freed.
5523  */
5524     void
5525 job_unref(job_T *job)
5526 {
5527     if (job != NULL && --job->jv_refcount <= 0)
5528     {
5529 	/* Do not free the job if there is a channel where the close callback
5530 	 * may get the job info. */
5531 	if (!job_channel_still_useful(job))
5532 	{
5533 	    /* Do not free the job when it has not ended yet and there is a
5534 	     * "stoponexit" flag or an exit callback. */
5535 	    if (!job_need_end_check(job))
5536 	    {
5537 		job_free(job);
5538 	    }
5539 	    else if (job->jv_channel != NULL)
5540 	    {
5541 		/* Do remove the link to the channel, otherwise it hangs
5542 		 * around until Vim exits. See job_free() for refcount. */
5543 		ch_log(job->jv_channel, "detaching channel from job");
5544 		job->jv_channel->ch_job = NULL;
5545 		channel_unref(job->jv_channel);
5546 		job->jv_channel = NULL;
5547 	    }
5548 	}
5549     }
5550 }
5551 
5552     int
5553 free_unused_jobs_contents(int copyID, int mask)
5554 {
5555     int		did_free = FALSE;
5556     job_T	*job;
5557 
5558     for (job = first_job; job != NULL; job = job->jv_next)
5559 	if ((job->jv_copyID & mask) != (copyID & mask)
5560 						    && !job_still_useful(job))
5561 	{
5562 	    /* Free the channel and ordinary items it contains, but don't
5563 	     * recurse into Lists, Dictionaries etc. */
5564 	    job_free_contents(job);
5565 	    did_free = TRUE;
5566 	}
5567     return did_free;
5568 }
5569 
5570     void
5571 free_unused_jobs(int copyID, int mask)
5572 {
5573     job_T	*job;
5574     job_T	*job_next;
5575 
5576     for (job = first_job; job != NULL; job = job_next)
5577     {
5578 	job_next = job->jv_next;
5579 	if ((job->jv_copyID & mask) != (copyID & mask)
5580 						    && !job_still_useful(job))
5581 	{
5582 	    /* Free the job struct itself. */
5583 	    job_free_job(job);
5584 	}
5585     }
5586 }
5587 
5588 /*
5589  * Allocate a job.  Sets the refcount to one and sets options default.
5590  */
5591     job_T *
5592 job_alloc(void)
5593 {
5594     job_T *job;
5595 
5596     job = (job_T *)alloc_clear(sizeof(job_T));
5597     if (job != NULL)
5598     {
5599 	job->jv_refcount = 1;
5600 	job->jv_stoponexit = vim_strsave((char_u *)"term");
5601 
5602 	if (first_job != NULL)
5603 	{
5604 	    first_job->jv_prev = job;
5605 	    job->jv_next = first_job;
5606 	}
5607 	first_job = job;
5608     }
5609     return job;
5610 }
5611 
5612     void
5613 job_set_options(job_T *job, jobopt_T *opt)
5614 {
5615     if (opt->jo_set & JO_STOPONEXIT)
5616     {
5617 	vim_free(job->jv_stoponexit);
5618 	if (opt->jo_stoponexit == NULL || *opt->jo_stoponexit == NUL)
5619 	    job->jv_stoponexit = NULL;
5620 	else
5621 	    job->jv_stoponexit = vim_strsave(opt->jo_stoponexit);
5622     }
5623     if (opt->jo_set & JO_EXIT_CB)
5624     {
5625 	free_callback(job->jv_exit_cb, job->jv_exit_partial);
5626 	if (opt->jo_exit_cb == NULL || *opt->jo_exit_cb == NUL)
5627 	{
5628 	    job->jv_exit_cb = NULL;
5629 	    job->jv_exit_partial = NULL;
5630 	}
5631 	else
5632 	{
5633 	    job->jv_exit_partial = opt->jo_exit_partial;
5634 	    if (job->jv_exit_partial != NULL)
5635 	    {
5636 		job->jv_exit_cb = opt->jo_exit_cb;
5637 		++job->jv_exit_partial->pt_refcount;
5638 	    }
5639 	    else
5640 	    {
5641 		job->jv_exit_cb = vim_strsave(opt->jo_exit_cb);
5642 		func_ref(job->jv_exit_cb);
5643 	    }
5644 	}
5645     }
5646 }
5647 
5648 /*
5649  * Called when Vim is exiting: kill all jobs that have the "stoponexit" flag.
5650  */
5651     void
5652 job_stop_on_exit(void)
5653 {
5654     job_T	*job;
5655 
5656     for (job = first_job; job != NULL; job = job->jv_next)
5657 	if (job->jv_status == JOB_STARTED && job->jv_stoponexit != NULL)
5658 	    mch_signal_job(job, job->jv_stoponexit);
5659 }
5660 
5661 /*
5662  * Return TRUE when there is any job that has an exit callback and might exit,
5663  * which means job_check_ended() should be called more often.
5664  */
5665     int
5666 has_pending_job(void)
5667 {
5668     job_T	    *job;
5669 
5670     for (job = first_job; job != NULL; job = job->jv_next)
5671 	/* Only should check if the channel has been closed, if the channel is
5672 	 * open the job won't exit. */
5673 	if ((job->jv_status == JOB_STARTED && !job_channel_still_useful(job))
5674 		    || (job->jv_status == JOB_FINISHED
5675 					      && job_channel_can_close(job)))
5676 	    return TRUE;
5677     return FALSE;
5678 }
5679 
5680 #define MAX_CHECK_ENDED 8
5681 
5682 /*
5683  * Called once in a while: check if any jobs that seem useful have ended.
5684  * Returns TRUE if a job did end.
5685  */
5686     int
5687 job_check_ended(void)
5688 {
5689     int		i;
5690     int		did_end = FALSE;
5691 
5692     // be quick if there are no jobs to check
5693     if (first_job == NULL)
5694 	return did_end;
5695 
5696     for (i = 0; i < MAX_CHECK_ENDED; ++i)
5697     {
5698 	// NOTE: mch_detect_ended_job() must only return a job of which the
5699 	// status was just set to JOB_ENDED.
5700 	job_T	*job = mch_detect_ended_job(first_job);
5701 
5702 	if (job == NULL)
5703 	    break;
5704 	did_end = TRUE;
5705 	job_cleanup(job); // may add "job" to jobs_to_free
5706     }
5707 
5708     // Actually free jobs that were cleaned up.
5709     free_jobs_to_free_later();
5710 
5711     if (channel_need_redraw)
5712     {
5713 	channel_need_redraw = FALSE;
5714 	redraw_after_callback(TRUE);
5715     }
5716     return did_end;
5717 }
5718 
5719 /*
5720  * Create a job and return it.  Implements job_start().
5721  * "argv_arg" is only for Unix.
5722  * When "argv_arg" is NULL then "argvars" is used.
5723  * The returned job has a refcount of one.
5724  * Returns NULL when out of memory.
5725  */
5726     job_T *
5727 job_start(
5728 	typval_T    *argvars,
5729 	char	    **argv_arg,
5730 	jobopt_T    *opt_arg,
5731 	int	    is_terminal UNUSED)
5732 {
5733     job_T	*job;
5734     char_u	*cmd = NULL;
5735     char	**argv = NULL;
5736     int		argc = 0;
5737 #if defined(UNIX)
5738 # define USE_ARGV
5739     int		i;
5740 #else
5741     garray_T	ga;
5742 #endif
5743     jobopt_T	opt;
5744     ch_part_T	part;
5745 
5746     job = job_alloc();
5747     if (job == NULL)
5748 	return NULL;
5749 
5750     job->jv_status = JOB_FAILED;
5751 #ifndef USE_ARGV
5752     ga_init2(&ga, (int)sizeof(char*), 20);
5753 #endif
5754 
5755     if (opt_arg != NULL)
5756 	opt = *opt_arg;
5757     else
5758     {
5759 	/* Default mode is NL. */
5760 	clear_job_options(&opt);
5761 	opt.jo_mode = MODE_NL;
5762 	if (get_job_options(&argvars[1], &opt,
5763 		    JO_MODE_ALL + JO_CB_ALL + JO_TIMEOUT_ALL + JO_STOPONEXIT
5764 			 + JO_EXIT_CB + JO_OUT_IO + JO_BLOCK_WRITE,
5765 		     JO2_ENV + JO2_CWD) == FAIL)
5766 	    goto theend;
5767     }
5768 
5769     /* Check that when io is "file" that there is a file name. */
5770     for (part = PART_OUT; part < PART_COUNT; ++part)
5771 	if ((opt.jo_set & (JO_OUT_IO << (part - PART_OUT)))
5772 		&& opt.jo_io[part] == JIO_FILE
5773 		&& (!(opt.jo_set & (JO_OUT_NAME << (part - PART_OUT)))
5774 		    || *opt.jo_io_name[part] == NUL))
5775 	{
5776 	    emsg(_("E920: _io file requires _name to be set"));
5777 	    goto theend;
5778 	}
5779 
5780     if ((opt.jo_set & JO_IN_IO) && opt.jo_io[PART_IN] == JIO_BUFFER)
5781     {
5782 	buf_T *buf = NULL;
5783 
5784 	/* check that we can find the buffer before starting the job */
5785 	if (opt.jo_set & JO_IN_BUF)
5786 	{
5787 	    buf = buflist_findnr(opt.jo_io_buf[PART_IN]);
5788 	    if (buf == NULL)
5789 		semsg(_(e_nobufnr), (long)opt.jo_io_buf[PART_IN]);
5790 	}
5791 	else if (!(opt.jo_set & JO_IN_NAME))
5792 	{
5793 	    emsg(_("E915: in_io buffer requires in_buf or in_name to be set"));
5794 	}
5795 	else
5796 	    buf = buflist_find_by_name(opt.jo_io_name[PART_IN], FALSE);
5797 	if (buf == NULL)
5798 	    goto theend;
5799 	if (buf->b_ml.ml_mfp == NULL)
5800 	{
5801 	    char_u	numbuf[NUMBUFLEN];
5802 	    char_u	*s;
5803 
5804 	    if (opt.jo_set & JO_IN_BUF)
5805 	    {
5806 		sprintf((char *)numbuf, "%d", opt.jo_io_buf[PART_IN]);
5807 		s = numbuf;
5808 	    }
5809 	    else
5810 		s = opt.jo_io_name[PART_IN];
5811 	    semsg(_("E918: buffer must be loaded: %s"), s);
5812 	    goto theend;
5813 	}
5814 	job->jv_in_buf = buf;
5815     }
5816 
5817     job_set_options(job, &opt);
5818 
5819 #ifdef USE_ARGV
5820     if (argv_arg != NULL)
5821     {
5822 	/* Make a copy of argv_arg for job->jv_argv. */
5823 	for (i = 0; argv_arg[i] != NULL; i++)
5824 	    argc++;
5825 	argv = (char **)alloc(sizeof(char *) * (argc + 1));
5826 	if (argv == NULL)
5827 	    goto theend;
5828 	for (i = 0; i < argc; i++)
5829 	    argv[i] = (char *)vim_strsave((char_u *)argv_arg[i]);
5830 	argv[argc] = NULL;
5831     }
5832     else
5833 #endif
5834     if (argvars[0].v_type == VAR_STRING)
5835     {
5836 	/* Command is a string. */
5837 	cmd = argvars[0].vval.v_string;
5838 	if (cmd == NULL || *cmd == NUL)
5839 	{
5840 	    emsg(_(e_invarg));
5841 	    goto theend;
5842 	}
5843 
5844 	if (build_argv_from_string(cmd, &argv, &argc) == FAIL)
5845 	    goto theend;
5846     }
5847     else if (argvars[0].v_type != VAR_LIST
5848 	    || argvars[0].vval.v_list == NULL
5849 	    || argvars[0].vval.v_list->lv_len < 1)
5850     {
5851 	emsg(_(e_invarg));
5852 	goto theend;
5853     }
5854     else
5855     {
5856 	list_T *l = argvars[0].vval.v_list;
5857 
5858 	if (build_argv_from_list(l, &argv, &argc) == FAIL)
5859 	    goto theend;
5860 #ifndef USE_ARGV
5861 	if (win32_build_cmd(l, &ga) == FAIL)
5862 	    goto theend;
5863 	cmd = ga.ga_data;
5864 #endif
5865     }
5866 
5867     /* Save the command used to start the job. */
5868     job->jv_argv = argv;
5869 
5870 #ifdef USE_ARGV
5871     if (ch_log_active())
5872     {
5873 	garray_T    ga;
5874 
5875 	ga_init2(&ga, (int)sizeof(char), 200);
5876 	for (i = 0; i < argc; ++i)
5877 	{
5878 	    if (i > 0)
5879 		ga_concat(&ga, (char_u *)"  ");
5880 	    ga_concat(&ga, (char_u *)argv[i]);
5881 	}
5882 	ch_log(NULL, "Starting job: %s", (char *)ga.ga_data);
5883 	ga_clear(&ga);
5884     }
5885     mch_job_start(argv, job, &opt, is_terminal);
5886 #else
5887     ch_log(NULL, "Starting job: %s", (char *)cmd);
5888     mch_job_start((char *)cmd, job, &opt);
5889 #endif
5890 
5891     /* If the channel is reading from a buffer, write lines now. */
5892     if (job->jv_channel != NULL)
5893 	channel_write_in(job->jv_channel);
5894 
5895 theend:
5896 #ifndef USE_ARGV
5897     vim_free(ga.ga_data);
5898 #endif
5899     if (argv != job->jv_argv)
5900 	vim_free(argv);
5901     free_job_options(&opt);
5902     return job;
5903 }
5904 
5905 /*
5906  * Get the status of "job" and invoke the exit callback when needed.
5907  * The returned string is not allocated.
5908  */
5909     char *
5910 job_status(job_T *job)
5911 {
5912     char	*result;
5913 
5914     if (job->jv_status >= JOB_ENDED)
5915 	/* No need to check, dead is dead. */
5916 	result = "dead";
5917     else if (job->jv_status == JOB_FAILED)
5918 	result = "fail";
5919     else
5920     {
5921 	result = mch_job_status(job);
5922 	if (job->jv_status == JOB_ENDED)
5923 	    job_cleanup(job);
5924     }
5925     return result;
5926 }
5927 
5928 /*
5929  * Implementation of job_info().
5930  */
5931     void
5932 job_info(job_T *job, dict_T *dict)
5933 {
5934     dictitem_T	*item;
5935     varnumber_T	nr;
5936     list_T	*l;
5937     int		i;
5938 
5939     dict_add_string(dict, "status", (char_u *)job_status(job));
5940 
5941     item = dictitem_alloc((char_u *)"channel");
5942     if (item == NULL)
5943 	return;
5944     item->di_tv.v_type = VAR_CHANNEL;
5945     item->di_tv.vval.v_channel = job->jv_channel;
5946     if (job->jv_channel != NULL)
5947 	++job->jv_channel->ch_refcount;
5948     if (dict_add(dict, item) == FAIL)
5949 	dictitem_free(item);
5950 
5951 #ifdef UNIX
5952     nr = job->jv_pid;
5953 #else
5954     nr = job->jv_proc_info.dwProcessId;
5955 #endif
5956     dict_add_number(dict, "process", nr);
5957     dict_add_string(dict, "tty_in", job->jv_tty_in);
5958     dict_add_string(dict, "tty_out", job->jv_tty_out);
5959 
5960     dict_add_number(dict, "exitval", job->jv_exitval);
5961     dict_add_string(dict, "exit_cb", job->jv_exit_cb);
5962     dict_add_string(dict, "stoponexit", job->jv_stoponexit);
5963 #ifdef UNIX
5964     dict_add_string(dict, "termsig", job->jv_termsig);
5965 #endif
5966 
5967     l = list_alloc();
5968     if (l != NULL)
5969     {
5970 	dict_add_list(dict, "cmd", l);
5971 	if (job->jv_argv != NULL)
5972 	    for (i = 0; job->jv_argv[i] != NULL; i++)
5973 		list_append_string(l, (char_u *)job->jv_argv[i], -1);
5974     }
5975 }
5976 
5977 /*
5978  * Implementation of job_info() to return info for all jobs.
5979  */
5980     void
5981 job_info_all(list_T *l)
5982 {
5983     job_T	*job;
5984     typval_T	tv;
5985 
5986     for (job = first_job; job != NULL; job = job->jv_next)
5987     {
5988 	tv.v_type = VAR_JOB;
5989 	tv.vval.v_job = job;
5990 
5991 	if (list_append_tv(l, &tv) != OK)
5992 	    return;
5993     }
5994 }
5995 
5996 /*
5997  * Send a signal to "job".  Implements job_stop().
5998  * When "type" is not NULL use this for the type.
5999  * Otherwise use argvars[1] for the type.
6000  */
6001     int
6002 job_stop(job_T *job, typval_T *argvars, char *type)
6003 {
6004     char_u *arg;
6005 
6006     if (type != NULL)
6007 	arg = (char_u *)type;
6008     else if (argvars[1].v_type == VAR_UNKNOWN)
6009 	arg = (char_u *)"";
6010     else
6011     {
6012 	arg = tv_get_string_chk(&argvars[1]);
6013 	if (arg == NULL)
6014 	{
6015 	    emsg(_(e_invarg));
6016 	    return 0;
6017 	}
6018     }
6019     if (job->jv_status == JOB_FAILED)
6020     {
6021 	ch_log(job->jv_channel, "Job failed to start, job_stop() skipped");
6022 	return 0;
6023     }
6024     if (job->jv_status == JOB_ENDED)
6025     {
6026 	ch_log(job->jv_channel, "Job has already ended, job_stop() skipped");
6027 	return 0;
6028     }
6029     ch_log(job->jv_channel, "Stopping job with '%s'", (char *)arg);
6030     if (mch_signal_job(job, arg) == FAIL)
6031 	return 0;
6032 
6033     /* Assume that only "kill" will kill the job. */
6034     if (job->jv_channel != NULL && STRCMP(arg, "kill") == 0)
6035 	job->jv_channel->ch_job_killed = TRUE;
6036 
6037     /* We don't try freeing the job, obviously the caller still has a
6038      * reference to it. */
6039     return 1;
6040 }
6041 
6042     void
6043 invoke_prompt_callback(void)
6044 {
6045     typval_T	rettv;
6046     int		dummy;
6047     typval_T	argv[2];
6048     char_u	*text;
6049     char_u	*prompt;
6050     linenr_T	lnum = curbuf->b_ml.ml_line_count;
6051 
6052     // Add a new line for the prompt before invoking the callback, so that
6053     // text can always be inserted above the last line.
6054     ml_append(lnum, (char_u  *)"", 0, FALSE);
6055     curwin->w_cursor.lnum = lnum + 1;
6056     curwin->w_cursor.col = 0;
6057 
6058     if (curbuf->b_prompt_callback == NULL || *curbuf->b_prompt_callback == NUL)
6059 	return;
6060     text = ml_get(lnum);
6061     prompt = prompt_text();
6062     if (STRLEN(text) >= STRLEN(prompt))
6063 	text += STRLEN(prompt);
6064     argv[0].v_type = VAR_STRING;
6065     argv[0].vval.v_string = vim_strsave(text);
6066     argv[1].v_type = VAR_UNKNOWN;
6067 
6068     call_func(curbuf->b_prompt_callback,
6069 	      (int)STRLEN(curbuf->b_prompt_callback),
6070 	      &rettv, 1, argv, NULL, 0L, 0L, &dummy, TRUE,
6071 	      curbuf->b_prompt_partial, NULL);
6072     clear_tv(&argv[0]);
6073     clear_tv(&rettv);
6074 }
6075 
6076 /*
6077  * Return TRUE when the interrupt callback was invoked.
6078  */
6079     int
6080 invoke_prompt_interrupt(void)
6081 {
6082     typval_T	rettv;
6083     int		dummy;
6084     typval_T	argv[1];
6085 
6086     if (curbuf->b_prompt_interrupt == NULL
6087 					|| *curbuf->b_prompt_interrupt == NUL)
6088 	return FALSE;
6089     argv[0].v_type = VAR_UNKNOWN;
6090 
6091     got_int = FALSE; // don't skip executing commands
6092     call_func(curbuf->b_prompt_interrupt,
6093 	      (int)STRLEN(curbuf->b_prompt_interrupt),
6094 	      &rettv, 0, argv, NULL, 0L, 0L, &dummy, TRUE,
6095 	      curbuf->b_prompt_int_partial, NULL);
6096     clear_tv(&rettv);
6097     return TRUE;
6098 }
6099 
6100 #endif /* FEAT_JOB_CHANNEL */
6101