xref: /vim-8.2.3635/src/channel.c (revision fc3b7750)
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 	// Invoke callbacks and flush buffers before the close callback.
3160 	if (channel->ch_close_cb.cb_name != NULL)
3161 	    ch_log(channel,
3162 		     "Invoking callbacks and flushing buffers before closing");
3163 	for (part = PART_SOCK; part < PART_IN; ++part)
3164 	{
3165 	    if (channel->ch_close_cb.cb_name != NULL
3166 			    || channel->ch_part[part].ch_bufref.br_buf != NULL)
3167 	    {
3168 		// Increment the refcount to avoid the channel being freed
3169 		// halfway.
3170 		++channel->ch_refcount;
3171 		if (channel->ch_close_cb.cb_name == NULL)
3172 		    ch_log(channel, "flushing %s buffers before closing",
3173 							     part_names[part]);
3174 		while (may_invoke_callback(channel, part))
3175 		    ;
3176 		--channel->ch_refcount;
3177 	    }
3178 	}
3179 
3180 	if (channel->ch_close_cb.cb_name != NULL)
3181 	{
3182 	      typval_T	argv[1];
3183 	      typval_T	rettv;
3184 
3185 	      // Increment the refcount to avoid the channel being freed
3186 	      // halfway.
3187 	      ++channel->ch_refcount;
3188 	      ch_log(channel, "Invoking close callback %s",
3189 					 (char *)channel->ch_close_cb.cb_name);
3190 	      argv[0].v_type = VAR_CHANNEL;
3191 	      argv[0].vval.v_channel = channel;
3192 	      call_callback(&channel->ch_close_cb, -1, &rettv, 1, argv);
3193 	      clear_tv(&rettv);
3194 	      channel_need_redraw = TRUE;
3195 
3196 	      // the callback is only called once
3197 	      free_callback(&channel->ch_close_cb);
3198 
3199 	      if (channel_need_redraw)
3200 	      {
3201 		  channel_need_redraw = FALSE;
3202 		  redraw_after_callback(TRUE);
3203 	      }
3204 
3205 	      if (!channel->ch_drop_never)
3206 		  // any remaining messages are useless now
3207 		  for (part = PART_SOCK; part < PART_IN; ++part)
3208 		      drop_messages(channel, part);
3209 
3210 	      --channel->ch_refcount;
3211 	}
3212     }
3213 
3214     channel->ch_nb_close_cb = NULL;
3215 
3216 #ifdef FEAT_TERMINAL
3217     term_channel_closed(channel);
3218 #endif
3219 }
3220 
3221 /*
3222  * Close the "in" part channel "channel".
3223  */
3224     static void
channel_close_in(channel_T * channel)3225 channel_close_in(channel_T *channel)
3226 {
3227     ch_close_part(channel, PART_IN);
3228 }
3229 
3230     static void
remove_from_writeque(writeq_T * wq,writeq_T * entry)3231 remove_from_writeque(writeq_T *wq, writeq_T *entry)
3232 {
3233     ga_clear(&entry->wq_ga);
3234     wq->wq_next = entry->wq_next;
3235     if (wq->wq_next == NULL)
3236 	wq->wq_prev = NULL;
3237     else
3238 	wq->wq_next->wq_prev = NULL;
3239     vim_free(entry);
3240 }
3241 
3242 /*
3243  * Clear the read buffer on "channel"/"part".
3244  */
3245     static void
channel_clear_one(channel_T * channel,ch_part_T part)3246 channel_clear_one(channel_T *channel, ch_part_T part)
3247 {
3248     chanpart_T *ch_part = &channel->ch_part[part];
3249     jsonq_T *json_head = &ch_part->ch_json_head;
3250     cbq_T   *cb_head = &ch_part->ch_cb_head;
3251 
3252     while (channel_peek(channel, part) != NULL)
3253 	vim_free(channel_get(channel, part, NULL));
3254 
3255     while (cb_head->cq_next != NULL)
3256     {
3257 	cbq_T *node = cb_head->cq_next;
3258 
3259 	remove_cb_node(cb_head, node);
3260 	free_callback(&node->cq_callback);
3261 	vim_free(node);
3262     }
3263 
3264     while (json_head->jq_next != NULL)
3265     {
3266 	free_tv(json_head->jq_next->jq_value);
3267 	remove_json_node(json_head, json_head->jq_next);
3268     }
3269 
3270     free_callback(&ch_part->ch_callback);
3271     ga_clear(&ch_part->ch_block_ids);
3272 
3273     while (ch_part->ch_writeque.wq_next != NULL)
3274 	remove_from_writeque(&ch_part->ch_writeque,
3275 						 ch_part->ch_writeque.wq_next);
3276 }
3277 
3278 /*
3279  * Clear all the read buffers on "channel".
3280  */
3281     void
channel_clear(channel_T * channel)3282 channel_clear(channel_T *channel)
3283 {
3284     ch_log(channel, "Clearing channel");
3285     VIM_CLEAR(channel->ch_hostname);
3286     channel_clear_one(channel, PART_SOCK);
3287     channel_clear_one(channel, PART_OUT);
3288     channel_clear_one(channel, PART_ERR);
3289     channel_clear_one(channel, PART_IN);
3290     free_callback(&channel->ch_callback);
3291     free_callback(&channel->ch_close_cb);
3292 }
3293 
3294 #if defined(EXITFREE) || defined(PROTO)
3295     void
channel_free_all(void)3296 channel_free_all(void)
3297 {
3298     channel_T *channel;
3299 
3300     ch_log(NULL, "channel_free_all()");
3301     FOR_ALL_CHANNELS(channel)
3302 	channel_clear(channel);
3303 }
3304 #endif
3305 
3306 
3307 // Sent when the netbeans channel is found closed when reading.
3308 #define DETACH_MSG_RAW "DETACH\n"
3309 
3310 // Buffer size for reading incoming messages.
3311 #define MAXMSGSIZE 4096
3312 
3313 #if defined(HAVE_SELECT)
3314 /*
3315  * Add write fds where we are waiting for writing to be possible.
3316  */
3317     static int
channel_fill_wfds(int maxfd_arg,fd_set * wfds)3318 channel_fill_wfds(int maxfd_arg, fd_set *wfds)
3319 {
3320     int		maxfd = maxfd_arg;
3321     channel_T	*ch;
3322 
3323     FOR_ALL_CHANNELS(ch)
3324     {
3325 	chanpart_T  *in_part = &ch->ch_part[PART_IN];
3326 
3327 	if (in_part->ch_fd != INVALID_FD
3328 		&& (in_part->ch_bufref.br_buf != NULL
3329 		    || in_part->ch_writeque.wq_next != NULL))
3330 	{
3331 	    FD_SET((int)in_part->ch_fd, wfds);
3332 	    if ((int)in_part->ch_fd >= maxfd)
3333 		maxfd = (int)in_part->ch_fd + 1;
3334 	}
3335     }
3336     return maxfd;
3337 }
3338 #else
3339 /*
3340  * Add write fds where we are waiting for writing to be possible.
3341  */
3342     static int
channel_fill_poll_write(int nfd_in,struct pollfd * fds)3343 channel_fill_poll_write(int nfd_in, struct pollfd *fds)
3344 {
3345     int		nfd = nfd_in;
3346     channel_T	*ch;
3347 
3348     FOR_ALL_CHANNELS(ch)
3349     {
3350 	chanpart_T  *in_part = &ch->ch_part[PART_IN];
3351 
3352 	if (in_part->ch_fd != INVALID_FD
3353 		&& (in_part->ch_bufref.br_buf != NULL
3354 		    || in_part->ch_writeque.wq_next != NULL))
3355 	{
3356 	    in_part->ch_poll_idx = nfd;
3357 	    fds[nfd].fd = in_part->ch_fd;
3358 	    fds[nfd].events = POLLOUT;
3359 	    ++nfd;
3360 	}
3361 	else
3362 	    in_part->ch_poll_idx = -1;
3363     }
3364     return nfd;
3365 }
3366 #endif
3367 
3368 typedef enum {
3369     CW_READY,
3370     CW_NOT_READY,
3371     CW_ERROR
3372 } channel_wait_result;
3373 
3374 /*
3375  * Check for reading from "fd" with "timeout" msec.
3376  * Return CW_READY when there is something to read.
3377  * Return CW_NOT_READY when there is nothing to read.
3378  * Return CW_ERROR when there is an error.
3379  */
3380     static channel_wait_result
channel_wait(channel_T * channel,sock_T fd,int timeout)3381 channel_wait(channel_T *channel, sock_T fd, int timeout)
3382 {
3383     if (timeout > 0)
3384 	ch_log(channel, "Waiting for up to %d msec", timeout);
3385 
3386 # ifdef MSWIN
3387     if (fd != channel->CH_SOCK_FD)
3388     {
3389 	DWORD	nread;
3390 	int	sleep_time;
3391 	DWORD	deadline = GetTickCount() + timeout;
3392 	int	delay = 1;
3393 
3394 	// reading from a pipe, not a socket
3395 	while (TRUE)
3396 	{
3397 	    int r = PeekNamedPipe((HANDLE)fd, NULL, 0, NULL, &nread, NULL);
3398 
3399 	    if (r && nread > 0)
3400 		return CW_READY;
3401 
3402 	    if (channel->ch_named_pipe)
3403 	    {
3404 		DisconnectNamedPipe((HANDLE)fd);
3405 		ConnectNamedPipe((HANDLE)fd, NULL);
3406 	    }
3407 	    else if (r == 0)
3408 		return CW_ERROR;
3409 
3410 	    // perhaps write some buffer lines
3411 	    channel_write_any_lines();
3412 
3413 	    sleep_time = deadline - GetTickCount();
3414 	    if (sleep_time <= 0)
3415 		break;
3416 	    // Wait for a little while.  Very short at first, up to 10 msec
3417 	    // after looping a few times.
3418 	    if (sleep_time > delay)
3419 		sleep_time = delay;
3420 	    Sleep(sleep_time);
3421 	    delay = delay * 2;
3422 	    if (delay > 10)
3423 		delay = 10;
3424 	}
3425     }
3426     else
3427 #endif
3428     {
3429 #if defined(HAVE_SELECT)
3430 	struct timeval	tval;
3431 	fd_set		rfds;
3432 	fd_set		wfds;
3433 	int		ret;
3434 	int		maxfd;
3435 
3436 	tval.tv_sec = timeout / 1000;
3437 	tval.tv_usec = (timeout % 1000) * 1000;
3438 	for (;;)
3439 	{
3440 	    FD_ZERO(&rfds);
3441 	    FD_SET((int)fd, &rfds);
3442 
3443 	    // Write lines to a pipe when a pipe can be written to.  Need to
3444 	    // set this every time, some buffers may be done.
3445 	    maxfd = (int)fd + 1;
3446 	    FD_ZERO(&wfds);
3447 	    maxfd = channel_fill_wfds(maxfd, &wfds);
3448 
3449 	    ret = select(maxfd, &rfds, &wfds, NULL, &tval);
3450 # ifdef EINTR
3451 	    SOCK_ERRNO;
3452 	    if (ret == -1 && errno == EINTR)
3453 		continue;
3454 # endif
3455 	    if (ret > 0)
3456 	    {
3457 		if (FD_ISSET(fd, &rfds))
3458 		    return CW_READY;
3459 		channel_write_any_lines();
3460 		continue;
3461 	    }
3462 	    break;
3463 	}
3464 #else
3465 	for (;;)
3466 	{
3467 	    struct pollfd   fds[MAX_OPEN_CHANNELS + 1];
3468 	    int		    nfd = 1;
3469 
3470 	    fds[0].fd = fd;
3471 	    fds[0].events = POLLIN;
3472 	    nfd = channel_fill_poll_write(nfd, fds);
3473 	    if (poll(fds, nfd, timeout) > 0)
3474 	    {
3475 		if (fds[0].revents & POLLIN)
3476 		    return CW_READY;
3477 		channel_write_any_lines();
3478 		continue;
3479 	    }
3480 	    break;
3481 	}
3482 #endif
3483     }
3484     return CW_NOT_READY;
3485 }
3486 
3487     static void
ch_close_part_on_error(channel_T * channel,ch_part_T part,int is_err,char * func)3488 ch_close_part_on_error(
3489 	channel_T *channel, ch_part_T part, int is_err, char *func)
3490 {
3491     char	msg[] = "%s(): Read %s from ch_part[%d], closing";
3492 
3493     if (is_err)
3494 	// Do not call emsg(), most likely the other end just exited.
3495 	ch_error(channel, msg, func, "error", part);
3496     else
3497 	ch_log(channel, msg, func, "EOF", part);
3498 
3499     // Queue a "DETACH" netbeans message in the command queue in order to
3500     // terminate the netbeans session later. Do not end the session here
3501     // directly as we may be running in the context of a call to
3502     // netbeans_parse_messages():
3503     //	netbeans_parse_messages
3504     //	    -> autocmd triggered while processing the netbeans cmd
3505     //		-> ui_breakcheck
3506     //		    -> gui event loop or select loop
3507     //			-> channel_read()
3508     // Only send "DETACH" for a netbeans channel.
3509     if (channel->ch_nb_close_cb != NULL)
3510 	channel_save(channel, PART_SOCK, (char_u *)DETACH_MSG_RAW,
3511 			      (int)STRLEN(DETACH_MSG_RAW), FALSE, "PUT ");
3512 
3513     // When reading is not possible close this part of the channel.  Don't
3514     // close the channel yet, there may be something to read on another part.
3515     // When stdout and stderr use the same FD we get the error only on one of
3516     // them, also close the other.
3517     if (part == PART_OUT || part == PART_ERR)
3518     {
3519 	ch_part_T other = part == PART_OUT ? PART_ERR : PART_OUT;
3520 
3521 	if (channel->ch_part[part].ch_fd == channel->ch_part[other].ch_fd)
3522 	    ch_close_part(channel, other);
3523     }
3524     ch_close_part(channel, part);
3525 
3526 #ifdef FEAT_GUI
3527     // Stop listening to GUI events right away.
3528     channel_gui_unregister_one(channel, part);
3529 #endif
3530 }
3531 
3532     static void
channel_close_now(channel_T * channel)3533 channel_close_now(channel_T *channel)
3534 {
3535     ch_log(channel, "Closing channel because all readable fds are closed");
3536     if (channel->ch_nb_close_cb != NULL)
3537 	(*channel->ch_nb_close_cb)();
3538     channel_close(channel, TRUE);
3539 }
3540 
3541 /*
3542  * Read from channel "channel" for as long as there is something to read.
3543  * "part" is PART_SOCK, PART_OUT or PART_ERR.
3544  * The data is put in the read queue.  No callbacks are invoked here.
3545  */
3546     static void
channel_read(channel_T * channel,ch_part_T part,char * func)3547 channel_read(channel_T *channel, ch_part_T part, char *func)
3548 {
3549     static char_u	*buf = NULL;
3550     int			len = 0;
3551     int			readlen = 0;
3552     sock_T		fd;
3553     int			use_socket = FALSE;
3554 
3555     fd = channel->ch_part[part].ch_fd;
3556     if (fd == INVALID_FD)
3557     {
3558 	ch_error(channel, "channel_read() called while %s part is closed",
3559 							    part_names[part]);
3560 	return;
3561     }
3562     use_socket = fd == channel->CH_SOCK_FD;
3563 
3564     // Allocate a buffer to read into.
3565     if (buf == NULL)
3566     {
3567 	buf = alloc(MAXMSGSIZE);
3568 	if (buf == NULL)
3569 	    return;	// out of memory!
3570     }
3571 
3572     // Keep on reading for as long as there is something to read.
3573     // Use select() or poll() to avoid blocking on a message that is exactly
3574     // MAXMSGSIZE long.
3575     for (;;)
3576     {
3577 	if (channel_wait(channel, fd, 0) != CW_READY)
3578 	    break;
3579 	if (use_socket)
3580 	    len = sock_read(fd, (char *)buf, MAXMSGSIZE);
3581 	else
3582 	    len = fd_read(fd, (char *)buf, MAXMSGSIZE);
3583 	if (len <= 0)
3584 	    break;	// error or nothing more to read
3585 
3586 	// Store the read message in the queue.
3587 	channel_save(channel, part, buf, len, FALSE, "RECV ");
3588 	readlen += len;
3589 	if (len < MAXMSGSIZE)
3590 	    break;	// did read everything that's available
3591     }
3592 
3593     // Reading a disconnection (readlen == 0), or an error.
3594     if (readlen <= 0)
3595     {
3596 	if (!channel->ch_keep_open)
3597 	    ch_close_part_on_error(channel, part, (len < 0), func);
3598     }
3599 #if defined(CH_HAS_GUI) && defined(FEAT_GUI_GTK)
3600     else if (CH_HAS_GUI && gtk_main_level() > 0)
3601 	// signal the main loop that there is something to read
3602 	gtk_main_quit();
3603 #endif
3604 }
3605 
3606 /*
3607  * Read from RAW or NL "channel"/"part".  Blocks until there is something to
3608  * read or the timeout expires.
3609  * When "raw" is TRUE don't block waiting on a NL.
3610  * Does not trigger timers or handle messages.
3611  * Returns what was read in allocated memory.
3612  * Returns NULL in case of error or timeout.
3613  */
3614     static char_u *
channel_read_block(channel_T * channel,ch_part_T part,int timeout,int raw,int * outlen)3615 channel_read_block(
3616 	channel_T *channel, ch_part_T part, int timeout, int raw, int *outlen)
3617 {
3618     char_u	*buf;
3619     char_u	*msg;
3620     ch_mode_T	mode = channel->ch_part[part].ch_mode;
3621     sock_T	fd = channel->ch_part[part].ch_fd;
3622     char_u	*nl;
3623     readq_T	*node;
3624 
3625     ch_log(channel, "Blocking %s read, timeout: %d msec",
3626 				     mode == MODE_RAW ? "RAW" : "NL", timeout);
3627 
3628     while (TRUE)
3629     {
3630 	node = channel_peek(channel, part);
3631 	if (node != NULL)
3632 	{
3633 	    if (mode == MODE_RAW || (mode == MODE_NL
3634 					   && channel_first_nl(node) != NULL))
3635 		// got a complete message
3636 		break;
3637 	    if (channel_collapse(channel, part, mode == MODE_NL) == OK)
3638 		continue;
3639 	    // If not blocking or nothing more is coming then return what we
3640 	    // have.
3641 	    if (raw || fd == INVALID_FD)
3642 		break;
3643 	}
3644 
3645 	// Wait for up to the channel timeout.
3646 	if (fd == INVALID_FD)
3647 	    return NULL;
3648 	if (channel_wait(channel, fd, timeout) != CW_READY)
3649 	{
3650 	    ch_log(channel, "Timed out");
3651 	    return NULL;
3652 	}
3653 	channel_read(channel, part, "channel_read_block");
3654     }
3655 
3656     // We have a complete message now.
3657     if (mode == MODE_RAW || outlen != NULL)
3658     {
3659 	msg = channel_get_all(channel, part, outlen);
3660     }
3661     else
3662     {
3663 	char_u *p;
3664 
3665 	buf = node->rq_buffer;
3666 	nl = channel_first_nl(node);
3667 
3668 	// Convert NUL to NL, the internal representation.
3669 	for (p = buf; (nl == NULL || p < nl) && p < buf + node->rq_buflen; ++p)
3670 	    if (*p == NUL)
3671 		*p = NL;
3672 
3673 	if (nl == NULL)
3674 	{
3675 	    // must be a closed channel with missing NL
3676 	    msg = channel_get(channel, part, NULL);
3677 	}
3678 	else if (nl + 1 == buf + node->rq_buflen)
3679 	{
3680 	    // get the whole buffer
3681 	    msg = channel_get(channel, part, NULL);
3682 	    *nl = NUL;
3683 	}
3684 	else
3685 	{
3686 	    // Copy the message into allocated memory and remove it from the
3687 	    // buffer.
3688 	    msg = vim_strnsave(buf, nl - buf);
3689 	    channel_consume(channel, part, (int)(nl - buf) + 1);
3690 	}
3691     }
3692     if (ch_log_active())
3693 	ch_log(channel, "Returning %d bytes", (int)STRLEN(msg));
3694     return msg;
3695 }
3696 
3697 static int channel_blocking_wait = 0;
3698 
3699 /*
3700  * Return TRUE if in a blocking wait that might trigger callbacks.
3701  */
3702     int
channel_in_blocking_wait(void)3703 channel_in_blocking_wait(void)
3704 {
3705     return channel_blocking_wait > 0;
3706 }
3707 
3708 /*
3709  * Read one JSON message with ID "id" from "channel"/"part" and store the
3710  * result in "rettv".
3711  * When "id" is -1 accept any message;
3712  * Blocks until the message is received or the timeout is reached.
3713  * In corner cases this can be called recursively, that is why ch_block_ids is
3714  * a list.
3715  */
3716     static int
channel_read_json_block(channel_T * channel,ch_part_T part,int timeout_arg,int id,typval_T ** rettv)3717 channel_read_json_block(
3718 	channel_T   *channel,
3719 	ch_part_T   part,
3720 	int	    timeout_arg,
3721 	int	    id,
3722 	typval_T    **rettv)
3723 {
3724     int		more;
3725     sock_T	fd;
3726     int		timeout;
3727     chanpart_T	*chanpart = &channel->ch_part[part];
3728     int		retval = FAIL;
3729 
3730     ch_log(channel, "Blocking read JSON for id %d", id);
3731     ++channel_blocking_wait;
3732 
3733     if (id >= 0)
3734 	channel_add_block_id(chanpart, id);
3735 
3736     for (;;)
3737     {
3738 	more = channel_parse_json(channel, part);
3739 
3740 	// search for message "id"
3741 	if (channel_get_json(channel, part, id, TRUE, rettv) == OK)
3742 	{
3743 	    ch_log(channel, "Received JSON for id %d", id);
3744 	    retval = OK;
3745 	    break;
3746 	}
3747 
3748 	if (!more)
3749 	{
3750 	    // Handle any other messages in the queue.  If done some more
3751 	    // messages may have arrived.
3752 	    if (channel_parse_messages())
3753 		continue;
3754 
3755 	    // Wait for up to the timeout.  If there was an incomplete message
3756 	    // use the deadline for that.
3757 	    timeout = timeout_arg;
3758 	    if (chanpart->ch_wait_len > 0)
3759 	    {
3760 #ifdef MSWIN
3761 		timeout = chanpart->ch_deadline - GetTickCount() + 1;
3762 #else
3763 		{
3764 		    struct timeval now_tv;
3765 
3766 		    gettimeofday(&now_tv, NULL);
3767 		    timeout = (chanpart->ch_deadline.tv_sec
3768 						       - now_tv.tv_sec) * 1000
3769 			+ (chanpart->ch_deadline.tv_usec
3770 						     - now_tv.tv_usec) / 1000
3771 			+ 1;
3772 		}
3773 #endif
3774 		if (timeout < 0)
3775 		{
3776 		    // Something went wrong, channel_parse_json() didn't
3777 		    // discard message.  Cancel waiting.
3778 		    chanpart->ch_wait_len = 0;
3779 		    timeout = timeout_arg;
3780 		}
3781 		else if (timeout > timeout_arg)
3782 		    timeout = timeout_arg;
3783 	    }
3784 	    fd = chanpart->ch_fd;
3785 	    if (fd == INVALID_FD
3786 			    || channel_wait(channel, fd, timeout) != CW_READY)
3787 	    {
3788 		if (timeout == timeout_arg)
3789 		{
3790 		    if (fd != INVALID_FD)
3791 			ch_log(channel, "Timed out on id %d", id);
3792 		    break;
3793 		}
3794 	    }
3795 	    else
3796 		channel_read(channel, part, "channel_read_json_block");
3797 	}
3798     }
3799     if (id >= 0)
3800 	channel_remove_block_id(chanpart, id);
3801     --channel_blocking_wait;
3802 
3803     return retval;
3804 }
3805 
3806 /*
3807  * Get the channel from the argument.
3808  * Returns NULL if the handle is invalid.
3809  * When "check_open" is TRUE check that the channel can be used.
3810  * When "reading" is TRUE "check_open" considers typeahead useful.
3811  * "part" is used to check typeahead, when PART_COUNT use the default part.
3812  */
3813     static channel_T *
get_channel_arg(typval_T * tv,int check_open,int reading,ch_part_T part)3814 get_channel_arg(typval_T *tv, int check_open, int reading, ch_part_T part)
3815 {
3816     channel_T	*channel = NULL;
3817     int		has_readahead = FALSE;
3818 
3819     if (tv->v_type == VAR_JOB)
3820     {
3821 	if (tv->vval.v_job != NULL)
3822 	    channel = tv->vval.v_job->jv_channel;
3823     }
3824     else if (tv->v_type == VAR_CHANNEL)
3825     {
3826 	channel = tv->vval.v_channel;
3827     }
3828     else
3829     {
3830 	semsg(_(e_invarg2), tv_get_string(tv));
3831 	return NULL;
3832     }
3833     if (channel != NULL && reading)
3834 	has_readahead = channel_has_readahead(channel,
3835 		       part != PART_COUNT ? part : channel_part_read(channel));
3836 
3837     if (check_open && (channel == NULL || (!channel_is_open(channel)
3838 					     && !(reading && has_readahead))))
3839     {
3840 	emsg(_("E906: not an open channel"));
3841 	return NULL;
3842     }
3843     return channel;
3844 }
3845 
3846 /*
3847  * Common for ch_read() and ch_readraw().
3848  */
3849     static void
common_channel_read(typval_T * argvars,typval_T * rettv,int raw,int blob)3850 common_channel_read(typval_T *argvars, typval_T *rettv, int raw, int blob)
3851 {
3852     channel_T	*channel;
3853     ch_part_T	part = PART_COUNT;
3854     jobopt_T	opt;
3855     int		mode;
3856     int		timeout;
3857     int		id = -1;
3858     typval_T	*listtv = NULL;
3859 
3860     // return an empty string by default
3861     rettv->v_type = VAR_STRING;
3862     rettv->vval.v_string = NULL;
3863 
3864     if (in_vim9script()
3865 	    && (check_for_chan_or_job_arg(argvars, 0) == FAIL
3866 		|| check_for_opt_dict_arg(argvars, 1) == FAIL))
3867 	return;
3868 
3869     clear_job_options(&opt);
3870     if (get_job_options(&argvars[1], &opt, JO_TIMEOUT + JO_PART + JO_ID, 0)
3871 								      == FAIL)
3872 	goto theend;
3873 
3874     if (opt.jo_set & JO_PART)
3875 	part = opt.jo_part;
3876     channel = get_channel_arg(&argvars[0], TRUE, TRUE, part);
3877     if (channel != NULL)
3878     {
3879 	if (part == PART_COUNT)
3880 	    part = channel_part_read(channel);
3881 	mode = channel_get_mode(channel, part);
3882 	timeout = channel_get_timeout(channel, part);
3883 	if (opt.jo_set & JO_TIMEOUT)
3884 	    timeout = opt.jo_timeout;
3885 
3886 	if (blob)
3887 	{
3888 	    int	    outlen = 0;
3889 	    char_u  *p = channel_read_block(channel, part,
3890 						       timeout, TRUE, &outlen);
3891 	    if (p != NULL)
3892 	    {
3893 		blob_T	*b = blob_alloc();
3894 
3895 		if (b != NULL)
3896 		{
3897 		    b->bv_ga.ga_len = outlen;
3898 		    if (ga_grow(&b->bv_ga, outlen) == FAIL)
3899 			blob_free(b);
3900 		    else
3901 		    {
3902 			memcpy(b->bv_ga.ga_data, p, outlen);
3903 			rettv_blob_set(rettv, b);
3904 		    }
3905 		}
3906 		vim_free(p);
3907 	    }
3908 	}
3909 	else if (raw || mode == MODE_RAW || mode == MODE_NL)
3910 	    rettv->vval.v_string = channel_read_block(channel, part,
3911 							 timeout, raw, NULL);
3912 	else
3913 	{
3914 	    if (opt.jo_set & JO_ID)
3915 		id = opt.jo_id;
3916 	    channel_read_json_block(channel, part, timeout, id, &listtv);
3917 	    if (listtv != NULL)
3918 	    {
3919 		*rettv = *listtv;
3920 		vim_free(listtv);
3921 	    }
3922 	    else
3923 	    {
3924 		rettv->v_type = VAR_SPECIAL;
3925 		rettv->vval.v_number = VVAL_NONE;
3926 	    }
3927 	}
3928     }
3929 
3930 theend:
3931     free_job_options(&opt);
3932 }
3933 
3934 #if defined(MSWIN) || defined(__HAIKU__) || defined(FEAT_GUI) || defined(PROTO)
3935 /*
3936  * Check the channels for anything that is ready to be read.
3937  * The data is put in the read queue.
3938  * if "only_keep_open" is TRUE only check channels where ch_keep_open is set.
3939  */
3940     void
channel_handle_events(int only_keep_open)3941 channel_handle_events(int only_keep_open)
3942 {
3943     channel_T	*channel;
3944     ch_part_T	part;
3945     sock_T	fd;
3946 
3947     FOR_ALL_CHANNELS(channel)
3948     {
3949 	if (only_keep_open && !channel->ch_keep_open)
3950 	    continue;
3951 
3952 	// check the socket and pipes
3953 	for (part = PART_SOCK; part < PART_IN; ++part)
3954 	{
3955 	    fd = channel->ch_part[part].ch_fd;
3956 	    if (fd != INVALID_FD)
3957 	    {
3958 		int r = channel_wait(channel, fd, 0);
3959 
3960 		if (r == CW_READY)
3961 		    channel_read(channel, part, "channel_handle_events");
3962 		else if (r == CW_ERROR)
3963 		    ch_close_part_on_error(channel, part, TRUE,
3964 						     "channel_handle_events");
3965 	    }
3966 	}
3967 
3968 # ifdef __HAIKU__
3969 	// Workaround for Haiku: Since select/poll cannot detect EOF from tty,
3970 	// should close fds when the job has finished if 'channel' connects to
3971 	// the pty.
3972 	if (channel->ch_job != NULL)
3973 	{
3974 	    job_T *job = channel->ch_job;
3975 
3976 	    if (job->jv_tty_out != NULL && job->jv_status == JOB_FINISHED)
3977 		for (part = PART_SOCK; part < PART_COUNT; ++part)
3978 		    ch_close_part(channel, part);
3979 	}
3980 # endif
3981     }
3982 }
3983 #endif
3984 
3985 # if defined(FEAT_GUI) || defined(PROTO)
3986 /*
3987  * Return TRUE when there is any channel with a keep_open flag.
3988  */
3989     int
channel_any_keep_open()3990 channel_any_keep_open()
3991 {
3992     channel_T	*channel;
3993 
3994     FOR_ALL_CHANNELS(channel)
3995 	if (channel->ch_keep_open)
3996 	    return TRUE;
3997     return FALSE;
3998 }
3999 # endif
4000 
4001 /*
4002  * Set "channel"/"part" to non-blocking.
4003  * Only works for sockets and pipes.
4004  */
4005     void
channel_set_nonblock(channel_T * channel,ch_part_T part)4006 channel_set_nonblock(channel_T *channel, ch_part_T part)
4007 {
4008     chanpart_T *ch_part = &channel->ch_part[part];
4009     int		fd = ch_part->ch_fd;
4010 
4011     if (fd != INVALID_FD)
4012     {
4013 #ifdef MSWIN
4014 	u_long	val = 1;
4015 
4016 	ioctlsocket(fd, FIONBIO, &val);
4017 #else
4018 	(void)fcntl(fd, F_SETFL, O_NONBLOCK);
4019 #endif
4020 	ch_part->ch_nonblocking = TRUE;
4021     }
4022 }
4023 
4024 /*
4025  * Write "buf" (NUL terminated string) to "channel"/"part".
4026  * When "fun" is not NULL an error message might be given.
4027  * Return FAIL or OK.
4028  */
4029     int
channel_send(channel_T * channel,ch_part_T part,char_u * buf_arg,int len_arg,char * fun)4030 channel_send(
4031 	channel_T *channel,
4032 	ch_part_T part,
4033 	char_u	  *buf_arg,
4034 	int	  len_arg,
4035 	char	  *fun)
4036 {
4037     int		res;
4038     sock_T	fd;
4039     chanpart_T	*ch_part = &channel->ch_part[part];
4040     int		did_use_queue = FALSE;
4041 
4042     fd = ch_part->ch_fd;
4043     if (fd == INVALID_FD)
4044     {
4045 	if (!channel->ch_error && fun != NULL)
4046 	{
4047 	    ch_error(channel, "%s(): write while not connected", fun);
4048 	    semsg(_("E630: %s(): write while not connected"), fun);
4049 	}
4050 	channel->ch_error = TRUE;
4051 	return FAIL;
4052     }
4053 
4054     if (channel->ch_nonblock && !ch_part->ch_nonblocking)
4055 	channel_set_nonblock(channel, part);
4056 
4057     if (ch_log_active())
4058     {
4059 	ch_log_lead("SEND ", channel, part);
4060 	fprintf(log_fd, "'");
4061 	vim_ignored = (int)fwrite(buf_arg, len_arg, 1, log_fd);
4062 	fprintf(log_fd, "'\n");
4063 	fflush(log_fd);
4064 	did_repeated_msg = 0;
4065     }
4066 
4067     for (;;)
4068     {
4069 	writeq_T    *wq = &ch_part->ch_writeque;
4070 	char_u	    *buf;
4071 	int	    len;
4072 
4073 	if (wq->wq_next != NULL)
4074 	{
4075 	    // first write what was queued
4076 	    buf = wq->wq_next->wq_ga.ga_data;
4077 	    len = wq->wq_next->wq_ga.ga_len;
4078 	    did_use_queue = TRUE;
4079 	}
4080 	else
4081 	{
4082 	    if (len_arg == 0)
4083 		// nothing to write, called from channel_select_check()
4084 		return OK;
4085 	    buf = buf_arg;
4086 	    len = len_arg;
4087 	}
4088 
4089 	if (part == PART_SOCK)
4090 	    res = sock_write(fd, (char *)buf, len);
4091 	else
4092 	{
4093 	    res = fd_write(fd, (char *)buf, len);
4094 #ifdef MSWIN
4095 	    if (channel->ch_named_pipe && res < 0)
4096 	    {
4097 		DisconnectNamedPipe((HANDLE)fd);
4098 		ConnectNamedPipe((HANDLE)fd, NULL);
4099 	    }
4100 #endif
4101 	}
4102 	if (res < 0 && (errno == EWOULDBLOCK
4103 #ifdef EAGAIN
4104 			|| errno == EAGAIN
4105 #endif
4106 		    ))
4107 	    res = 0; // nothing got written
4108 
4109 	if (res >= 0 && ch_part->ch_nonblocking)
4110 	{
4111 	    writeq_T *entry = wq->wq_next;
4112 
4113 	    if (did_use_queue)
4114 		ch_log(channel, "Sent %d bytes now", res);
4115 	    if (res == len)
4116 	    {
4117 		// Wrote all the buf[len] bytes.
4118 		if (entry != NULL)
4119 		{
4120 		    // Remove the entry from the write queue.
4121 		    remove_from_writeque(wq, entry);
4122 		    continue;
4123 		}
4124 		if (did_use_queue)
4125 		    ch_log(channel, "Write queue empty");
4126 	    }
4127 	    else
4128 	    {
4129 		// Wrote only buf[res] bytes, can't write more now.
4130 		if (entry != NULL)
4131 		{
4132 		    if (res > 0)
4133 		    {
4134 			// Remove the bytes that were written.
4135 			mch_memmove(entry->wq_ga.ga_data,
4136 				    (char *)entry->wq_ga.ga_data + res,
4137 				    len - res);
4138 			entry->wq_ga.ga_len -= res;
4139 		    }
4140 		    buf = buf_arg;
4141 		    len = len_arg;
4142 		}
4143 		else
4144 		{
4145 		    buf += res;
4146 		    len -= res;
4147 		}
4148 		ch_log(channel, "Adding %d bytes to the write queue", len);
4149 
4150 		// Append the not written bytes of the argument to the write
4151 		// buffer.  Limit entries to 4000 bytes.
4152 		if (wq->wq_prev != NULL
4153 			&& wq->wq_prev->wq_ga.ga_len + len < 4000)
4154 		{
4155 		    writeq_T *last = wq->wq_prev;
4156 
4157 		    // append to the last entry
4158 		    if (len > 0 && ga_grow(&last->wq_ga, len) == OK)
4159 		    {
4160 			mch_memmove((char *)last->wq_ga.ga_data
4161 							  + last->wq_ga.ga_len,
4162 				    buf, len);
4163 			last->wq_ga.ga_len += len;
4164 		    }
4165 		}
4166 		else
4167 		{
4168 		    writeq_T *last = ALLOC_ONE(writeq_T);
4169 
4170 		    if (last != NULL)
4171 		    {
4172 			last->wq_prev = wq->wq_prev;
4173 			last->wq_next = NULL;
4174 			if (wq->wq_prev == NULL)
4175 			    wq->wq_next = last;
4176 			else
4177 			    wq->wq_prev->wq_next = last;
4178 			wq->wq_prev = last;
4179 			ga_init2(&last->wq_ga, 1, 1000);
4180 			if (len > 0 && ga_grow(&last->wq_ga, len) == OK)
4181 			{
4182 			    mch_memmove(last->wq_ga.ga_data, buf, len);
4183 			    last->wq_ga.ga_len = len;
4184 			}
4185 		    }
4186 		}
4187 	    }
4188 	}
4189 	else if (res != len)
4190 	{
4191 	    if (!channel->ch_error && fun != NULL)
4192 	    {
4193 		ch_error(channel, "%s(): write failed", fun);
4194 		semsg(_("E631: %s(): write failed"), fun);
4195 	    }
4196 	    channel->ch_error = TRUE;
4197 	    return FAIL;
4198 	}
4199 
4200 	channel->ch_error = FALSE;
4201 	return OK;
4202     }
4203 }
4204 
4205 /*
4206  * Common for "ch_sendexpr()" and "ch_sendraw()".
4207  * Returns the channel if the caller should read the response.
4208  * Sets "part_read" to the read fd.
4209  * Otherwise returns NULL.
4210  */
4211     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)4212 send_common(
4213 	typval_T    *argvars,
4214 	char_u	    *text,
4215 	int	    len,
4216 	int	    id,
4217 	int	    eval,
4218 	jobopt_T    *opt,
4219 	char	    *fun,
4220 	ch_part_T   *part_read)
4221 {
4222     channel_T	*channel;
4223     ch_part_T	part_send;
4224 
4225     clear_job_options(opt);
4226     channel = get_channel_arg(&argvars[0], TRUE, FALSE, 0);
4227     if (channel == NULL)
4228 	return NULL;
4229     part_send = channel_part_send(channel);
4230     *part_read = channel_part_read(channel);
4231 
4232     if (get_job_options(&argvars[2], opt, JO_CALLBACK + JO_TIMEOUT, 0) == FAIL)
4233 	return NULL;
4234 
4235     // Set the callback. An empty callback means no callback and not reading
4236     // the response. With "ch_evalexpr()" and "ch_evalraw()" a callback is not
4237     // allowed.
4238     if (opt->jo_callback.cb_name != NULL && *opt->jo_callback.cb_name != NUL)
4239     {
4240 	if (eval)
4241 	{
4242 	    semsg(_("E917: Cannot use a callback with %s()"), fun);
4243 	    return NULL;
4244 	}
4245 	channel_set_req_callback(channel, *part_read, &opt->jo_callback, id);
4246     }
4247 
4248     if (channel_send(channel, part_send, text, len, fun) == OK
4249 					   && opt->jo_callback.cb_name == NULL)
4250 	return channel;
4251     return NULL;
4252 }
4253 
4254 /*
4255  * common for "ch_evalexpr()" and "ch_sendexpr()"
4256  */
4257     static void
ch_expr_common(typval_T * argvars,typval_T * rettv,int eval)4258 ch_expr_common(typval_T *argvars, typval_T *rettv, int eval)
4259 {
4260     char_u	*text;
4261     typval_T	*listtv;
4262     channel_T	*channel;
4263     int		id;
4264     ch_mode_T	ch_mode;
4265     ch_part_T	part_send;
4266     ch_part_T	part_read;
4267     jobopt_T    opt;
4268     int		timeout;
4269 
4270     // return an empty string by default
4271     rettv->v_type = VAR_STRING;
4272     rettv->vval.v_string = NULL;
4273 
4274     if (in_vim9script()
4275 	    && (check_for_chan_or_job_arg(argvars, 0) == FAIL
4276 		|| check_for_opt_dict_arg(argvars, 2) == FAIL))
4277 	return;
4278 
4279     channel = get_channel_arg(&argvars[0], TRUE, FALSE, 0);
4280     if (channel == NULL)
4281 	return;
4282     part_send = channel_part_send(channel);
4283 
4284     ch_mode = channel_get_mode(channel, part_send);
4285     if (ch_mode == MODE_RAW || ch_mode == MODE_NL)
4286     {
4287 	emsg(_("E912: cannot use ch_evalexpr()/ch_sendexpr() with a raw or nl channel"));
4288 	return;
4289     }
4290 
4291     id = ++channel->ch_last_msg_id;
4292     text = json_encode_nr_expr(id, &argvars[1],
4293 				 (ch_mode == MODE_JS ? JSON_JS : 0) | JSON_NL);
4294     if (text == NULL)
4295 	return;
4296 
4297     channel = send_common(argvars, text, (int)STRLEN(text), id, eval, &opt,
4298 			    eval ? "ch_evalexpr" : "ch_sendexpr", &part_read);
4299     vim_free(text);
4300     if (channel != NULL && eval)
4301     {
4302 	if (opt.jo_set & JO_TIMEOUT)
4303 	    timeout = opt.jo_timeout;
4304 	else
4305 	    timeout = channel_get_timeout(channel, part_read);
4306 	if (channel_read_json_block(channel, part_read, timeout, id, &listtv)
4307 									== OK)
4308 	{
4309 	    list_T *list = listtv->vval.v_list;
4310 
4311 	    // Move the item from the list and then change the type to
4312 	    // avoid the value being freed.
4313 	    *rettv = list->lv_u.mat.lv_last->li_tv;
4314 	    list->lv_u.mat.lv_last->li_tv.v_type = VAR_NUMBER;
4315 	    free_tv(listtv);
4316 	}
4317     }
4318     free_job_options(&opt);
4319 }
4320 
4321 /*
4322  * common for "ch_evalraw()" and "ch_sendraw()"
4323  */
4324     static void
ch_raw_common(typval_T * argvars,typval_T * rettv,int eval)4325 ch_raw_common(typval_T *argvars, typval_T *rettv, int eval)
4326 {
4327     char_u	buf[NUMBUFLEN];
4328     char_u	*text;
4329     int		len;
4330     channel_T	*channel;
4331     ch_part_T	part_read;
4332     jobopt_T    opt;
4333     int		timeout;
4334 
4335     // return an empty string by default
4336     rettv->v_type = VAR_STRING;
4337     rettv->vval.v_string = NULL;
4338 
4339     if (in_vim9script()
4340 	    && (check_for_chan_or_job_arg(argvars, 0) == FAIL
4341 		|| check_for_string_or_blob_arg(argvars, 1) == FAIL
4342 		|| check_for_opt_dict_arg(argvars, 2) == FAIL))
4343 	return;
4344 
4345     if (argvars[1].v_type == VAR_BLOB)
4346     {
4347 	text = argvars[1].vval.v_blob->bv_ga.ga_data;
4348 	len = argvars[1].vval.v_blob->bv_ga.ga_len;
4349     }
4350     else
4351     {
4352 	text = tv_get_string_buf(&argvars[1], buf);
4353 	len = (int)STRLEN(text);
4354     }
4355     channel = send_common(argvars, text, len, 0, eval, &opt,
4356 			      eval ? "ch_evalraw" : "ch_sendraw", &part_read);
4357     if (channel != NULL && eval)
4358     {
4359 	if (opt.jo_set & JO_TIMEOUT)
4360 	    timeout = opt.jo_timeout;
4361 	else
4362 	    timeout = channel_get_timeout(channel, part_read);
4363 	rettv->vval.v_string = channel_read_block(channel, part_read,
4364 							timeout, TRUE, NULL);
4365     }
4366     free_job_options(&opt);
4367 }
4368 
4369 #define KEEP_OPEN_TIME 20  // msec
4370 
4371 #if (defined(UNIX) && !defined(HAVE_SELECT)) || defined(PROTO)
4372 /*
4373  * Add open channels to the poll struct.
4374  * Return the adjusted struct index.
4375  * The type of "fds" is hidden to avoid problems with the function proto.
4376  */
4377     int
channel_poll_setup(int nfd_in,void * fds_in,int * towait)4378 channel_poll_setup(int nfd_in, void *fds_in, int *towait)
4379 {
4380     int		nfd = nfd_in;
4381     channel_T	*channel;
4382     struct	pollfd *fds = fds_in;
4383     ch_part_T	part;
4384 
4385     FOR_ALL_CHANNELS(channel)
4386     {
4387 	for (part = PART_SOCK; part < PART_IN; ++part)
4388 	{
4389 	    chanpart_T	*ch_part = &channel->ch_part[part];
4390 
4391 	    if (ch_part->ch_fd != INVALID_FD)
4392 	    {
4393 		if (channel->ch_keep_open)
4394 		{
4395 		    // For unknown reason poll() returns immediately for a
4396 		    // keep-open channel.  Instead of adding it to the fds add
4397 		    // a short timeout and check, like polling.
4398 		    if (*towait < 0 || *towait > KEEP_OPEN_TIME)
4399 			*towait = KEEP_OPEN_TIME;
4400 		}
4401 		else
4402 		{
4403 		    ch_part->ch_poll_idx = nfd;
4404 		    fds[nfd].fd = ch_part->ch_fd;
4405 		    fds[nfd].events = POLLIN;
4406 		    nfd++;
4407 		}
4408 	    }
4409 	    else
4410 		channel->ch_part[part].ch_poll_idx = -1;
4411 	}
4412     }
4413 
4414     nfd = channel_fill_poll_write(nfd, fds);
4415 
4416     return nfd;
4417 }
4418 
4419 /*
4420  * The type of "fds" is hidden to avoid problems with the function proto.
4421  */
4422     int
channel_poll_check(int ret_in,void * fds_in)4423 channel_poll_check(int ret_in, void *fds_in)
4424 {
4425     int		ret = ret_in;
4426     channel_T	*channel;
4427     struct	pollfd *fds = fds_in;
4428     ch_part_T	part;
4429     int		idx;
4430     chanpart_T	*in_part;
4431 
4432     FOR_ALL_CHANNELS(channel)
4433     {
4434 	for (part = PART_SOCK; part < PART_IN; ++part)
4435 	{
4436 	    idx = channel->ch_part[part].ch_poll_idx;
4437 
4438 	    if (ret > 0 && idx != -1 && (fds[idx].revents & POLLIN))
4439 	    {
4440 		channel_read(channel, part, "channel_poll_check");
4441 		--ret;
4442 	    }
4443 	    else if (channel->ch_part[part].ch_fd != INVALID_FD
4444 						      && channel->ch_keep_open)
4445 	    {
4446 		// polling a keep-open channel
4447 		channel_read(channel, part, "channel_poll_check_keep_open");
4448 	    }
4449 	}
4450 
4451 	in_part = &channel->ch_part[PART_IN];
4452 	idx = in_part->ch_poll_idx;
4453 	if (ret > 0 && idx != -1 && (fds[idx].revents & POLLOUT))
4454 	{
4455 	    channel_write_input(channel);
4456 	    --ret;
4457 	}
4458     }
4459 
4460     return ret;
4461 }
4462 #endif // UNIX && !HAVE_SELECT
4463 
4464 #if (!defined(MSWIN) && defined(HAVE_SELECT)) || defined(PROTO)
4465 
4466 /*
4467  * The "fd_set" type is hidden to avoid problems with the function proto.
4468  */
4469     int
channel_select_setup(int maxfd_in,void * rfds_in,void * wfds_in,struct timeval * tv,struct timeval ** tvp)4470 channel_select_setup(
4471 	int maxfd_in,
4472 	void *rfds_in,
4473 	void *wfds_in,
4474 	struct timeval *tv,
4475 	struct timeval **tvp)
4476 {
4477     int		maxfd = maxfd_in;
4478     channel_T	*channel;
4479     fd_set	*rfds = rfds_in;
4480     fd_set	*wfds = wfds_in;
4481     ch_part_T	part;
4482 
4483     FOR_ALL_CHANNELS(channel)
4484     {
4485 	for (part = PART_SOCK; part < PART_IN; ++part)
4486 	{
4487 	    sock_T fd = channel->ch_part[part].ch_fd;
4488 
4489 	    if (fd != INVALID_FD)
4490 	    {
4491 		if (channel->ch_keep_open)
4492 		{
4493 		    // For unknown reason select() returns immediately for a
4494 		    // keep-open channel.  Instead of adding it to the rfds add
4495 		    // a short timeout and check, like polling.
4496 		    if (*tvp == NULL || tv->tv_sec > 0
4497 					|| tv->tv_usec > KEEP_OPEN_TIME * 1000)
4498 		    {
4499 			*tvp = tv;
4500 			tv->tv_sec = 0;
4501 			tv->tv_usec = KEEP_OPEN_TIME * 1000;
4502 		    }
4503 		}
4504 		else
4505 		{
4506 		    FD_SET((int)fd, rfds);
4507 		    if (maxfd < (int)fd)
4508 			maxfd = (int)fd;
4509 		}
4510 	    }
4511 	}
4512     }
4513 
4514     maxfd = channel_fill_wfds(maxfd, wfds);
4515 
4516     return maxfd;
4517 }
4518 
4519 /*
4520  * The "fd_set" type is hidden to avoid problems with the function proto.
4521  */
4522     int
channel_select_check(int ret_in,void * rfds_in,void * wfds_in)4523 channel_select_check(int ret_in, void *rfds_in, void *wfds_in)
4524 {
4525     int		ret = ret_in;
4526     channel_T	*channel;
4527     fd_set	*rfds = rfds_in;
4528     fd_set	*wfds = wfds_in;
4529     ch_part_T	part;
4530     chanpart_T	*in_part;
4531 
4532     FOR_ALL_CHANNELS(channel)
4533     {
4534 	for (part = PART_SOCK; part < PART_IN; ++part)
4535 	{
4536 	    sock_T fd = channel->ch_part[part].ch_fd;
4537 
4538 	    if (ret > 0 && fd != INVALID_FD && FD_ISSET(fd, rfds))
4539 	    {
4540 		channel_read(channel, part, "channel_select_check");
4541 		FD_CLR(fd, rfds);
4542 		--ret;
4543 	    }
4544 	    else if (fd != INVALID_FD && channel->ch_keep_open)
4545 	    {
4546 		// polling a keep-open channel
4547 		channel_read(channel, part, "channel_select_check_keep_open");
4548 	    }
4549 	}
4550 
4551 	in_part = &channel->ch_part[PART_IN];
4552 	if (ret > 0 && in_part->ch_fd != INVALID_FD
4553 					    && FD_ISSET(in_part->ch_fd, wfds))
4554 	{
4555 	    // Clear the flag first, ch_fd may change in channel_write_input().
4556 	    FD_CLR(in_part->ch_fd, wfds);
4557 	    channel_write_input(channel);
4558 	    --ret;
4559 	}
4560 
4561 # ifdef __HAIKU__
4562 	// Workaround for Haiku: Since select/poll cannot detect EOF from tty,
4563 	// should close fds when the job has finished if 'channel' connects to
4564 	// the pty.
4565 	if (channel->ch_job != NULL)
4566 	{
4567 	    job_T *job = channel->ch_job;
4568 
4569 	    if (job->jv_tty_out != NULL && job->jv_status == JOB_FINISHED)
4570 		for (part = PART_SOCK; part < PART_COUNT; ++part)
4571 		    ch_close_part(channel, part);
4572 	}
4573 # endif
4574     }
4575 
4576     return ret;
4577 }
4578 #endif // !MSWIN && HAVE_SELECT
4579 
4580 /*
4581  * Execute queued up commands.
4582  * Invoked from the main loop when it's safe to execute received commands,
4583  * and during a blocking wait for ch_evalexpr().
4584  * Return TRUE when something was done.
4585  */
4586     int
channel_parse_messages(void)4587 channel_parse_messages(void)
4588 {
4589     channel_T	*channel = first_channel;
4590     int		ret = FALSE;
4591     int		r;
4592     ch_part_T	part = PART_SOCK;
4593     static int	recursive = 0;
4594 #ifdef ELAPSED_FUNC
4595     elapsed_T	start_tv;
4596 #endif
4597 
4598     // The code below may invoke callbacks, which might call us back.
4599     // In a recursive call channels will not be closed.
4600     ++recursive;
4601     ++safe_to_invoke_callback;
4602 
4603 #ifdef ELAPSED_FUNC
4604     ELAPSED_INIT(start_tv);
4605 #endif
4606 
4607     // Only do this message when another message was given, otherwise we get
4608     // lots of them.
4609     if ((did_repeated_msg & REPEATED_MSG_LOOKING) == 0)
4610     {
4611 	ch_log(NULL, "looking for messages on channels");
4612 	// now we should also give the message for SafeState
4613 	did_repeated_msg = REPEATED_MSG_LOOKING;
4614     }
4615     while (channel != NULL)
4616     {
4617 	if (recursive == 1)
4618 	{
4619 	    if (channel_can_close(channel))
4620 	    {
4621 		channel->ch_to_be_closed = (1U << PART_COUNT);
4622 		channel_close_now(channel);
4623 		// channel may have been freed, start over
4624 		channel = first_channel;
4625 		continue;
4626 	    }
4627 	    if (channel->ch_to_be_freed || channel->ch_killing)
4628 	    {
4629 		channel_free_contents(channel);
4630 		if (channel->ch_job != NULL)
4631 		    channel->ch_job->jv_channel = NULL;
4632 
4633 		// free the channel and then start over
4634 		channel_free_channel(channel);
4635 		channel = first_channel;
4636 		continue;
4637 	    }
4638 	    if (channel->ch_refcount == 0 && !channel_still_useful(channel))
4639 	    {
4640 		// channel is no longer useful, free it
4641 		channel_free(channel);
4642 		channel = first_channel;
4643 		part = PART_SOCK;
4644 		continue;
4645 	    }
4646 	}
4647 
4648 	if (channel->ch_part[part].ch_fd != INVALID_FD
4649 				      || channel_has_readahead(channel, part))
4650 	{
4651 	    // Increase the refcount, in case the handler causes the channel
4652 	    // to be unreferenced or closed.
4653 	    ++channel->ch_refcount;
4654 	    r = may_invoke_callback(channel, part);
4655 	    if (r == OK)
4656 		ret = TRUE;
4657 	    if (channel_unref(channel) || (r == OK
4658 #ifdef ELAPSED_FUNC
4659 			// Limit the time we loop here to 100 msec, otherwise
4660 			// Vim becomes unresponsive when the callback takes
4661 			// more than a bit of time.
4662 			&& ELAPSED_FUNC(start_tv) < 100L
4663 #endif
4664 			))
4665 	    {
4666 		// channel was freed or something was done, start over
4667 		channel = first_channel;
4668 		part = PART_SOCK;
4669 		continue;
4670 	    }
4671 	}
4672 	if (part < PART_ERR)
4673 	    ++part;
4674 	else
4675 	{
4676 	    channel = channel->ch_next;
4677 	    part = PART_SOCK;
4678 	}
4679     }
4680 
4681     if (channel_need_redraw)
4682     {
4683 	channel_need_redraw = FALSE;
4684 	redraw_after_callback(TRUE);
4685     }
4686 
4687     --safe_to_invoke_callback;
4688     --recursive;
4689 
4690     return ret;
4691 }
4692 
4693 /*
4694  * Return TRUE if any channel has readahead.  That means we should not block on
4695  * waiting for input.
4696  */
4697     int
channel_any_readahead(void)4698 channel_any_readahead(void)
4699 {
4700     channel_T	*channel = first_channel;
4701     ch_part_T	part = PART_SOCK;
4702 
4703     while (channel != NULL)
4704     {
4705 	if (channel_has_readahead(channel, part))
4706 	    return TRUE;
4707 	if (part < PART_ERR)
4708 	    ++part;
4709 	else
4710 	{
4711 	    channel = channel->ch_next;
4712 	    part = PART_SOCK;
4713 	}
4714     }
4715     return FALSE;
4716 }
4717 
4718 /*
4719  * Mark references to lists used in channels.
4720  */
4721     int
set_ref_in_channel(int copyID)4722 set_ref_in_channel(int copyID)
4723 {
4724     int		abort = FALSE;
4725     channel_T	*channel;
4726     typval_T	tv;
4727 
4728     for (channel = first_channel; !abort && channel != NULL;
4729 						   channel = channel->ch_next)
4730 	if (channel_still_useful(channel))
4731 	{
4732 	    tv.v_type = VAR_CHANNEL;
4733 	    tv.vval.v_channel = channel;
4734 	    abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4735 	}
4736     return abort;
4737 }
4738 
4739 /*
4740  * Return the "part" to write to for "channel".
4741  */
4742     static ch_part_T
channel_part_send(channel_T * channel)4743 channel_part_send(channel_T *channel)
4744 {
4745     if (channel->CH_SOCK_FD == INVALID_FD)
4746 	return PART_IN;
4747     return PART_SOCK;
4748 }
4749 
4750 /*
4751  * Return the default "part" to read from for "channel".
4752  */
4753     static ch_part_T
channel_part_read(channel_T * channel)4754 channel_part_read(channel_T *channel)
4755 {
4756     if (channel->CH_SOCK_FD == INVALID_FD)
4757 	return PART_OUT;
4758     return PART_SOCK;
4759 }
4760 
4761 /*
4762  * Return the mode of "channel"/"part"
4763  * If "channel" is invalid returns MODE_JSON.
4764  */
4765     static ch_mode_T
channel_get_mode(channel_T * channel,ch_part_T part)4766 channel_get_mode(channel_T *channel, ch_part_T part)
4767 {
4768     if (channel == NULL)
4769 	return MODE_JSON;
4770     return channel->ch_part[part].ch_mode;
4771 }
4772 
4773 /*
4774  * Return the timeout of "channel"/"part"
4775  */
4776     static int
channel_get_timeout(channel_T * channel,ch_part_T part)4777 channel_get_timeout(channel_T *channel, ch_part_T part)
4778 {
4779     return channel->ch_part[part].ch_timeout;
4780 }
4781 
4782 /*
4783  * "ch_canread()" function
4784  */
4785     void
f_ch_canread(typval_T * argvars,typval_T * rettv)4786 f_ch_canread(typval_T *argvars, typval_T *rettv)
4787 {
4788     channel_T *channel;
4789 
4790     rettv->vval.v_number = 0;
4791     if (in_vim9script() && check_for_chan_or_job_arg(argvars, 0) == FAIL)
4792 	return;
4793 
4794     channel = get_channel_arg(&argvars[0], FALSE, FALSE, 0);
4795     if (channel != NULL)
4796 	rettv->vval.v_number = channel_has_readahead(channel, PART_SOCK)
4797 			    || channel_has_readahead(channel, PART_OUT)
4798 			    || channel_has_readahead(channel, PART_ERR);
4799 }
4800 
4801 /*
4802  * "ch_close()" function
4803  */
4804     void
f_ch_close(typval_T * argvars,typval_T * rettv UNUSED)4805 f_ch_close(typval_T *argvars, typval_T *rettv UNUSED)
4806 {
4807     channel_T *channel;
4808 
4809     if (in_vim9script() && check_for_chan_or_job_arg(argvars, 0) == FAIL)
4810 	return;
4811 
4812     channel = get_channel_arg(&argvars[0], TRUE, FALSE, 0);
4813     if (channel != NULL)
4814     {
4815 	channel_close(channel, FALSE);
4816 	channel_clear(channel);
4817     }
4818 }
4819 
4820 /*
4821  * "ch_close()" function
4822  */
4823     void
f_ch_close_in(typval_T * argvars,typval_T * rettv UNUSED)4824 f_ch_close_in(typval_T *argvars, typval_T *rettv UNUSED)
4825 {
4826     channel_T *channel;
4827 
4828     if (in_vim9script() && check_for_chan_or_job_arg(argvars, 0) == FAIL)
4829 	return;
4830 
4831     channel = get_channel_arg(&argvars[0], TRUE, FALSE, 0);
4832     if (channel != NULL)
4833 	channel_close_in(channel);
4834 }
4835 
4836 /*
4837  * "ch_getbufnr()" function
4838  */
4839     void
f_ch_getbufnr(typval_T * argvars,typval_T * rettv)4840 f_ch_getbufnr(typval_T *argvars, typval_T *rettv)
4841 {
4842     channel_T *channel;
4843 
4844     rettv->vval.v_number = -1;
4845 
4846     if (in_vim9script()
4847 	    && (check_for_chan_or_job_arg(argvars, 0) == FAIL
4848 		|| check_for_string_arg(argvars, 1) == FAIL))
4849 	return;
4850 
4851     channel = get_channel_arg(&argvars[0], FALSE, FALSE, 0);
4852     if (channel != NULL)
4853     {
4854 	char_u	*what = tv_get_string(&argvars[1]);
4855 	int	part;
4856 
4857 	if (STRCMP(what, "err") == 0)
4858 	    part = PART_ERR;
4859 	else if (STRCMP(what, "out") == 0)
4860 	    part = PART_OUT;
4861 	else if (STRCMP(what, "in") == 0)
4862 	    part = PART_IN;
4863 	else
4864 	    part = PART_SOCK;
4865 	if (channel->ch_part[part].ch_bufref.br_buf != NULL)
4866 	    rettv->vval.v_number =
4867 			      channel->ch_part[part].ch_bufref.br_buf->b_fnum;
4868     }
4869 }
4870 
4871 /*
4872  * "ch_getjob()" function
4873  */
4874     void
f_ch_getjob(typval_T * argvars,typval_T * rettv)4875 f_ch_getjob(typval_T *argvars, typval_T *rettv)
4876 {
4877     channel_T *channel;
4878 
4879     if (in_vim9script() && check_for_chan_or_job_arg(argvars, 0) == FAIL)
4880 	return;
4881 
4882     channel = get_channel_arg(&argvars[0], FALSE, FALSE, 0);
4883     if (channel != NULL)
4884     {
4885 	rettv->v_type = VAR_JOB;
4886 	rettv->vval.v_job = channel->ch_job;
4887 	if (channel->ch_job != NULL)
4888 	    ++channel->ch_job->jv_refcount;
4889     }
4890 }
4891 
4892 /*
4893  * "ch_info()" function
4894  */
4895     void
f_ch_info(typval_T * argvars,typval_T * rettv UNUSED)4896 f_ch_info(typval_T *argvars, typval_T *rettv UNUSED)
4897 {
4898     channel_T *channel;
4899 
4900     if (in_vim9script() && check_for_chan_or_job_arg(argvars, 0) == FAIL)
4901 	return;
4902 
4903     channel = get_channel_arg(&argvars[0], FALSE, FALSE, 0);
4904     if (channel != NULL && rettv_dict_alloc(rettv) != FAIL)
4905 	channel_info(channel, rettv->vval.v_dict);
4906 }
4907 
4908 /*
4909  * "ch_log()" function
4910  */
4911     void
f_ch_log(typval_T * argvars,typval_T * rettv UNUSED)4912 f_ch_log(typval_T *argvars, typval_T *rettv UNUSED)
4913 {
4914     char_u	*msg;
4915     channel_T	*channel = NULL;
4916 
4917     if (in_vim9script()
4918 	    && (check_for_string_arg(argvars, 0) == FAIL
4919 		|| check_for_opt_chan_or_job_arg(argvars, 1) == FAIL))
4920 	return;
4921 
4922     msg = tv_get_string(&argvars[0]);
4923     if (argvars[1].v_type != VAR_UNKNOWN)
4924 	channel = get_channel_arg(&argvars[1], FALSE, FALSE, 0);
4925 
4926     ch_log(channel, "%s", msg);
4927 }
4928 
4929 /*
4930  * "ch_logfile()" function
4931  */
4932     void
f_ch_logfile(typval_T * argvars,typval_T * rettv UNUSED)4933 f_ch_logfile(typval_T *argvars, typval_T *rettv UNUSED)
4934 {
4935     char_u *fname;
4936     char_u *opt = (char_u *)"";
4937     char_u buf[NUMBUFLEN];
4938 
4939     // Don't open a file in restricted mode.
4940     if (check_restricted() || check_secure())
4941 	return;
4942 
4943     if (in_vim9script()
4944 	    && (check_for_string_arg(argvars, 0) == FAIL
4945 		|| check_for_opt_string_arg(argvars, 1) == FAIL))
4946 	return;
4947 
4948     fname = tv_get_string(&argvars[0]);
4949     if (argvars[1].v_type == VAR_STRING)
4950 	opt = tv_get_string_buf(&argvars[1], buf);
4951     ch_logfile(fname, opt);
4952 }
4953 
4954 /*
4955  * "ch_open()" function
4956  */
4957     void
f_ch_open(typval_T * argvars,typval_T * rettv)4958 f_ch_open(typval_T *argvars, typval_T *rettv)
4959 {
4960     rettv->v_type = VAR_CHANNEL;
4961     if (check_restricted() || check_secure())
4962 	return;
4963     rettv->vval.v_channel = channel_open_func(argvars);
4964 }
4965 
4966 /*
4967  * "ch_read()" function
4968  */
4969     void
f_ch_read(typval_T * argvars,typval_T * rettv)4970 f_ch_read(typval_T *argvars, typval_T *rettv)
4971 {
4972     common_channel_read(argvars, rettv, FALSE, FALSE);
4973 }
4974 
4975 /*
4976  * "ch_readblob()" function
4977  */
4978     void
f_ch_readblob(typval_T * argvars,typval_T * rettv)4979 f_ch_readblob(typval_T *argvars, typval_T *rettv)
4980 {
4981     common_channel_read(argvars, rettv, TRUE, TRUE);
4982 }
4983 
4984 /*
4985  * "ch_readraw()" function
4986  */
4987     void
f_ch_readraw(typval_T * argvars,typval_T * rettv)4988 f_ch_readraw(typval_T *argvars, typval_T *rettv)
4989 {
4990     common_channel_read(argvars, rettv, TRUE, FALSE);
4991 }
4992 
4993 /*
4994  * "ch_evalexpr()" function
4995  */
4996     void
f_ch_evalexpr(typval_T * argvars,typval_T * rettv)4997 f_ch_evalexpr(typval_T *argvars, typval_T *rettv)
4998 {
4999     ch_expr_common(argvars, rettv, TRUE);
5000 }
5001 
5002 /*
5003  * "ch_sendexpr()" function
5004  */
5005     void
f_ch_sendexpr(typval_T * argvars,typval_T * rettv)5006 f_ch_sendexpr(typval_T *argvars, typval_T *rettv)
5007 {
5008     ch_expr_common(argvars, rettv, FALSE);
5009 }
5010 
5011 /*
5012  * "ch_evalraw()" function
5013  */
5014     void
f_ch_evalraw(typval_T * argvars,typval_T * rettv)5015 f_ch_evalraw(typval_T *argvars, typval_T *rettv)
5016 {
5017     ch_raw_common(argvars, rettv, TRUE);
5018 }
5019 
5020 /*
5021  * "ch_sendraw()" function
5022  */
5023     void
f_ch_sendraw(typval_T * argvars,typval_T * rettv)5024 f_ch_sendraw(typval_T *argvars, typval_T *rettv)
5025 {
5026     ch_raw_common(argvars, rettv, FALSE);
5027 }
5028 
5029 /*
5030  * "ch_setoptions()" function
5031  */
5032     void
f_ch_setoptions(typval_T * argvars,typval_T * rettv UNUSED)5033 f_ch_setoptions(typval_T *argvars, typval_T *rettv UNUSED)
5034 {
5035     channel_T	*channel;
5036     jobopt_T	opt;
5037 
5038     if (in_vim9script()
5039 	    && (check_for_chan_or_job_arg(argvars, 0) == FAIL
5040 		|| check_for_dict_arg(argvars, 1) == FAIL))
5041 	return;
5042 
5043     channel = get_channel_arg(&argvars[0], FALSE, FALSE, 0);
5044     if (channel == NULL)
5045 	return;
5046     clear_job_options(&opt);
5047     if (get_job_options(&argvars[1], &opt,
5048 			    JO_CB_ALL + JO_TIMEOUT_ALL + JO_MODE_ALL, 0) == OK)
5049 	channel_set_options(channel, &opt);
5050     free_job_options(&opt);
5051 }
5052 
5053 /*
5054  * "ch_status()" function
5055  */
5056     void
f_ch_status(typval_T * argvars,typval_T * rettv)5057 f_ch_status(typval_T *argvars, typval_T *rettv)
5058 {
5059     channel_T	*channel;
5060     jobopt_T	opt;
5061     int		part = -1;
5062 
5063     // return an empty string by default
5064     rettv->v_type = VAR_STRING;
5065     rettv->vval.v_string = NULL;
5066 
5067     if (in_vim9script()
5068 	    && (check_for_chan_or_job_arg(argvars, 0) == FAIL
5069 		|| check_for_opt_dict_arg(argvars, 1) == FAIL))
5070 	return;
5071 
5072     channel = get_channel_arg(&argvars[0], FALSE, FALSE, 0);
5073 
5074     if (argvars[1].v_type != VAR_UNKNOWN)
5075     {
5076 	clear_job_options(&opt);
5077 	if (get_job_options(&argvars[1], &opt, JO_PART, 0) == OK
5078 						     && (opt.jo_set & JO_PART))
5079 	    part = opt.jo_part;
5080     }
5081 
5082     rettv->vval.v_string = vim_strsave((char_u *)channel_status(channel, part));
5083 }
5084 
5085 /*
5086  * Get a string with information about the channel in "varp" in "buf".
5087  * "buf" must be at least NUMBUFLEN long.
5088  */
5089     char_u *
channel_to_string_buf(typval_T * varp,char_u * buf)5090 channel_to_string_buf(typval_T *varp, char_u *buf)
5091 {
5092     channel_T *channel = varp->vval.v_channel;
5093     char      *status = channel_status(channel, -1);
5094 
5095     if (channel == NULL)
5096 	vim_snprintf((char *)buf, NUMBUFLEN, "channel %s", status);
5097     else
5098 	vim_snprintf((char *)buf, NUMBUFLEN,
5099 				      "channel %d %s", channel->ch_id, status);
5100     return buf;
5101 }
5102 
5103 #endif // FEAT_JOB_CHANNEL
5104