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