-
Notifications
You must be signed in to change notification settings - Fork 19
/
nonblockio.c
1701 lines (1379 loc) · 39.1 KB
/
nonblockio.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
/* Part of SWI-Prolog
Author: Jan Wielemaker
E-mail: [email protected]
WWW: http://www.swi-prolog.org
Copyright (c) 2004-2023, University of Amsterdam
VU University Amsterdam
CWI, Amsterdam
SWI-Prolog Solutions b.v.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#define O_DEBUG 1
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
This module is extracted from socket.c to provide a common ground for
accessing sockets and possibly other devices in non-blocking mode,
allowing for GUI (XPCE) event dispatching, timeout handling and
multi-threaded signal and timeout handling.
Besides dealing with nonblocking aspects, an important facet of this
library is to hide OS differences.
API
---
The API is completely the same as for blocking IO. It is however built
on top of sockets used in non-blocking mode which enables the layer to
listen to Prolog events such as timeouts, GUI processing and thread
interaction. The functions are modelled after the POSIX socket API,
prefixed with nbio_*:
nbio_socket()
nbio_connect()
nbio_bind()
nbio_listen()
nbio_accept()
nbio_closesocket()
and IO is realised using
nbio_read() See also below
nbio_write()
Overall control of the library:
nbio_init()
nbio_cleanup()
nbio_debug()
Error handling
nbio_error() Raises a Prolog exception
Settings
nbio_setopt()
nbio_get_flags()
Address Converstion
nbio_get_sockaddr()
nbio_get_ip()
nbio_get_ip4()
Alternative to nbio_read() and nbio_write(), the application program may
call the low-level I/O routines in non-blocking mode and call
nbio_wait(int socket, nbio_request request). This function returns 0 if
it thinks the call might now succeed and -1 if an error occurred,
leaving the exception context in Prolog. On receiving -1, the user must
return an I/O error as soon as possible.
Windows issues
--------------
Winsock is hard to handle in blocking mode without blocking the whole
lot, notably (timeout) signals. Old versions uses WSAASyncSelect() and a
separate thread. This is slow and complicated. The current version was
written by Keri Harris and uses WSAEvent and
MsgWaitForMultipleObjects(). See wait_socket().
Unix issues
-----------
In the Unix version we simply call PL_dispatch() before doing recv() and
leave the details to this function.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#define _CRT_SECURE_NO_WARNINGS 1
#include <config.h>
#if defined(__MINGW32__)
#define __try
#define __except(_) if (0)
#define __finally
#endif
#if defined(__WINDOWS__)
#define WINVER 0x0501
#include <ws2tcpip.h>
#endif
#include "nonblockio.h"
#include <SWI-Stream.h>
#include "clib.h"
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <assert.h>
#include <string.h>
#ifdef __WINDOWS__
#include <malloc.h>
#endif
#if defined(HAVE_POLL_H)
#include <poll.h>
#endif
#ifdef __WINDOWS__
#define GET_ERRNO WSAGetLastError()
#define GET_H_ERRNO WSAGetLastError()
#else
#define GET_ERRNO errno
#define GET_H_ERRNO h_errno
#endif
#ifndef __WINDOWS__
#define closesocket(n) close((n)) /* same on Unix */
#endif
#ifdef __WINDOWS__
typedef int os_bufsize_t;
#define strdup(s) _strdup(s)
#else
typedef size_t os_bufsize_t;
#define INVALID_SOCKET -1
#endif
#ifndef SD_SEND
#define SD_RECEIVE 0 /* shutdown() parameters */
#define SD_SEND 1
#define SD_BOTH 2
#endif
#ifndef SOCKET_ERROR
#define SOCKET_ERROR (-1)
#endif
/* Everybody seems to defined `struct in6_addr` in a different way ...
*/
#ifndef s6_addr16
#if defined(s6_words)
#define s6_addr16 s6_words
#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
#define s6_addr16 __u6_addr.__u6_addr16
#endif
#endif
#define set(s, f) ((s)->flags |= (f))
#define clear(s, f) ((s)->flags &= ~(f))
#define ison(s, f) ((s)->flags & (f))
#define isoff(s, f) (!ison(s, f))
#define PLSOCK_MAGIC 0x38da3f2c
#define PLSOCK_CMAGIC 0x38da3f2d
typedef struct _plsocket
{ int magic; /* PLSOCK_MAGIC */
SOCKET socket; /* The OS socket */
int flags; /* Misc flags */
int domain; /* AF_* */
atom_t symbol; /* <socket>(%p) */
IOSTREAM * input; /* input stream */
IOSTREAM * output; /* output stream */
#ifdef __WINDOWS__
WSAEVENT event; /* Winsock event */
#endif
} plsocket;
#define VALID_SOCKET_RET(s, r) \
do \
{ if ( !(s && (s)->magic == PLSOCK_MAGIC) ) \
{ errno = EINVAL; \
return (r); \
} \
} while(0)
#define VALID_SOCKET(s) VALID_SOCKET_RET(s, -1)
static plsocket *allocSocket(SOCKET socket);
#ifdef __WINDOWS__
static const char *WinSockError(unsigned long eno);
#endif
static int need_retry(int error);
#ifdef O_DEBUG
static int debugging;
int
nbio_debug(int level)
{ int old = debugging;
if ( level >= 0 ) /* -1 --> return current setting */
debugging = level;
return old;
}
#define DEBUG(l, g) if ( debugging >= l ) g
#else
#define DEBUG(l, g) (void)0
int
nbio_debug(int level)
{ return 0;
}
#endif /*O_DEBUG*/
/*******************************
* COMPATIBILITY *
*******************************/
#ifdef __WINDOWS__
#if O_DEBUG
static char *
sepstrcatskip(char *buf, char *dest, char *src)
{ if ( dest != buf )
{ *dest++ = '|';
*dest = '\0';
}
strcat(dest, src);
dest += strlen(dest);
return dest;
}
static char *
event_name(int ev)
{ char buf[256];
char *o = buf;
o[0] = '\0';
if ( (ev & FD_READ) ) o=sepstrcatskip(buf, o, "FD_READ");
if ( (ev & FD_WRITE) ) o=sepstrcatskip(buf, o, "FD_WRITE");
if ( (ev & FD_ACCEPT) ) o=sepstrcatskip(buf, o, "FD_ACCEPT");
if ( (ev & FD_CONNECT) ) o=sepstrcatskip(buf, o, "FD_CONNECT");
if ( (ev & FD_CLOSE) ) o=sepstrcatskip(buf, o, "FD_CLOSE");
if ( (ev & FD_OOB) ) o=sepstrcatskip(buf, o, "FD_OOB");
if ( (ev & ~(FD_READ|FD_WRITE|FD_ACCEPT|FD_CONNECT|FD_CLOSE)) )
sepstrcatskip(buf, o, "FD_???");
return strdup(buf);
}
#endif /*O_DEBUG*/
#define F_SETFL 0
#define O_NONBLOCK 0
static int
nbio_fcntl(nbio_sock_t socket, int op, int arg)
{ VALID_SOCKET(socket);
switch(op)
{ case F_SETFL:
switch(arg)
{ case O_NONBLOCK:
{ int rval;
#if defined(__MINGW32__)
u_long non_block;
#else
/* FIXME: is this really `int' for MSC? */
int non_block;
#endif
non_block = 1;
rval = ioctlsocket(socket->socket, FIONBIO, &non_block);
if ( rval )
{ set(socket, PLSOCK_NONBLOCK);
return 0;
}
return -1;
}
default:
return -1;
}
break;
default:
return -1;
}
}
static int
need_retry(int error)
{ if ( error == WSAEINTR || error == WSAEWOULDBLOCK )
{ DEBUG(1, Sdprintf("need_retry(%d): %s\n", error, WinSockError(error)));
return TRUE;
}
return FALSE;
}
/* wait_socket() waits for the socket to become ready and in the
* while waiting processes Windows messages, including Prolog
* timeout.
*
* Returns TRUE if all ok and FALSE if some Prolog exception has
* been raised.
*/
static int
wait_socket(plsocket *s)
{ int index;
for(;;)
{ DEBUG(2, Sdprintf("waiting on socket: %d\n", s->socket));
index = MsgWaitForMultipleObjects(1, &s->event, FALSE, INFINITE, QS_ALLINPUT);
if ( index == WAIT_FAILED )
{ nbio_error(GetLastError(), TCP_ERRNO);
return FALSE;
} else if ( index == WAIT_OBJECT_0+0 ) /* socket event */
{ WSANETWORKEVENTS events;
if ( WSAEnumNetworkEvents(s->socket, s->event, &events) == SOCKET_ERROR )
{ nbio_error(GET_ERRNO, TCP_ERRNO);
return FALSE;
}
DEBUG(2,
{ char *nm = event_name(events.lNetworkEvents);
Sdprintf("WM_SOCKET on %d: ev=(%s)\n", s->socket, nm);
free(nm);
});
if ( events.lNetworkEvents & FD_CONNECT )
{ if ( events.iErrorCode[FD_CONNECT_BIT] )
{ nbio_error(events.iErrorCode[FD_CONNECT_BIT], TCP_ERRNO);
return FALSE;
}
}
if ( events.lNetworkEvents & FD_ACCEPT )
{ if ( events.iErrorCode[FD_ACCEPT_BIT] )
{ nbio_error(events.iErrorCode[FD_ACCEPT_BIT], TCP_ERRNO);
return FALSE;
}
}
if ( events.lNetworkEvents & FD_READ )
{ if ( events.iErrorCode[FD_READ_BIT] )
{ nbio_error(events.iErrorCode[FD_READ_BIT], TCP_ERRNO);
return FALSE;
}
}
if ( events.lNetworkEvents & FD_WRITE )
{ if ( events.iErrorCode[FD_WRITE_BIT] )
{ nbio_error(events.iErrorCode[FD_WRITE_BIT], TCP_ERRNO);
return FALSE;
}
}
break;
} else if ( index == WAIT_OBJECT_0+1 ) /* message event */
{ MSG msg;
DEBUG(2, Sdprintf("interrupted socket: %p\n", s->socket));
while( PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) )
{ TranslateMessage(&msg);
DispatchMessage(&msg);
if ( PL_handle_signals() < 0 )
{ errno = EPLEXCEPTION;
return FALSE;
}
continue;
}
}
}
return TRUE;
}
int
nbio_wait(nbio_sock_t socket, nbio_request request)
{ VALID_SOCKET(socket);
return wait_socket(socket) ? 0 : -1;
}
#else /*__WINDOWS__*/
static int
need_retry(int error)
{ if ( error == EINTR || error == EAGAIN || error == EWOULDBLOCK )
{ DEBUG(1, Sdprintf("need_retry(%d): %s\n", error, strerror(error)));
return TRUE;
}
return FALSE;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
wait_socket() is the Unix way to wait for input on the socket. By
default event-dispatching on behalf of XPCE is performed. If this is not
desired, you can use tcp_setopt(Socket, dispatch(false)), in which case
this call returns immediately, assuming the actual TCP call will block
without dispatching if no input is available.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static int
wait_socket(plsocket *s)
{ if ( ison(s, PLSOCK_DISPATCH) )
{ int fd = s->socket;
if ( ison(s, PLSOCK_NONBLOCK) && !PL_dispatch(fd, PL_DISPATCH_INSTALLED) )
{
#ifdef HAVE_POLL
struct pollfd fds[1];
fds[0].fd = fd;
fds[0].events = POLLIN;
poll(fds, 1, 250);
return TRUE;
#else
if ( fd < FD_SETSIZE ) /* Unix only, so ok */
{ fd_set rfds;
struct timeval tv;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 250000;
select(fd+1, &rfds, NULL, NULL, &tv);
return TRUE;
}
#endif
} else
{ int rc;
if ( !(rc = PL_dispatch(fd, PL_DISPATCH_WAIT)) )
errno = EPLEXCEPTION;
return rc;
}
}
return TRUE;
}
int
nbio_wait(nbio_sock_t socket, nbio_request request)
{ VALID_SOCKET(socket);
return wait_socket(socket) ? 0 : -1;
}
static int
nbio_fcntl(nbio_sock_t socket, int op, int arg)
{ int rc;
VALID_SOCKET(socket);
rc = fcntl(socket->socket, op, arg);
if ( rc == 0 )
{ if ( op == F_SETFL && arg == O_NONBLOCK )
set(socket, PLSOCK_NONBLOCK);
} else
nbio_error(GET_ERRNO, TCP_ERRNO);
return rc;
}
#endif /*__WINDOWS__*/
/*******************************
* ADMINISTRATION *
*******************************/
static functor_t FUNCTOR_module2;
static functor_t FUNCTOR_ip4;
static functor_t FUNCTOR_ip8;
static functor_t FUNCTOR_ip1;
static atom_t ATOM_any;
static atom_t ATOM_broadcast;
static atom_t ATOM_loopback;
static int initialised = FALSE; /* Windows only */
SOCKET
nbio_fd(nbio_sock_t socket)
{ VALID_SOCKET(socket);
return socket->socket;
}
void
nbio_set_symbol(nbio_sock_t socket, atom_t symbol)
{ socket->symbol = symbol;
}
int
is_nbio_socket(nbio_sock_t socket)
{ return socket && socket->magic == PLSOCK_MAGIC;
}
int
nbio_domain(nbio_sock_t socket)
{ return socket->domain;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Allocate a wrapper for an OS socket. The wrapper is allocated in an
array of pointers, to keep small integer identifiers we can use with
FD_SET, etc. for implementing a compatible nbio_select().
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static plsocket *
allocSocket(SOCKET socket)
{ plsocket *p;
if ( !(p = malloc(sizeof(*p))) )
{ PL_resource_error("memory");
return NULL;
}
memset(p, 0, sizeof(*p));
p->socket = socket;
p->flags = PLSOCK_DISPATCH|PLSOCK_VIRGIN; /* by default, dispatch */
p->magic = PLSOCK_MAGIC;
p->input = p->output = (IOSTREAM*)NULL;
#ifdef __WINDOWS__
{ WSAEVENT event = WSACreateEvent();
WSAEventSelect(socket, event, FD_READ|FD_WRITE|FD_ACCEPT|FD_CONNECT|FD_CLOSE);
p->event = event;
}
#endif
DEBUG(2, Sdprintf("[%d]: allocSocket(%d) --> %p\n",
PL_thread_self(), socket, p));
DEBUG(4, PL_backtrace(10,1));
return p;
}
void
freeSocket(nbio_sock_t s)
{ if ( s )
{ if ( s->magic == PLSOCK_CMAGIC )
free(s);
else
s->symbol = 0;
}
}
static int
closeSocket(plsocket *s)
{ int rval;
SOCKET sock;
DEBUG(2, Sdprintf("Closing %p (%zd)\n", s, (size_t)s->socket));
if ( !s || s->magic != PLSOCK_MAGIC )
{ DEBUG(1, Sdprintf("OOPS: closeSocket(%p) s->magic = %d\n",
s, s ? s->magic : 0));
errno = EINVAL;
return -1;
}
sock = s->socket;
s->magic = PLSOCK_CMAGIC;
#ifdef __WINDOWS__
if ( s->event )
WSACloseEvent(s->event);
#endif
if ( sock != INVALID_SOCKET )
{ again:
if ( (rval=closesocket(sock)) == SOCKET_ERROR )
{ if ( errno == EINTR )
goto again;
}
DEBUG(2, Sdprintf("closeSocket(%p=%d): closesocket() returned %d\n",
s, (int)sock, rval));
} else
{ DEBUG(2, Sdprintf("closeSocket(%p=%d): already closed\n",
s, (int)sock));
rval = 0; /* already closed. Use s->error? */
}
if ( !s->symbol )
free(s);
return rval;
}
/*******************************
* ERRORS *
*******************************/
#ifdef __WINDOWS__
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The code in BILLY_GETS_BETTER is, according to various documents the
right code, but it doesn't work, so we do it by hand.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#ifdef BILLY_GETS_BETTER
static const char *
WinSockError(unsigned long eno)
{ char buf[1024];
static HMODULE netmsg = 0;
static int netmsg_loaded = FALSE;
unsigned long flags = (FORMAT_MESSAGE_FROM_SYSTEM|
FORMAT_MESSAGE_IGNORE_INSERTS);
if ( !netmsg_loaded )
{ netmsg_loaded = TRUE;
netmsg = LoadLibraryEx("netmsg.dll", 0, LOAD_LIBRARY_AS_DATAFILE);
if ( !netmsg )
Sdprintf("failed to load netmsg.dll\n");
else
Sdprintf("Loaded netmsg.dll as %p\n", netmsg);
}
if ( netmsg )
flags |= FORMAT_MESSAGE_FROM_HMODULE;
if ( !FormatMessage(flags,
netmsg,
eno,
GetUserDefaultLangID(),
/*MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),*/
buf, sizeof(buf),
0))
{ sprintf(buf, "Unknown socket error (%u)", eno);
}
buf[sizeof(buf)-1]='\0';
return strdup(buf);
}
#else /*BILLY_GETS_BETTER*/
static const char *
WinSockError(unsigned long error)
{ struct
{ int index;
const char *string;
} *ep, edefs[] =
{ { WSAEACCES, "Permission denied" },
{ WSAEADDRINUSE, "Address already in use" },
{ WSAEADDRNOTAVAIL, "Cannot assign requested address" },
{ WSAEAFNOSUPPORT, "Address family not supported by protocol family" },
{ WSAEALREADY, "Operation already in progress" },
{ WSAECONNABORTED, "Software caused connection abort" },
{ WSAECONNREFUSED, "Connection refused" },
{ WSAECONNRESET, "Connection reset by peer" },
{ WSAEDESTADDRREQ, "Destination address required" },
{ WSAEFAULT, "Bad address" },
{ WSAEHOSTDOWN, "Host is down" },
{ WSAEHOSTUNREACH, "No route to host" },
{ WSAEINPROGRESS, "Operation now in progress" },
{ WSAEINTR, "Interrupted function call" },
{ WSAEINVAL, "Invalid argument" },
{ WSAEISCONN, "Socket is already connected" },
{ WSAEMFILE, "Too many open files" },
{ WSAEMSGSIZE, "Message too long" },
{ WSAENETDOWN, "Network is down" },
{ WSAENETRESET, "Network dropped connection on reset" },
{ WSAENETUNREACH, "Network is unreachable" },
{ WSAENOBUFS, "No buffer space available" },
{ WSAENOPROTOOPT, "Bad protocol option" },
{ WSAENOTCONN, "Socket is not connected" },
{ WSAENOTSOCK, "Socket operation on non-socket" },
{ WSAEOPNOTSUPP, "Operation not supported" },
{ WSAEPFNOSUPPORT, "Protocol family not supported" },
{ WSAEPROCLIM, "Too many processes" },
{ WSAEPROTONOSUPPORT, "Protocol not supported" },
{ WSAEPROTOTYPE, "Protocol wrong type for socket" },
{ WSAESHUTDOWN, "Cannot send after socket shutdown" },
{ WSAESOCKTNOSUPPORT, "Socket type not supported" },
{ WSAETIMEDOUT, "Connection timed out" },
{ WSAEWOULDBLOCK, "Resource temporarily unavailable" },
{ WSAEDISCON, "Graceful shutdown in progress" },
{ WSANOTINITIALISED, "Socket layer not initialised" },
/* WinSock 2 errors */
{ WSAHOST_NOT_FOUND, "Host not found" },
{ WSANO_DATA, "Valid name, no data record of requested type" },
{ 0, NULL }
};
char tmp[100];
for(ep=edefs; ep->string; ep++)
{ if ( ep->index == (int)error )
return ep->string;
}
sprintf(tmp, "Unknown error %ld", error);
return strdup(tmp); /* leaks memory on unknown errors */
}
#endif /*BILLY_GETS_BETTER*/
#endif /*__WINDOWS__*/
/*******************************
* POSIX SOCKET ERRORS *
*******************************/
#include "esymbols.ic"
#ifndef __WINDOWS__
#ifndef HAVE_HSTRERROR
#define hstrerror my_hstrerror
static const char *
hstrerror(int code)
{ return error_symbol(code, h_errno_symbols);
}
#endif /*HAVE_HSTRERROR*/
#ifndef HAVE_GAI_STRERROR
#define gai_strerror my_gai_strerror
static const char *
gai_strerror(int code)
{ return error_symbol(code, gai_errno_symbols);
}
#endif /*HAVE_HAVE_GAI_STRERROR*/
#endif /*__WINDOWS__*/
int
nbio_error(int code, nbio_error_map mapid)
{ const char *msg;
const char *symbol;
term_t ex;
if ( code == EPLEXCEPTION || PL_exception(0) )
return FALSE;
#ifdef __WINDOWS__
msg = WinSockError(code);
symbol = error_symbol(code, wsa_errno_symbols);
#else
switch( mapid )
{ case TCP_ERRNO:
msg = strerror(code);
symbol = error_symbol(code, errno_symbols);
break;
case TCP_HERRNO:
msg = hstrerror(code);
symbol = error_symbol(code, h_errno_symbols);
break;
case TCP_GAI_ERRNO:
msg = gai_strerror(code);
symbol = error_symbol(code, gai_errno_symbols);
break;
default:
assert(0);
msg = NULL;
break;
}
#endif
errno = EPLEXCEPTION;
return ( (ex = PL_new_term_ref()) &&
PL_unify_term(ex,
CompoundArg("error", 2),
CompoundArg("socket_error", 2),
AtomArg(symbol),
AtomMbArg(msg),
PL_VARIABLE) &&
PL_raise_exception(ex)
);
}
const char *
nbio_last_error(nbio_sock_t socket)
{ return NULL;
}
/*******************************
* INITIALISATION *
*******************************/
int
nbio_init(const char *module)
{ if ( initialised ) /* called from install handlers, which */
return TRUE; /* are serialized by the compiler mutex */
initialised = TRUE;
FUNCTOR_module2 = PL_new_functor(PL_new_atom(":"), 2);
FUNCTOR_ip1 = PL_new_functor(PL_new_atom("ip"), 1);
FUNCTOR_ip4 = PL_new_functor(PL_new_atom("ip"), 4);
FUNCTOR_ip8 = PL_new_functor(PL_new_atom("ip"), 8);
ATOM_any = PL_new_atom("any");
ATOM_broadcast = PL_new_atom("broadcast");
ATOM_loopback = PL_new_atom("loopback");
#ifdef __WINDOWS__
{ WSADATA WSAData;
if ( WSAStartup(MAKEWORD(2,0), &WSAData) )
return PL_warning("nbio_init() - WSAStartup failed.");
}
#endif /*__WINDOWS__*/
return TRUE;
}
int
nbio_cleanup(void)
{ if ( initialised )
{
#ifdef __WINDOWS__
WSACleanup();
#endif
}
return 0;
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
socket(-Socket)
Create a stream inet socket. The socket is represented by a term of
the format $socket(Id).
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
nbio_sock_t
nbio_socket(int domain, int type, int protocol)
{ SOCKET sock;
plsocket *s;
assert(initialised);
if ( (sock = socket(domain, type , protocol)) == INVALID_SOCKET )
{ nbio_error(GET_ERRNO, TCP_ERRNO);
return NULL;
}
if ( !(s=allocSocket(sock)) ) /* register it */
{ closesocket(sock);
return NULL;
}
s->domain = domain;
#ifdef __WINDOWS__
/* On older versions of Windows (win7 and before) the default send
buffer size is only 8k. On a high latency link this can seriously
hamper performance. Default it to max(64k, current-value)
*/
{ int val;
int val_len = sizeof(val);
if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)&val, &val_len) == 0 &&
val < 65535)
{ val = 65535;
setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)&val, sizeof(int));
}
}
#endif
return s;
}
int
nbio_closesocket(nbio_sock_t socket)
{ int rc = 0;
VALID_SOCKET(socket);
clear(socket, PLSOCK_VIRGIN);
if ( ison(socket, PLSOCK_OUTSTREAM|PLSOCK_INSTREAM) )
{ int flags = socket->flags; /* may drop out! */
if ( flags & PLSOCK_INSTREAM )
{ assert(socket->input);
if ( Slock(socket->input) == 0 )
rc += Sclose(socket->input);
else
rc--;
}
if ( flags & PLSOCK_OUTSTREAM )
{ assert(socket->output);
if ( Slock(socket->output) == 0 )
rc += Sclose(socket->output);
else
rc--;
}
} else
{ rc = 0;
#ifdef __WINDOWS__
shutdown(socket->socket, SD_BOTH);
#endif
closeSocket(socket);
}
return rc;
}
int
nbio_setopt(nbio_sock_t socket, nbio_option opt, ...)
{ va_list args;
int rc;
VALID_SOCKET(socket);
va_start(args, opt);
switch(opt)
{ case TCP_NONBLOCK:
rc = nbio_fcntl(socket, F_SETFL, O_NONBLOCK);
break;
case TCP_REUSEADDR:
{ int val = va_arg(args, int);
if( setsockopt(socket->socket, SOL_SOCKET, SO_REUSEADDR,
(const char *)&val, sizeof(val)) == -1 )
{ nbio_error(GET_ERRNO, TCP_ERRNO);
rc = -1;
} else
rc = 0;
break;
}
case SCK_BINDTODEVICE:
{ const char *dev = va_arg(args, char*);
#ifdef SO_BINDTODEVICE
if ( setsockopt(socket->socket, SOL_SOCKET, SO_BINDTODEVICE,
dev, strlen(dev)) == 0 )
{ rc = 0;
break;
}
nbio_error(GET_ERRNO, TCP_ERRNO);
rc = -1;
#else
(void)dev;
rc = -2;
#endif
break;
}
case TCP_NO_DELAY:
#ifdef TCP_NODELAY
{ int val = va_arg(args, int);
#ifndef IPPROTO_TCP /* Is this correct? */
#define IPPROTO_TCP SOL_SOCKET
#endif
if ( setsockopt(socket->socket, IPPROTO_TCP, TCP_NODELAY,
(const char *)&val, sizeof(val)) == -1 )
{ nbio_error(GET_ERRNO, TCP_ERRNO);
rc = -1;
} else
{ rc = 0;
}
break;