forked from SWI-Prolog/packages-clib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nonblockio.c
2543 lines (2051 loc) · 55.8 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): 1985-2013, University of Amsterdam
VU University Amsterdam
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#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_ip4()
Waiting
nbio_select()
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. We therefore have a seperate thread
dealing with I/O and operating the sockets through WSAAsyncSelect()
generated events. Requests are registered with the plsocket structure,
handled and handled in the socket thread. Upon completion, a message is
sent back to the waiting thread.
Unix issues
-----------
In the Unix version we simply call PL_dispatch() before doing recv() and
leave the details to this function.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef __CYGWIN__
#undef HAVE_H_ERRNO
#endif
#ifdef __MINGW32__
//disgusting stuff :(
#define __try if (1)
#define __except(A) else
#endif
#if defined(__MINGW32__)
#define __try
#define __except(_) if (0)
#define __finally
#endif
#if defined(__MINGW32__)
#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
void /* allow debugger breakpoint */
tcp_debug(void);
#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
#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
#ifdef CLIB_MSG_DONTWAIT
#define CLIB_MSG_DONTWAIT MSG_DONTWAIT
#else
#define CLIB_MSG_DONTWAIT 0
#endif
#ifndef INADDR_LOOPBACK
#define INADDR_LOOPBACK ((uint32_t)0x7f000001) /* INET 127.0.0.1 */
#endif
#ifdef _REENTRANT
#if __WINDOWS__
static CRITICAL_SECTION mutex;
static CRITICAL_SECTION mutex_free;
#define LOCK() EnterCriticalSection(&mutex)
#define UNLOCK() LeaveCriticalSection(&mutex)
#define LOCK_FREE() EnterCriticalSection(&mutex_free)
#define UNLOCK_FREE() LeaveCriticalSection(&mutex_free)
#define INITLOCK() ( InitializeCriticalSection(&mutex), \
InitializeCriticalSection(&mutex_free))
#define LOCK_SOCKET(s) EnterCriticalSection(&s->socket_mutex)
#define UNLOCK_SOCKET(s) LeaveCriticalSection(&s->socket_mutex)
#define INIT_SOCKET_LOCK(s) InitializeCriticalSection(&s->socket_mutex)
#define FREE_SOCKET_LOCK(s) DeleteCriticalSection(&s->socket_mutex)
#else /*__WINDOWS__*/
#include <pthread.h>
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
#define LOCK() pthread_mutex_lock(&mutex)
#define UNLOCK() pthread_mutex_unlock(&mutex)
#define LOCK_FREE() (void)0
#define UNLOCK_FREE() (void)0
#define INITLOCK() (void)0
#define FREE_SOCKET_LOCK(s) (void)0
#endif /*__WINDOWS__*/
#else /* _REENTRANT */
#define LOCK() (void)0
#define UNLOCK() (void)0
#define LOCK_FREE() (void)0
#define UNLOCK_FREE() (void)0
#define INITLOCK() (void)0
#define FREE_SOCKET_LOCK(s) (void)0
#if __WINDOWS__
#define LOCK_SOCKET(s) (void)0
#define UNLOCK_SOCKET(s) (void)0
#define INIT_SOCKET_LOCK(s) (void)0
#endif
#endif /* _REENTRANT */
#define set(s, f) ((s)->flags |= (f))
#define clear(s, f) ((s)->flags &= ~(f))
#define True(s, f) ((s)->flags & (f))
#define False(s, f) (!True(s, f))
#define PLSOCK_MAGIC 0x38da3f2c
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NOTE: We must lock the structure to avoid freeSocket() called from
Prolog deleting the socket while there are still pending events on it
that are concurrently executed in the socket thread.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
typedef struct _plsocket
{ int magic; /* PLSOCK_MAGIC */
nbio_sock_t id; /* Integer id */
SOCKET socket; /* The OS socket */
int flags; /* Misc flags */
IOSTREAM * input; /* input stream */
IOSTREAM * output; /* output stream */
#ifdef __WINDOWS__
nbio_request request; /* our request */
DWORD thread; /* waiting thread */
DWORD error; /* error while executing request */
DWORD close_timeout; /* Time to reap socket if FD_CLOSE is not received */
int done; /* request completed */
int w32_flags; /* or of received FD_* */
CRITICAL_SECTION socket_mutex; /* synchronization mutex */
union
{ struct
{ struct sockaddr_in addr; /* accepted address */
int addrlen; /* address length */
nbio_sock_t slave; /* descriptor of slave */
} accept;
struct
{ struct sockaddr_in addr; /* accepted address */
size_t addrlen; /* address length */
} connect;
struct
{ int bytes; /* byte count */
char *buffer; /* the buffer */
size_t size; /* buffer size */
} read;
struct
{ int bytes; /* byte count */
char *buffer; /* the buffer */
size_t written;
size_t size; /* buffer size */
} write;
struct
{ int bytes; /* byte count */
void *buffer; /* the buffer */
size_t size; /* buffer size */
int flags;
struct sockaddr *from;
socklen_t *fromlen;
} recvfrom;
struct
{ int bytes; /* byte count */
void *buffer; /* the buffer */
int size; /* buffer size */
int flags;
const struct sockaddr *to;
int tolen;
} sendto;
} rdata;
#endif
} plsocket;
static plsocket *allocSocket(SOCKET socket);
#ifdef __WINDOWS__
static plsocket *lookupOSSocket(SOCKET socket);
static int socketIsPendingClose(plsocket *s);
static const char *WinSockError(unsigned long eno);
#endif
#ifndef __WINDOWS__
static int
need_retry(int error)
{ if ( error == EINTR || error == EAGAIN || error == EWOULDBLOCK )
return TRUE;
return FALSE;
}
#endif
int nbio_debug(int level);
#ifdef O_DEBUG
static int debugging;
NBIO_EXPORT(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
void /* allow debugger breakpoint */
tcp_debug(void)
{ Sdprintf("Trapping debugger\n");
}
/*******************************
* COMPATIBILITY *
*******************************/
#ifdef __WINDOWS__
static UINT WM_SOCKET = WM_APP+20;
static UINT WM_REQUEST = WM_APP+21;
static UINT WM_READY = WM_APP+22;
static UINT WM_DONE = WM_APP+23;
#if O_DEBUG
static char *
request_name(nbio_request request)
{ switch(request)
{ case REQ_NONE: return "req_none";
case REQ_ACCEPT: return "req_accept";
case REQ_CONNECT: return "req_connect";
case REQ_READ: return "req_read";
case REQ_WRITE: return "req_write";
case REQ_RECVFROM:return "req_recvfrom";
case REQ_SENDTO: return "req_sendto";
default: return "req_???";
}
}
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
#define F_SETFL 0
#define O_NONBLOCK 0
static int
nbio_fcntl(nbio_sock_t socket, int op, int arg)
{ plsocket *s;
if ( !(s=nbio_to_plsocket(socket)) )
return -1;
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(s->socket, FIONBIO, &non_block);
if ( rval )
{ s->flags |= PLSOCK_NONBLOCK;
return 0;
}
return -1;
}
default:
return -1;
}
break;
default:
return -1;
}
}
static HINSTANCE hinstance; /* hinstance */
typedef struct
{ HWND hwnd; /* our window */
DWORD tid; /* thread id */
} local_state;
static local_state nbio_state;
#define State() (&nbio_state)
static int
doneRequest(plsocket *s)
{ SOCKET sock;
LOCK_SOCKET(s);
s->done = TRUE;
s->request = REQ_NONE;
UNLOCK_SOCKET(s);
/* If we have FD_CLOSE, then we know we can release the socket to the OS */
if ( (s->w32_flags & FD_CLOSE) && (sock=s->socket) >= 0 )
{ s->socket = -1;
closesocket(sock);
}
if ( s->thread )
{ DEBUG(2, Sdprintf("doneRequest(%d): posting %d\n", s->id, s->thread));
PostThreadMessage(s->thread, WM_DONE, 0, (WPARAM)s);
}
return TRUE;
}
static int
waitRequest(plsocket *s)
{ assert(s->magic == PLSOCK_MAGIC);
DEBUG(2, Sdprintf("[%d] (%ld): Waiting for %s on %d ...",
PL_thread_self(), s->thread,
request_name(s->request), (int)s->socket));
for(;;)
{ MSG msg;
if ( PL_handle_signals() < 0 )
{ DEBUG(1, Sdprintf("[%d]: Exception\n", PL_thread_self()));
return FALSE;
}
if ( s->done )
{ DEBUG(2, Sdprintf("[%d]: Done\n", PL_thread_self()));
return TRUE;
}
if ( False(s, PLSOCK_DISPATCH) )
{ if ( !GetMessage(&msg, NULL, WM_DONE, WM_DONE) )
return FALSE;
} else if ( GetMessage(&msg, NULL, 0, 0) )
{ TranslateMessage(&msg);
DispatchMessage(&msg);
if ( PL_exception(0) )
return FALSE; /* DispatchMessage handled a signal */
} else
{ ExitThread(0); /* WM_QUIT received */
return FALSE; /* NOTREACHED */
}
}
}
int
nbio_wait(nbio_sock_t socket, nbio_request request)
{ plsocket *s;
if ( !(s=nbio_to_plsocket(socket)) )
return -1;
LOCK_SOCKET(s);
s->flags |= PLSOCK_WAITING;
s->done = FALSE;
s->error = 0;
s->thread = GetCurrentThreadId();
s->request = request;
UNLOCK_SOCKET(s);
SendMessage(State()->hwnd, WM_REQUEST, 1, (LPARAM)&s);
DEBUG(2, Sdprintf("[%d] (%ld): Waiting ... ",
PL_thread_self(), s->thread));
for(;;)
{ MSG msg;
if ( PL_handle_signals() < 0 )
{ DEBUG(1, Sdprintf("[%d]: Exception\n", PL_thread_self()));
return -1;
}
if ( s->done )
{ DEBUG(2, Sdprintf("[%d]: Done\n", PL_thread_self()));
return 0;
}
if ( False(s, PLSOCK_DISPATCH) )
{ if ( !GetMessage(&msg, NULL, WM_DONE, WM_DONE) )
return FALSE;
} else if ( GetMessage(&msg, NULL, 0, 0) )
{ TranslateMessage(&msg);
DispatchMessage(&msg);
} else
{ ExitThread(0); /* WM_QUIT received */
return -1; /* NOTREACHED */
}
}
}
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
nbio_select() selects using a set of socket streams.
NOTE: The Windows versions uses our nbio_sock_t abstraction, while the
other version uses the raw Unix file descriptors referencing the
underlying socket.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
int
nbio_select(int n,
fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
struct timeval *timeout)
{ plsocket **sockets = alloca(n * sizeof(plsocket*));
int i;
DWORD t_end;
if ( !sockets )
{ errno = ENOMEM;
return -1;
}
for(i=0; i<n; i++)
sockets[i] = NULL;
if ( readfds )
{ for(i=0; i<n; i++)
{ if ( FD_ISSET(i, readfds) )
{ plsocket *s = nbio_to_plsocket(i);
if ( s )
{ LOCK_SOCKET(s);
s->flags |= PLSOCK_WAITING;
s->done = FALSE;
s->error = 0;
s->thread = GetCurrentThreadId();
s->request = (s->flags & PLSOCK_LISTEN) ? REQ_ACCEPT : REQ_READ;
UNLOCK_SOCKET(s);
sockets[i] = s;
} else
{ DEBUG(2, Sdprintf("nbio_select(): no socket for %d\n", i));
}
}
}
}
if ( writefds )
return -1; /* not yet implemented */
if ( exceptfds )
return -1; /* idem (might never be) */
if ( timeout )
{ t_end = GetTickCount();
t_end += timeout->tv_sec*1000;
t_end += timeout->tv_usec/1000;
}
FD_ZERO(readfds);
SendMessage(State()->hwnd, WM_REQUEST, n, (LPARAM)sockets);
for(;;)
{ MSG msg;
plsocket **s;
int ready;
if ( PL_handle_signals() < 0 )
{ DEBUG(1, Sdprintf("[%d]: Exception\n", PL_thread_self()));
return -1;
}
for(ready=0, i=0, s=sockets; i<n; i++, s++)
{ if ( *s && (*s)->done )
{ ready++;
FD_SET((unsigned)i, readfds);
}
}
if ( ready > 0 )
return ready;
if ( timeout )
{ DWORD rc;
DWORD t = GetTickCount();
long msec = t_end - t;
if ( msec < 0 )
msec = -msec; /* wrapped around */
rc = MsgWaitForMultipleObjects(0, NULL, FALSE, msec, QS_ALLINPUT);
if ( rc == WAIT_OBJECT_0 )
{ if ( GetMessage(&msg, NULL, 0, 0) )
{ TranslateMessage(&msg);
DispatchMessage(&msg);
} else
{ ExitThread(0); /* WM_QUIT received */
return -1; /* NOTREACHED */
}
} else if ( rc == WAIT_TIMEOUT )
{ return 0;
} else
{ assert(0);
}
} else
{ if ( GetMessage(&msg, NULL, 0, 0) )
{ TranslateMessage(&msg);
DispatchMessage(&msg);
} else
{ ExitThread(0); /* WM_QUIT received */
return -1; /* NOTREACHED */
}
}
}
}
static int
placeRequest(plsocket *s, nbio_request request)
{ if ( s->magic != PLSOCK_MAGIC )
Sdprintf("placeRequest: %p has bad magic\n", s);
LOCK_SOCKET(s);
s->error = 0;
s->done = FALSE;
s->thread = GetCurrentThreadId();
s->request = request;
clear(s, PLSOCK_WAITING);
UNLOCK_SOCKET(s);
SendMessage(State()->hwnd, WM_REQUEST, 1, (LPARAM)&s);
DEBUG(2, Sdprintf("[%d] (%ld): Placed %s request for %d\n",
PL_thread_self(), s->thread,
request_name(request), (int)s->socket));
return TRUE;
}
static int
doRequest(plsocket *s)
{ if ( s->magic != PLSOCK_MAGIC )
Sdprintf("doRequest: %p has bad magic\n", s);
switch(s->request)
{ case REQ_NONE:
break;
case REQ_CONNECT:
if ( s->w32_flags & FD_CONNECT )
{ s->w32_flags &= ~FD_CONNECT;
if ( True(s, PLSOCK_WAITING) )
{ doneRequest(s);
break;
}
if ( connect(s->socket,
(struct sockaddr*)&s->rdata.connect.addr,
(int)s->rdata.connect.addrlen) )
{ s->error = WSAGetLastError();
switch(s->error)
{ case WSAEWOULDBLOCK:
case WSAEINVAL:
case WSAEALREADY:
break;
case WSAEISCONN:
s->error = 0;
doneRequest(s);
break;
default:
doneRequest(s);
}
} else
{ s->error = 0;
doneRequest(s);
}
}
break;
case REQ_ACCEPT:
if ( s->w32_flags & FD_ACCEPT )
{ SOCKET slave;
s->w32_flags &= ~FD_ACCEPT;
if ( True(s, PLSOCK_WAITING) )
{ doneRequest(s);
break;
}
slave = accept(s->socket,
(struct sockaddr*)&s->rdata.accept.addr,
&s->rdata.accept.addrlen);
if ( slave == SOCKET_ERROR )
{ s->error = WSAGetLastError();
DEBUG(2, Sdprintf("Accept(%d): %s\n",
(int)s->socket, WinSockError(s->error)));
if ( s->error != WSAEWOULDBLOCK )
{ s->rdata.accept.slave = (nbio_sock_t)-1;
doneRequest(s);
}
} else
{ plsocket *pls;
DEBUG(2, Sdprintf("Accept(%d) --> %d\n",
(int)s->socket, (int)slave));
if ( (pls = allocSocket(slave)) )
{ pls->flags |= PLSOCK_ACCEPT; /* requests */
s->rdata.accept.slave = pls->id;
s->error = 0;
doneRequest(s);
} else
{ DEBUG(1, Sdprintf("Socket %d already registered; "
"considering bogus\n", (int)slave));
}
}
}
break;
case REQ_READ:
if ( s->w32_flags & (FD_READ|FD_CLOSE) )
{ s->w32_flags &= ~FD_READ;
if ( True(s, PLSOCK_WAITING) )
{ doneRequest(s);
break;
}
s->rdata.read.bytes = recv(s->socket,
s->rdata.read.buffer,
(int)s->rdata.read.size,
0);
if ( s->rdata.read.bytes < 0 )
{ s->error = WSAGetLastError();
if ( s->error != WSAEWOULDBLOCK )
{ DEBUG(1, Sdprintf("Error reading from %d: %s\n",
s->socket, WinSockError(s->error)));
doneRequest(s);
}
} else
{ doneRequest(s);
}
}
break;
case REQ_RECVFROM:
if ( s->w32_flags & (FD_READ|FD_CLOSE) )
{ int iflen = (int)*s->rdata.recvfrom.fromlen;
s->w32_flags &= ~FD_READ;
if ( True(s, PLSOCK_WAITING) )
{ doneRequest(s);
break;
}
s->rdata.recvfrom.bytes =
recvfrom(s->socket,
s->rdata.recvfrom.buffer,
(int)s->rdata.recvfrom.size,
s->rdata.recvfrom.flags,
s->rdata.recvfrom.from,
&iflen);
if ( s->rdata.recvfrom.bytes < 0 )
{ s->error = WSAGetLastError();
if ( s->error != WSAEWOULDBLOCK )
{ DEBUG(1, Sdprintf("Error recvfrom from %d: %s\n",
s->socket, WinSockError(s->error)));
doneRequest(s);
}
} else
{ *s->rdata.recvfrom.fromlen = iflen;
doneRequest(s);
}
}
break;
case REQ_WRITE:
if ( s->w32_flags & FD_WRITE )
{ int n;
int len = (int)(s->rdata.write.size - s->rdata.write.written);
s->w32_flags &= ~FD_WRITE;
if ( True(s, PLSOCK_WAITING) )
{ doneRequest(s);
break;
}
DEBUG(2, Sdprintf("send() %d bytes\n", s->rdata.write.size));
n = send(s->socket,
s->rdata.write.buffer + s->rdata.write.written,
len, 0);
DEBUG(2, Sdprintf("Wrote %d bytes\n", n));
if ( n < 0 )
{ s->error = WSAGetLastError();
if ( s->error == WSAEWOULDBLOCK )
break;
s->rdata.write.bytes = n;
DEBUG(1, Sdprintf("[%d]: send(%d, %d bytes): %s\n",
PL_thread_self(), s->socket, len,
WinSockError(s->error)));
doneRequest(s);
} else
s->error = 0;
s->rdata.write.written += n;
if ( s->rdata.write.written >= s->rdata.write.size )
{ s->rdata.write.bytes = (int)s->rdata.write.written;
doneRequest(s);
}
} else if ( s->w32_flags & FD_CLOSE )
{ if ( s->rdata.write.written > 0 )
s->rdata.write.bytes = (int)s->rdata.write.written;
else
s->rdata.write.bytes = -1;
doneRequest(s);
}
break;
case REQ_SENDTO:
if ( s->w32_flags & FD_WRITE )
{ int n;
s->w32_flags &= ~FD_WRITE;
if ( True(s, PLSOCK_WAITING) )
{ doneRequest(s);
break;
}
DEBUG(2, Sdprintf("sendto() %d bytes\n", s->rdata.write.size));
n = sendto(s->socket,
s->rdata.sendto.buffer,
s->rdata.sendto.size,
s->rdata.sendto.flags,
s->rdata.sendto.to,
s->rdata.sendto.tolen);
DEBUG(2, Sdprintf("Wrote %d bytes\n", n));
if ( n < 0 )
{ s->error = WSAGetLastError();
s->rdata.write.bytes = n;
DEBUG(1, Sdprintf("[%d]: send(%d, %d bytes): %s\n",
PL_thread_self(), s->socket,
s->rdata.sendto.size,
WinSockError(s->error)));
doneRequest(s);
} else
s->error = 0;
s->rdata.sendto.bytes = n;
doneRequest(s);
}
break;
}
return TRUE;
}
static LRESULT WINAPI
socket_wnd_proc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{ if ( message == WM_REQUEST )
{ plsocket **s = (plsocket **)lParam;
int i, n = (int)wParam;
for(i=0; i<n; i++)
{ if ( s[i] )
{ __try
{ if ( s[i]->magic != PLSOCK_MAGIC )
{ goto nosocket;
}
} __except(EXCEPTION_EXECUTE_HANDLER)
{ goto nosocket;
}
doRequest(s[i]);
}
}
return 0;
nosocket:
Sdprintf("%p@%d is not a socket!?\n", s[i], i);
return 0;
} else if ( message == WM_SOCKET )
{ SOCKET sock = (SOCKET) wParam;
int err = WSAGETSELECTERROR(lParam);
int evt = WSAGETSELECTEVENT(lParam);
plsocket *s;
if ( evt&FD_CLOSE )
{ DEBUG(1,
{ char *nm = event_name(evt);
Sdprintf("WM_SOCKET on %d: ev=(%s); err=%s\n",
(int)sock, nm, err ? WinSockError(err) : "none");
free(nm);
});
} else
{ DEBUG(3,
{ char *nm = event_name(evt);
Sdprintf("WM_SOCKET on %d: ev=(%s); err=%s\n",
(int)sock, nm, err ? WinSockError(err) : "none");
free(nm);
});
}
LOCK_FREE();
s = lookupOSSocket(sock);
if ( s )
{ if ( (s->w32_flags & FD_CLOSE) )
{ DEBUG(1,
{ char *nm = event_name(evt);
Sdprintf("Got event %s (err=%s) on closed socket %d=%d\n",
nm, err ? WinSockError(err) : "none", s->id, sock);
free(nm);
})
}
s->w32_flags |= evt;
if ( err == WSAECONNABORTED && s->request == REQ_READ )
{ s->rdata.read.bytes = 0;
doneRequest(s);
} else if ( err )
{ SOCKET sock = s->socket;
s->error = err;
if ( sock )
{ /* We cannot close the socket yet, since the late arrival
of FD_CLOSE might be delivered to this socket even after
it has been reallocated. Instead, calculate a timeout to
allow for the case when FD_CLOSE never comes, and then
continue as normal
*/
socketIsPendingClose(s);
}
switch(s->request)
{ case REQ_CONNECT:
break;
case REQ_NONE:
/* FIXME: is this OK? */
break;
case REQ_ACCEPT:
s->rdata.accept.slave = SOCKET_ERROR;
break;
case REQ_READ:
s->rdata.read.bytes = -1;
break;
case REQ_RECVFROM:
s->rdata.recvfrom.bytes = -1;