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