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