forked from vim/vim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel.c
5103 lines (4577 loc) · 120 KB
/
channel.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* vi:set ts=8 sts=4 sw=4 noet:
*
* VIM - Vi IMproved by Bram Moolenaar
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
*/
/*
* Implements communication through a socket or any file handle.
*/
#ifdef WIN32
// Must include winsock2.h before windows.h since it conflicts with winsock.h
// (included in windows.h).
# include <winsock2.h>
# include <ws2tcpip.h>
#endif
#include "vim.h"
#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
// TRUE when netbeans is running with a GUI.
#ifdef FEAT_GUI
# define CH_HAS_GUI (gui.in_use || gui.starting)
#endif
// Note: when making changes here also adjust configure.ac.
#ifdef MSWIN
// WinSock API is separated from C API, thus we can't use read(), write(),
// errno...
# define SOCK_ERRNO errno = WSAGetLastError()
# undef ECONNREFUSED
# define ECONNREFUSED WSAECONNREFUSED
# undef EWOULDBLOCK
# define EWOULDBLOCK WSAEWOULDBLOCK
# undef EINPROGRESS
# define EINPROGRESS WSAEINPROGRESS
# ifdef EINTR
# undef EINTR
# endif
# define EINTR WSAEINTR
# define sock_write(sd, buf, len) send((SOCKET)sd, buf, len, 0)
# define sock_read(sd, buf, len) recv((SOCKET)sd, buf, len, 0)
# define sock_close(sd) closesocket((SOCKET)sd)
#else
# include <netdb.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# include <sys/socket.h>
# ifdef HAVE_LIBGEN_H
# include <libgen.h>
# endif
# define SOCK_ERRNO
# define sock_write(sd, buf, len) write(sd, buf, len)
# define sock_read(sd, buf, len) read(sd, buf, len)
# define sock_close(sd) close(sd)
# define fd_read(fd, buf, len) read(fd, buf, len)
# define fd_write(sd, buf, len) write(sd, buf, len)
# define fd_close(sd) close(sd)
#endif
static void channel_read(channel_T *channel, ch_part_T part, char *func);
static ch_mode_T channel_get_mode(channel_T *channel, ch_part_T part);
static int channel_get_timeout(channel_T *channel, ch_part_T part);
static ch_part_T channel_part_send(channel_T *channel);
static ch_part_T channel_part_read(channel_T *channel);
#define FOR_ALL_CHANNELS(ch) \
for ((ch) = first_channel; (ch) != NULL; (ch) = (ch)->ch_next)
// Whether we are inside channel_parse_messages() or another situation where it
// is safe to invoke callbacks.
static int safe_to_invoke_callback = 0;
static char *part_names[] = {"sock", "out", "err", "in"};
#ifdef MSWIN
static int
fd_read(sock_T fd, char *buf, size_t len)
{
HANDLE h = (HANDLE)fd;
DWORD nread;
if (!ReadFile(h, buf, (DWORD)len, &nread, NULL))
return -1;
return (int)nread;
}
static int
fd_write(sock_T fd, char *buf, size_t len)
{
size_t todo = len;
HANDLE h = (HANDLE)fd;
DWORD nwrite, size, done = 0;
OVERLAPPED ov;
while (todo > 0)
{
if (todo > MAX_NAMED_PIPE_SIZE)
size = MAX_NAMED_PIPE_SIZE;
else
size = (DWORD)todo;
// If the pipe overflows while the job does not read the data,
// WriteFile() will block forever. This abandons the write.
memset(&ov, 0, sizeof(ov));
nwrite = 0;
if (!WriteFile(h, buf + done, size, &nwrite, &ov))
{
DWORD err = GetLastError();
if (err != ERROR_IO_PENDING)
return -1;
if (!GetOverlappedResult(h, &ov, &nwrite, FALSE))
return -1;
FlushFileBuffers(h);
}
else if (nwrite == 0)
// WriteFile() returns TRUE but did not write anything. This causes
// a hang, so bail out.
break;
todo -= nwrite;
done += nwrite;
}
return (int)done;
}
static void
fd_close(sock_T fd)
{
HANDLE h = (HANDLE)fd;
CloseHandle(h);
}
#endif
// Log file opened with ch_logfile().
static FILE *log_fd = NULL;
static char_u *log_name = NULL;
#ifdef FEAT_RELTIME
static proftime_T log_start;
#endif
void
ch_logfile(char_u *fname, char_u *opt)
{
FILE *file = NULL;
if (log_fd != NULL)
{
if (*fname != NUL)
ch_log(NULL, "closing this logfile, opening %s", fname);
else
ch_log(NULL, "closing logfile %s", log_name);
fclose(log_fd);
}
if (*fname != NUL)
{
file = fopen((char *)fname, *opt == 'w' ? "w" : "a");
if (file == NULL)
{
semsg(_(e_notopen), fname);
return;
}
vim_free(log_name);
log_name = vim_strsave(fname);
}
log_fd = file;
if (log_fd != NULL)
{
fprintf(log_fd, "==== start log session ====\n");
#ifdef FEAT_RELTIME
profile_start(&log_start);
#endif
}
}
int
ch_log_active(void)
{
return log_fd != NULL;
}
static void
ch_log_lead(const char *what, channel_T *ch, ch_part_T part)
{
if (log_fd != NULL)
{
#ifdef FEAT_RELTIME
proftime_T log_now;
profile_start(&log_now);
profile_sub(&log_now, &log_start);
fprintf(log_fd, "%s ", profile_msg(&log_now));
#endif
if (ch != NULL)
{
if (part < PART_COUNT)
fprintf(log_fd, "%son %d(%s): ",
what, ch->ch_id, part_names[part]);
else
fprintf(log_fd, "%son %d: ", what, ch->ch_id);
}
else
fprintf(log_fd, "%s: ", what);
}
}
#ifndef PROTO // prototype is in proto.h
void
ch_log(channel_T *ch, const char *fmt, ...)
{
if (log_fd != NULL)
{
va_list ap;
ch_log_lead("", ch, PART_COUNT);
va_start(ap, fmt);
vfprintf(log_fd, fmt, ap);
va_end(ap);
fputc('\n', log_fd);
fflush(log_fd);
did_repeated_msg = 0;
}
}
#endif
static void
ch_error(channel_T *ch, const char *fmt, ...) ATTRIBUTE_FORMAT_PRINTF(2, 3);
static void
ch_error(channel_T *ch, const char *fmt, ...)
{
if (log_fd != NULL)
{
va_list ap;
ch_log_lead("ERR ", ch, PART_COUNT);
va_start(ap, fmt);
vfprintf(log_fd, fmt, ap);
va_end(ap);
fputc('\n', log_fd);
fflush(log_fd);
did_repeated_msg = 0;
}
}
#ifdef MSWIN
# undef PERROR
# define PERROR(msg) (void)semsg("%s: %s", msg, strerror_win32(errno))
static char *
strerror_win32(int eno)
{
static LPVOID msgbuf = NULL;
char_u *ptr;
if (msgbuf)
{
LocalFree(msgbuf);
msgbuf = NULL;
}
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
eno,
MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
(LPTSTR) &msgbuf,
0,
NULL);
if (msgbuf != NULL)
// chomp \r or \n
for (ptr = (char_u *)msgbuf; *ptr; ptr++)
switch (*ptr)
{
case '\r':
STRMOVE(ptr, ptr + 1);
ptr--;
break;
case '\n':
if (*(ptr + 1) == '\0')
*ptr = '\0';
else
*ptr = ' ';
break;
}
return msgbuf;
}
#endif
/*
* The list of all allocated channels.
*/
static channel_T *first_channel = NULL;
static int next_ch_id = 0;
/*
* Allocate a new channel. The refcount is set to 1.
* The channel isn't actually used until it is opened.
* Returns NULL if out of memory.
*/
channel_T *
add_channel(void)
{
ch_part_T part;
channel_T *channel = ALLOC_CLEAR_ONE(channel_T);
if (channel == NULL)
return NULL;
channel->ch_id = next_ch_id++;
ch_log(channel, "Created channel");
for (part = PART_SOCK; part < PART_COUNT; ++part)
{
channel->ch_part[part].ch_fd = INVALID_FD;
#ifdef FEAT_GUI_X11
channel->ch_part[part].ch_inputHandler = (XtInputId)NULL;
#endif
#ifdef FEAT_GUI_GTK
channel->ch_part[part].ch_inputHandler = 0;
#endif
channel->ch_part[part].ch_timeout = 2000;
}
if (first_channel != NULL)
{
first_channel->ch_prev = channel;
channel->ch_next = first_channel;
}
first_channel = channel;
channel->ch_refcount = 1;
return channel;
}
int
has_any_channel(void)
{
return first_channel != NULL;
}
/*
* Called when the refcount of a channel is zero.
* Return TRUE if "channel" has a callback and the associated job wasn't
* killed.
*/
int
channel_still_useful(channel_T *channel)
{
int has_sock_msg;
int has_out_msg;
int has_err_msg;
// If the job was killed the channel is not expected to work anymore.
if (channel->ch_job_killed && channel->ch_job == NULL)
return FALSE;
// If there is a close callback it may still need to be invoked.
if (channel->ch_close_cb.cb_name != NULL)
return TRUE;
// If reading from or a buffer it's still useful.
if (channel->ch_part[PART_IN].ch_bufref.br_buf != NULL)
return TRUE;
// If there is no callback then nobody can get readahead. If the fd is
// closed and there is no readahead then the callback won't be called.
has_sock_msg = channel->ch_part[PART_SOCK].ch_fd != INVALID_FD
|| channel->ch_part[PART_SOCK].ch_head.rq_next != NULL
|| channel->ch_part[PART_SOCK].ch_json_head.jq_next != NULL;
has_out_msg = channel->ch_part[PART_OUT].ch_fd != INVALID_FD
|| channel->ch_part[PART_OUT].ch_head.rq_next != NULL
|| channel->ch_part[PART_OUT].ch_json_head.jq_next != NULL;
has_err_msg = channel->ch_part[PART_ERR].ch_fd != INVALID_FD
|| channel->ch_part[PART_ERR].ch_head.rq_next != NULL
|| channel->ch_part[PART_ERR].ch_json_head.jq_next != NULL;
return (channel->ch_callback.cb_name != NULL && (has_sock_msg
|| has_out_msg || has_err_msg))
|| ((channel->ch_part[PART_OUT].ch_callback.cb_name != NULL
|| channel->ch_part[PART_OUT].ch_bufref.br_buf != NULL)
&& has_out_msg)
|| ((channel->ch_part[PART_ERR].ch_callback.cb_name != NULL
|| channel->ch_part[PART_ERR].ch_bufref.br_buf != NULL)
&& has_err_msg);
}
/*
* Return TRUE if "channel" is closeable (i.e. all readable fds are closed).
*/
int
channel_can_close(channel_T *channel)
{
return channel->ch_to_be_closed == 0;
}
/*
* Close a channel and free all its resources.
* The "channel" pointer remains valid.
*/
static void
channel_free_contents(channel_T *channel)
{
channel_close(channel, TRUE);
channel_clear(channel);
ch_log(channel, "Freeing channel");
}
/*
* Unlink "channel" from the list of channels and free it.
*/
static void
channel_free_channel(channel_T *channel)
{
if (channel->ch_next != NULL)
channel->ch_next->ch_prev = channel->ch_prev;
if (channel->ch_prev == NULL)
first_channel = channel->ch_next;
else
channel->ch_prev->ch_next = channel->ch_next;
vim_free(channel);
}
static void
channel_free(channel_T *channel)
{
if (!in_free_unref_items)
{
if (safe_to_invoke_callback == 0)
channel->ch_to_be_freed = TRUE;
else
{
channel_free_contents(channel);
channel_free_channel(channel);
}
}
}
/*
* Close a channel and free all its resources if there is no further action
* possible, there is no callback to be invoked or the associated job was
* killed.
* Return TRUE if the channel was freed.
*/
static int
channel_may_free(channel_T *channel)
{
if (!channel_still_useful(channel))
{
channel_free(channel);
return TRUE;
}
return FALSE;
}
/*
* Decrement the reference count on "channel" and maybe free it when it goes
* down to zero. Don't free it if there is a pending action.
* Returns TRUE when the channel is no longer referenced.
*/
int
channel_unref(channel_T *channel)
{
if (channel != NULL && --channel->ch_refcount <= 0)
return channel_may_free(channel);
return FALSE;
}
int
free_unused_channels_contents(int copyID, int mask)
{
int did_free = FALSE;
channel_T *ch;
// This is invoked from the garbage collector, which only runs at a safe
// point.
++safe_to_invoke_callback;
FOR_ALL_CHANNELS(ch)
if (!channel_still_useful(ch)
&& (ch->ch_copyID & mask) != (copyID & mask))
{
// Free the channel and ordinary items it contains, but don't
// recurse into Lists, Dictionaries etc.
channel_free_contents(ch);
did_free = TRUE;
}
--safe_to_invoke_callback;
return did_free;
}
void
free_unused_channels(int copyID, int mask)
{
channel_T *ch;
channel_T *ch_next;
for (ch = first_channel; ch != NULL; ch = ch_next)
{
ch_next = ch->ch_next;
if (!channel_still_useful(ch)
&& (ch->ch_copyID & mask) != (copyID & mask))
// Free the channel struct itself.
channel_free_channel(ch);
}
}
#if defined(FEAT_GUI) || defined(PROTO)
# if defined(FEAT_GUI_X11) || defined(FEAT_GUI_GTK)
/*
* Lookup the channel from the socket. Set "partp" to the fd index.
* Returns NULL when the socket isn't found.
*/
static channel_T *
channel_fd2channel(sock_T fd, ch_part_T *partp)
{
channel_T *channel;
ch_part_T part;
if (fd != INVALID_FD)
FOR_ALL_CHANNELS(channel)
{
for (part = PART_SOCK; part < PART_IN; ++part)
if (channel->ch_part[part].ch_fd == fd)
{
*partp = part;
return channel;
}
}
return NULL;
}
static void
channel_read_fd(int fd)
{
channel_T *channel;
ch_part_T part;
channel = channel_fd2channel(fd, &part);
if (channel == NULL)
ch_error(NULL, "Channel for fd %d not found", fd);
else
channel_read(channel, part, "channel_read_fd");
}
# endif
/*
* Read a command from netbeans.
*/
# ifdef FEAT_GUI_X11
static void
messageFromServerX11(XtPointer clientData,
int *unused1 UNUSED,
XtInputId *unused2 UNUSED)
{
channel_read_fd((int)(long)clientData);
}
# endif
# ifdef FEAT_GUI_GTK
# if GTK_CHECK_VERSION(3,0,0)
static gboolean
messageFromServerGtk3(GIOChannel *unused1 UNUSED,
GIOCondition unused2 UNUSED,
gpointer clientData)
{
channel_read_fd(GPOINTER_TO_INT(clientData));
return TRUE; // Return FALSE instead in case the event source is to
// be removed after this function returns.
}
# else
static void
messageFromServerGtk2(gpointer clientData,
gint unused1 UNUSED,
GdkInputCondition unused2 UNUSED)
{
channel_read_fd((int)(long)clientData);
}
# endif
# endif
static void
channel_gui_register_one(channel_T *channel, ch_part_T part UNUSED)
{
if (!CH_HAS_GUI)
return;
// gets stuck in handling events for a not connected channel
if (channel->ch_keep_open)
return;
# ifdef FEAT_GUI_X11
// Tell notifier we are interested in being called when there is input on
// the editor connection socket.
if (channel->ch_part[part].ch_inputHandler == (XtInputId)NULL)
{
ch_log(channel, "Registering part %s with fd %d",
part_names[part], channel->ch_part[part].ch_fd);
channel->ch_part[part].ch_inputHandler = XtAppAddInput(
(XtAppContext)app_context,
channel->ch_part[part].ch_fd,
(XtPointer)(XtInputReadMask + XtInputExceptMask),
messageFromServerX11,
(XtPointer)(long)channel->ch_part[part].ch_fd);
}
# else
# ifdef FEAT_GUI_GTK
// Tell gdk we are interested in being called when there is input on the
// editor connection socket.
if (channel->ch_part[part].ch_inputHandler == 0)
{
ch_log(channel, "Registering part %s with fd %d",
part_names[part], channel->ch_part[part].ch_fd);
# if GTK_CHECK_VERSION(3,0,0)
GIOChannel *chnnl = g_io_channel_unix_new(
(gint)channel->ch_part[part].ch_fd);
channel->ch_part[part].ch_inputHandler = g_io_add_watch(
chnnl,
G_IO_IN|G_IO_HUP|G_IO_ERR|G_IO_PRI,
messageFromServerGtk3,
GINT_TO_POINTER(channel->ch_part[part].ch_fd));
g_io_channel_unref(chnnl);
# else
channel->ch_part[part].ch_inputHandler = gdk_input_add(
(gint)channel->ch_part[part].ch_fd,
(GdkInputCondition)
((int)GDK_INPUT_READ + (int)GDK_INPUT_EXCEPTION),
messageFromServerGtk2,
(gpointer)(long)channel->ch_part[part].ch_fd);
# endif
}
# endif
# endif
}
static void
channel_gui_register(channel_T *channel)
{
if (channel->CH_SOCK_FD != INVALID_FD)
channel_gui_register_one(channel, PART_SOCK);
if (channel->CH_OUT_FD != INVALID_FD
&& channel->CH_OUT_FD != channel->CH_SOCK_FD)
channel_gui_register_one(channel, PART_OUT);
if (channel->CH_ERR_FD != INVALID_FD
&& channel->CH_ERR_FD != channel->CH_SOCK_FD
&& channel->CH_ERR_FD != channel->CH_OUT_FD)
channel_gui_register_one(channel, PART_ERR);
}
/*
* Register any of our file descriptors with the GUI event handling system.
* Called when the GUI has started.
*/
void
channel_gui_register_all(void)
{
channel_T *channel;
FOR_ALL_CHANNELS(channel)
channel_gui_register(channel);
}
static void
channel_gui_unregister_one(channel_T *channel UNUSED, ch_part_T part UNUSED)
{
# ifdef FEAT_GUI_X11
if (channel->ch_part[part].ch_inputHandler != (XtInputId)NULL)
{
ch_log(channel, "Unregistering part %s", part_names[part]);
XtRemoveInput(channel->ch_part[part].ch_inputHandler);
channel->ch_part[part].ch_inputHandler = (XtInputId)NULL;
}
# else
# ifdef FEAT_GUI_GTK
if (channel->ch_part[part].ch_inputHandler != 0)
{
ch_log(channel, "Unregistering part %s", part_names[part]);
# if GTK_CHECK_VERSION(3,0,0)
g_source_remove(channel->ch_part[part].ch_inputHandler);
# else
gdk_input_remove(channel->ch_part[part].ch_inputHandler);
# endif
channel->ch_part[part].ch_inputHandler = 0;
}
# endif
# endif
}
static void
channel_gui_unregister(channel_T *channel)
{
ch_part_T part;
for (part = PART_SOCK; part < PART_IN; ++part)
channel_gui_unregister_one(channel, part);
}
#endif // FEAT_GUI
static char *e_cannot_connect = N_("E902: Cannot connect to port");
/*
* For Unix we need to call connect() again after connect() failed.
* On Win32 one time is sufficient.
*/
static int
channel_connect(
channel_T *channel,
const struct sockaddr *server_addr,
int server_addrlen,
int *waittime)
{
int sd = -1;
#ifdef MSWIN
u_long val = 1;
#endif
while (TRUE)
{
long elapsed_msec = 0;
int waitnow;
int ret;
if (sd >= 0)
sock_close(sd);
sd = socket(server_addr->sa_family, SOCK_STREAM, 0);
if (sd == -1)
{
ch_error(channel, "in socket() in channel_connect().");
PERROR(_("E898: socket() in channel_connect()"));
return -1;
}
if (*waittime >= 0)
{
// Make connect() non-blocking.
if (
#ifdef MSWIN
ioctlsocket(sd, FIONBIO, &val) < 0
#else
fcntl(sd, F_SETFL, O_NONBLOCK) < 0
#endif
)
{
SOCK_ERRNO;
ch_error(channel,
"channel_connect: Connect failed with errno %d", errno);
sock_close(sd);
return -1;
}
}
// Try connecting to the server.
ch_log(channel, "Connecting...");
ret = connect(sd, server_addr, server_addrlen);
if (ret == 0)
// The connection could be established.
break;
SOCK_ERRNO;
if (*waittime < 0 || (errno != EWOULDBLOCK
&& errno != ECONNREFUSED
#ifdef EINPROGRESS
&& errno != EINPROGRESS
#endif
))
{
ch_error(channel,
"channel_connect: Connect failed with errno %d", errno);
PERROR(_(e_cannot_connect));
sock_close(sd);
return -1;
}
else if (errno == ECONNREFUSED)
{
ch_error(channel, "channel_connect: Connection refused");
sock_close(sd);
return -1;
}
// Limit the waittime to 50 msec. If it doesn't work within this
// time we close the socket and try creating it again.
waitnow = *waittime > 50 ? 50 : *waittime;
// If connect() didn't finish then try using select() to wait for the
// connection to be made. For Win32 always use select() to wait.
{
struct timeval tv;
fd_set rfds;
fd_set wfds;
#ifndef MSWIN
int so_error = 0;
socklen_t so_error_len = sizeof(so_error);
struct timeval start_tv;
struct timeval end_tv;
#endif
FD_ZERO(&rfds);
FD_SET(sd, &rfds);
FD_ZERO(&wfds);
FD_SET(sd, &wfds);
tv.tv_sec = waitnow / 1000;
tv.tv_usec = (waitnow % 1000) * 1000;
#ifndef MSWIN
gettimeofday(&start_tv, NULL);
#endif
ch_log(channel,
"Waiting for connection (waiting %d msec)...", waitnow);
ret = select((int)sd + 1, &rfds, &wfds, NULL, &tv);
if (ret < 0)
{
SOCK_ERRNO;
ch_error(channel,
"channel_connect: Connect failed with errno %d", errno);
PERROR(_(e_cannot_connect));
sock_close(sd);
return -1;
}
#ifdef MSWIN
// On Win32: select() is expected to work and wait for up to
// "waitnow" msec for the socket to be open.
if (FD_ISSET(sd, &wfds))
break;
elapsed_msec = waitnow;
if (*waittime > 1 && elapsed_msec < *waittime)
{
*waittime -= elapsed_msec;
continue;
}
#else
// On Linux-like systems: See socket(7) for the behavior
// After putting the socket in non-blocking mode, connect() will
// return EINPROGRESS, select() will not wait (as if writing is
// possible), need to use getsockopt() to check if the socket is
// actually able to connect.
// We detect a failure to connect when either read and write fds
// are set. Use getsockopt() to find out what kind of failure.
if (FD_ISSET(sd, &rfds) || FD_ISSET(sd, &wfds))
{
ret = getsockopt(sd,
SOL_SOCKET, SO_ERROR, &so_error, &so_error_len);
if (ret < 0 || (so_error != 0
&& so_error != EWOULDBLOCK
&& so_error != ECONNREFUSED
# ifdef EINPROGRESS
&& so_error != EINPROGRESS
# endif
))
{
ch_error(channel,
"channel_connect: Connect failed with errno %d",
so_error);
PERROR(_(e_cannot_connect));
sock_close(sd);
return -1;
}
else if (errno == ECONNREFUSED)
{
ch_error(channel, "channel_connect: Connection refused");
sock_close(sd);
return -1;
}
}
if (FD_ISSET(sd, &wfds) && so_error == 0)
// Did not detect an error, connection is established.
break;
gettimeofday(&end_tv, NULL);
elapsed_msec = (end_tv.tv_sec - start_tv.tv_sec) * 1000
+ (end_tv.tv_usec - start_tv.tv_usec) / 1000;
#endif
}
#ifndef MSWIN
if (*waittime > 1 && elapsed_msec < *waittime)
{
// The port isn't ready but we also didn't get an error.
// This happens when the server didn't open the socket
// yet. Select() may return early, wait until the remaining
// "waitnow" and try again.
waitnow -= elapsed_msec;
*waittime -= elapsed_msec;
if (waitnow > 0)
{
mch_delay((long)waitnow, MCH_DELAY_IGNOREINPUT);
ui_breakcheck();
*waittime -= waitnow;
}
if (!got_int)
{
if (*waittime <= 0)
// give it one more try
*waittime = 1;
continue;
}
// we were interrupted, behave as if timed out
}
#endif
// We timed out.
ch_error(channel, "Connection timed out");
sock_close(sd);
return -1;
}
if (*waittime >= 0)
{
#ifdef MSWIN
val = 0;
ioctlsocket(sd, FIONBIO, &val);
#else
(void)fcntl(sd, F_SETFL, 0);
#endif
}
return sd;
}
/*
* Open a socket channel to "hostname":"port".
* "waittime" is the time in msec to wait for the connection.
* When negative wait forever.
* Returns the channel for success.
* Returns NULL for failure.
*/
channel_T *
channel_open(
const char *hostname,
int port,
int waittime,
void (*nb_close_cb)(void))
{
int sd = -1;
channel_T *channel = NULL;
#ifdef FEAT_IPV6
int err;
struct addrinfo hints;
struct addrinfo *res = NULL;
struct addrinfo *addr = NULL;
#else
struct sockaddr_in server;
struct hostent *host = NULL;
#endif
#ifdef MSWIN
channel_init_winsock();
#endif
channel = add_channel();
if (channel == NULL)
{
ch_error(NULL, "Cannot allocate channel.");
return NULL;
}
// Get the server internet address and put into addr structure fill in the
// socket address structure and connect to server.
#ifdef FEAT_IPV6
CLEAR_FIELD(hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
# if defined(AI_ADDRCONFIG) && defined(AI_V4MAPPED)
hints.ai_flags = AI_ADDRCONFIG | AI_V4MAPPED;
# endif
// Set port number manually in order to prevent name resolution services
// from being invoked in the environment where AI_NUMERICSERV is not
// defined.
if ((err = getaddrinfo(hostname, NULL, &hints, &res)) != 0)
{
ch_error(channel, "in getaddrinfo() in channel_open()");
semsg(_("E901: getaddrinfo() in channel_open(): %s"),
gai_strerror(err));
channel_free(channel);
return NULL;
}
for (addr = res; addr != NULL; addr = addr->ai_next)
{
const char *dst = hostname;
# ifdef HAVE_INET_NTOP
const void *src = NULL;
char buf[NUMBUFLEN];
# endif
if (addr->ai_family == AF_INET6)
{