-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathWin32_FDAPI.cpp
1235 lines (1080 loc) · 41.8 KB
/
Win32_FDAPI.cpp
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
/*
* Copyright (c), Microsoft Open Technologies, Inc.
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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 HOLDER 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.
*/
#include "win32_types.h"
#define FDAPI_NOCRTREDEFS
#include "Win32_FDAPI.h"
#include "win32_rfdmap.h"
#include <exception>
#include <mswsock.h>
#include <sys/stat.h>
#include "Win32_fdapi_crt.h"
#include "Win32_variadicFunctor.h"
#include "Win32_ANSI.h"
#include "Win32_RedisLog.h"
#include "Win32_Common.h"
#include "Win32_Error.h"
#include "Win32_Assert.h"
using namespace std;
#define CATCH_AND_REPORT() catch(const std::exception &){::redisLog(REDIS_WARNING, "FDAPI: std exception");}catch(...){::redisLog(REDIS_WARNING, "FDAPI: other exception");}
extern "C" {
// Unix compatible FD based routines
fdapi_accept win32_accept = NULL;
fdapi_access win32_access = NULL;
fdapi_bind win32_bind = NULL;
fdapi_connect win32_connect = NULL;
fdapi_fcntl win32_fcntl = NULL;
fdapi_fstat win32_fdapi_fstat64 = NULL;
fdapi_fsync win32_fsync = NULL;
fdapi_ftruncate win32_ftruncate = NULL;
fdapi_freeaddrinfo win32_freeaddrinfo = NULL;
fdapi_getaddrinfo win32_getaddrinfo = NULL;
fdapi_getpeername win32_getpeername = NULL;
fdapi_getsockname win32_getsockname = NULL;
fdapi_getsockopt win32_getsockopt = NULL;
fdapi_htonl win32_htonl = NULL;
fdapi_htons win32_htons = NULL;
fdapi_isatty win32_isatty = NULL;
fdapi_inet_ntop win32_inet_ntop = NULL;
fdapi_inet_pton win32_inet_pton = NULL;
fdapi_listen win32_listen = NULL;
fdapi_lseek64 win32_lseek64 = NULL;
fdapi_ntohl win32_ntohl = NULL;
fdapi_ntohs win32_ntohs = NULL;
fdapi_open win32_open = NULL;
fdapi_pipe win32_pipe = NULL;
fdapi_poll win32_poll = NULL;
fdapi_read win32_read = NULL;
fdapi_select win32_select = NULL;
fdapi_setsockopt win32_setsockopt = NULL;
fdapi_socket win32_socket = NULL;
fdapi_write win32_write = NULL;
}
auto f_WSACleanup = dllfunctor_stdcall<int>("ws2_32.dll", "WSACleanup");
auto f_WSAFDIsSet = dllfunctor_stdcall<int, SOCKET, fd_set*>("ws2_32.dll", "__WSAFDIsSet");
auto f_WSAGetLastError = dllfunctor_stdcall<int>("ws2_32.dll", "WSAGetLastError");
auto f_WSAGetOverlappedResult = dllfunctor_stdcall<BOOL, SOCKET, LPWSAOVERLAPPED, LPDWORD, BOOL, LPDWORD>("ws2_32.dll", "WSAGetOverlappedResult");
auto f_WSADuplicateSocket = dllfunctor_stdcall<int, SOCKET, DWORD, LPWSAPROTOCOL_INFO>("ws2_32.dll", "WSADuplicateSocketW");
auto f_WSAIoctl = dllfunctor_stdcall<int, SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPVOID, LPWSAOVERLAPPED, LPWSAOVERLAPPED_COMPLETION_ROUTINE>("ws2_32.dll", "WSAIoctl");
auto f_WSARecv = dllfunctor_stdcall<int, SOCKET, LPWSABUF, DWORD, LPDWORD, LPDWORD, LPWSAOVERLAPPED, LPWSAOVERLAPPED_COMPLETION_ROUTINE>("ws2_32.dll", "WSARecv");
auto f_WSASocket = dllfunctor_stdcall<SOCKET, int, int, int, LPWSAPROTOCOL_INFO, GROUP, DWORD>("ws2_32.dll", "WSASocketW");
auto f_WSASend = dllfunctor_stdcall<int, SOCKET, LPWSABUF, DWORD, LPDWORD, DWORD, LPWSAOVERLAPPED, LPWSAOVERLAPPED_COMPLETION_ROUTINE>("ws2_32.dll", "WSASend");
auto f_WSAStartup = dllfunctor_stdcall<int, WORD, LPWSADATA>("ws2_32.dll", "WSAStartup");
auto f_ioctlsocket = dllfunctor_stdcall<int, SOCKET, long, u_long*>("ws2_32.dll", "ioctlsocket");
auto f_accept = dllfunctor_stdcall<SOCKET, SOCKET, struct sockaddr*, int*>("ws2_32.dll", "accept");
auto f_bind = dllfunctor_stdcall<int, SOCKET, const struct sockaddr*, int>("ws2_32.dll", "bind");
auto f_closesocket = dllfunctor_stdcall<int, SOCKET>("ws2_32.dll", "closesocket");
auto f_connect = dllfunctor_stdcall<int, SOCKET, const struct sockaddr*, int>("ws2_32.dll", "connect");
auto f_freeaddrinfo = dllfunctor_stdcall<void, addrinfo*>("ws2_32.dll", "freeaddrinfo");
auto f_getaddrinfo = dllfunctor_stdcall<int, PCSTR, PCSTR, const ADDRINFOA*, ADDRINFOA**>("ws2_32.dll", "getaddrinfo");
auto f_gethostbyname = dllfunctor_stdcall<struct hostent*, const char*>("ws2_32.dll", "gethostbyname");
auto f_getpeername = dllfunctor_stdcall<int, SOCKET, struct sockaddr*, int*>("ws2_32.dll", "getpeername");
auto f_getsockname = dllfunctor_stdcall<int, SOCKET, struct sockaddr*, int*>("ws2_32.dll", "getsockname");
auto f_getsockopt = dllfunctor_stdcall<int, SOCKET, int, int, char*, int*>("ws2_32.dll", "getsockopt");
auto f_htonl = dllfunctor_stdcall<u_long, u_long>("ws2_32.dll", "htonl");
auto f_htons = dllfunctor_stdcall<u_short, u_short>("ws2_32.dll", "htons");
auto f_listen = dllfunctor_stdcall<int, SOCKET, int>("ws2_32.dll", "listen");
auto f_ntohs = dllfunctor_stdcall<u_short, u_short>("ws2_32.dll", "ntohs");
auto f_ntohl = dllfunctor_stdcall<u_long, u_long>("ws2_32.dll", "ntohl");
auto f_recv = dllfunctor_stdcall<int, SOCKET, char*, int, int>("ws2_32.dll", "recv");
auto f_select = dllfunctor_stdcall<int, int, fd_set*, fd_set*, fd_set*, const struct timeval*>("ws2_32.dll", "select");
auto f_send = dllfunctor_stdcall<int, SOCKET, const char*, int, int>("ws2_32.dll", "send");
auto f_setsockopt = dllfunctor_stdcall<int, SOCKET, int, int, const char*, int>("ws2_32.dll", "setsockopt");
auto f_socket = dllfunctor_stdcall<SOCKET, int, int, int>("ws2_32.dll", "socket");
#ifndef SIO_LOOPBACK_FAST_PATH
const DWORD SIO_LOOPBACK_FAST_PATH = 0x98000010; // from Win8 SDK
#endif
void EnableFastLoopback(SOCKET socket) {
// If Win8+ (6.2), use fast path option on loopback
if (WindowsVersion::getInstance().IsAtLeast_6_2()) {
int enabled = 1;
DWORD result_byte_count = -1;
int result = f_WSAIoctl(socket, SIO_LOOPBACK_FAST_PATH, &enabled, sizeof(enabled), NULL, 0, &result_byte_count, NULL, NULL);
if (result != 0) {
throw std::system_error(f_WSAGetLastError(), system_category(), "WSAIoctl failed");
}
}
}
static fnWSIOCP_CloseSocketStateRFD* wsiocp_CloseSocketState;
void FDAPI_SetCloseSocketState(fnWSIOCP_CloseSocketStateRFD* func) {
wsiocp_CloseSocketState = func;
}
int FDAPI_WSAGetLastError(void) {
return f_WSAGetLastError();
}
BOOL FDAPI_WSAGetOverlappedResult(int rfd, LPWSAOVERLAPPED lpOverlapped, LPDWORD lpcbTransfer, BOOL fWait, LPDWORD lpdwFlags) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
return f_WSAGetOverlappedResult(socket, lpOverlapped, lpcbTransfer, fWait, lpdwFlags);
}
} CATCH_AND_REPORT();
errno = EBADF;
return SOCKET_ERROR;
}
/* This method should only be called to close the sockets duplicated
* by the child process.
*/
BOOL FDAPI_CloseDuplicatedSocket(int rfd) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
RFDMap::getInstance().removeRFDToSocketInfo(rfd);
RFDMap::getInstance().removeSocketToRFD(socket);
return f_closesocket(socket);
}
} CATCH_AND_REPORT();
errno = EBADF;
return FALSE;
}
int FDAPI_WSADuplicateSocket(int rfd, DWORD dwProcessId, LPWSAPROTOCOL_INFO lpProtocolInfo) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
return f_WSADuplicateSocket(socket, dwProcessId, lpProtocolInfo);
}
} CATCH_AND_REPORT();
errno = EBADF;
return SOCKET_ERROR;
}
int FDAPI_WSASocket(int af, int type, int protocol, LPWSAPROTOCOL_INFO lpProtocolInfo, GROUP g, DWORD dwFlags) {
try {
SOCKET socket = f_WSASocket(af,
type,
protocol,
lpProtocolInfo,
g,
dwFlags);
if (socket != INVALID_SOCKET) {
return RFDMap::getInstance().addSocket(socket);
}
} CATCH_AND_REPORT();
return -1;
}
int FDAPI_WSASend(int rfd, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesSent, DWORD dwFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
return f_WSASend(socket,
lpBuffers,
dwBufferCount,
lpNumberOfBytesSent,
dwFlags,
lpOverlapped,
lpCompletionRoutine);
}
} CATCH_AND_REPORT();
errno = EBADF;
return SOCKET_ERROR;
}
int FDAPI_WSARecv(int rfd, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
return f_WSARecv(socket,
lpBuffers,
dwBufferCount,
lpNumberOfBytesRecvd,
lpFlags,
lpOverlapped,
lpCompletionRoutine);
}
} CATCH_AND_REPORT();
errno = EBADF;
return SOCKET_ERROR;
}
int FDAPI_WSAIoctl(int rfd, DWORD dwIoControlCode, LPVOID lpvInBuffer, DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer, LPDWORD lpcbBytesReturned, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
if (f_WSAIoctl(socket,
dwIoControlCode,
lpvInBuffer,
cbInBuffer,
lpvOutBuffer,
cbOutBuffer,
lpcbBytesReturned,
lpOverlapped,
lpCompletionRoutine) == 0) {
return 0;
} else {
errno = f_WSAGetLastError();
return SOCKET_ERROR;
}
}
} CATCH_AND_REPORT();
errno = EBADF;
return SOCKET_ERROR;
}
void FDAPI_SaveSocketAddrStorage(int rfd, SOCKADDR_STORAGE* socketAddrStorage) {
SocketInfo* socket_info = RFDMap::getInstance().lookupSocketInfo(rfd);
if (socket_info != NULL) {
memcpy(&(socket_info->socketAddrStorage), socketAddrStorage, sizeof(SOCKADDR_STORAGE));
}
}
BOOL FDAPI_SocketAttachIOCP(int rfd, HANDLE iocph) {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
// Set the socket to nonblocking mode
DWORD yes = 1;
if (f_ioctlsocket(socket, FIONBIO, &yes) != SOCKET_ERROR) {
// Make the socket non-inheritable
if (SetHandleInformation((HANDLE) socket, HANDLE_FLAG_INHERIT, 0)) {
// Associate it with the I/O completion port.
// Use the rfd as the completion key.
if (CreateIoCompletionPort((HANDLE) socket,
iocph,
(ULONG_PTR) rfd,
0) != NULL) {
return TRUE;
}
}
}
errno = f_WSAGetLastError();
} else {
errno = EBADF;
}
return FALSE;
}
BOOL FDAPI_AcceptEx(int listenFD, int acceptFD, PVOID lpOutputBuffer, DWORD dwReceiveDataLength, DWORD dwLocalAddressLength, DWORD dwRemoteAddressLength, LPDWORD lpdwBytesReceived, LPOVERLAPPED lpOverlapped) {
try {
SOCKET sListen = RFDMap::getInstance().lookupSocket(listenFD);
SOCKET sAccept = RFDMap::getInstance().lookupSocket(acceptFD);
if (sListen != INVALID_SOCKET && sAccept != INVALID_SOCKET) {
LPFN_ACCEPTEX acceptex;
const GUID wsaid_acceptex = WSAID_ACCEPTEX;
DWORD bytes;
if (SOCKET_ERROR == f_WSAIoctl(sListen,
SIO_GET_EXTENSION_FUNCTION_POINTER,
(void *) &wsaid_acceptex,
sizeof(GUID),
&acceptex,
sizeof(LPFN_ACCEPTEX),
&bytes,
NULL,
NULL)) {
return FALSE;
}
return acceptex(sListen, sAccept, lpOutputBuffer, dwReceiveDataLength, dwLocalAddressLength, dwRemoteAddressLength, lpdwBytesReceived, lpOverlapped);
}
} CATCH_AND_REPORT();
return FALSE;
}
BOOL FDAPI_ConnectEx(int rfd, const struct sockaddr *name, int namelen, PVOID lpSendBuffer, DWORD dwSendDataLength, LPDWORD lpdwBytesSent, LPOVERLAPPED lpOverlapped) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
LPFN_CONNECTEX connectex;
const GUID wsaid_connectex = WSAID_CONNECTEX;
DWORD bytes;
if (SOCKET_ERROR == f_WSAIoctl(socket,
SIO_GET_EXTENSION_FUNCTION_POINTER,
(void *) &wsaid_connectex,
sizeof(GUID),
&connectex,
sizeof(LPFN_ACCEPTEX),
&bytes,
NULL,
NULL)) {
return FALSE;
}
EnableFastLoopback(socket);
return connectex(socket,
name,namelen,
lpSendBuffer,
dwSendDataLength,
lpdwBytesSent,
lpOverlapped);
}
} CATCH_AND_REPORT();
return FALSE;
}
void FDAPI_GetAcceptExSockaddrs(int rfd, PVOID lpOutputBuffer, DWORD dwReceiveDataLength, DWORD dwLocalAddressLength, DWORD dwRemoteAddressLength, LPSOCKADDR *LocalSockaddr, LPINT LocalSockaddrLength, LPSOCKADDR *RemoteSockaddr, LPINT RemoteSockaddrLength) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
LPFN_GETACCEPTEXSOCKADDRS getacceptsockaddrs;
const GUID wsaid_getacceptsockaddrs = WSAID_GETACCEPTEXSOCKADDRS;
DWORD bytes;
if (SOCKET_ERROR == f_WSAIoctl(socket,
SIO_GET_EXTENSION_FUNCTION_POINTER,
(void *) &wsaid_getacceptsockaddrs,
sizeof(GUID),
&getacceptsockaddrs,
sizeof(LPFN_ACCEPTEX),
&bytes,
NULL,
NULL)) {
return;
}
getacceptsockaddrs(lpOutputBuffer,
dwReceiveDataLength,
dwLocalAddressLength,
dwRemoteAddressLength,
LocalSockaddr,
LocalSockaddrLength,
RemoteSockaddr,
RemoteSockaddrLength);
}
} CATCH_AND_REPORT();
}
int FDAPI_UpdateAcceptContext(int rfd) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
return f_setsockopt(socket,
SOL_SOCKET,
SO_UPDATE_ACCEPT_CONTEXT,
(char*) &socket,
sizeof(SOCKET));
}
} CATCH_AND_REPORT();
errno = EBADF;
return SOCKET_ERROR;
}
void** FDAPI_GetSocketStatePtr(int rfd) {
SocketInfo* socket_info = RFDMap::getInstance().lookupSocketInfo(rfd);
if (socket_info == NULL) {
return NULL;
} else {
return &(socket_info->state);
}
}
void FDAPI_ClearSocketInfo(int rfd) {
SocketInfo* socketInfo = RFDMap::getInstance().lookupSocketInfo(rfd);
ASSERT(socketInfo != NULL);
ASSERT(socketInfo->socket == INVALID_SOCKET);
if (socketInfo != NULL) {
if (socketInfo->socket == INVALID_SOCKET) {
RFDMap::getInstance().removeRFDToSocketInfo(rfd);
return;
} else {
redisLog(REDIS_WARNING, "FDAPI_ClearSocketInfo called on non closed socket.");
}
} else {
redisLog(REDIS_WARNING, "FDAPI_ClearSocketInfo called on non attached socket.");
}
}
int FDAPI_PipeSetNonBlock(int rfd, int non_blocking) {
try {
int crt_fd = RFDMap::getInstance().lookupCrtFD(rfd);
if (crt_fd != INVALID_FD) {
HANDLE h = (HANDLE) crt_get_osfhandle(crt_fd);
if (h == INVALID_HANDLE_VALUE) {
errno = EBADF;
return -1;
}
if (GetFileType(h) == FILE_TYPE_PIPE) {
/* h is a pipe or socket. */
DWORD state;
if (GetNamedPipeHandleState(h, &state, NULL, NULL, NULL, NULL, 0)) {
/* h is a pipe. */
if ((state & PIPE_NOWAIT) != 0) {
if (non_blocking)
return 0;
state &= ~PIPE_NOWAIT;
} else {
if (!non_blocking)
return 0;
state |= PIPE_NOWAIT;
}
if (SetNamedPipeHandleState(h, &state, NULL, NULL)) {
return 0;
}
errno = EINVAL;
return -1;
} else {
/* h is a socket. */
errno = EINVAL;
return -1;
}
} else {
/* Win32 does not support non-blocking on regular files. */
if (!non_blocking) {
return 0;
}
errno = ENOTSUP;
return -1;
}
return 0;
}
} CATCH_AND_REPORT();
errno = EBADF;
return -1;
}
int FDAPI_pipe(int *pfds) {
int result = -1;
try {
// Not passing _O_NOINHERIT, the underlying handles are inheritable by default
result = crt_pipe(pfds, 8192, _O_BINARY);
if (result == 0) {
pfds[0] = RFDMap::getInstance().addCrtFD(pfds[0]);
pfds[1] = RFDMap::getInstance().addCrtFD(pfds[1]);
}
} CATCH_AND_REPORT();
return result;
}
int FDAPI_socket(int af, int type, int protocol) {
try {
SOCKET socket = f_socket(af, type, protocol);
if (socket != INVALID_SOCKET) {
return RFDMap::getInstance().addSocket(socket);
} else {
errno = f_WSAGetLastError();
return -1;
}
} CATCH_AND_REPORT();
errno = EBADF;
return -1;
}
// In unix a fd is a fd. All are closed with close().
int FDAPI_close(int rfd) {
try {
SocketInfo* socketInfo = RFDMap::getInstance().lookupSocketInfo(rfd);
if (socketInfo != NULL) {
ASSERT(socketInfo->socket != INVALID_SOCKET);
if (socketInfo->socket != INVALID_SOCKET) {
SOCKET socket = socketInfo->socket;
socketInfo->socket = INVALID_SOCKET;
if (socketInfo->state != NULL) {
if (wsiocp_CloseSocketState != NULL) {
if (wsiocp_CloseSocketState(rfd)) {
RFDMap::getInstance().removeRFDToSocketInfo(rfd);
}
}
} else {
RFDMap::getInstance().removeRFDToSocketInfo(rfd);
}
RFDMap::getInstance().removeSocketToRFD(socket);
return f_closesocket(socket);
}
} else {
int crt_fd = RFDMap::getInstance().lookupCrtFD(rfd);
if (crt_fd != INVALID_FD) {
RFDMap::getInstance().removeCrtFD(crt_fd);
return crt_close(crt_fd);
}
}
} CATCH_AND_REPORT();
errno = EBADF;
return -1;
}
int FDAPI_open(const char * _Filename, int _OpenFlag, int flags = 0) {
try {
int crt_fd = crt_open(_Filename, _OpenFlag, flags);
if (crt_fd != INVALID_FD) {
return RFDMap::getInstance().addCrtFD(crt_fd);
}
} CATCH_AND_REPORT();
errno = GetLastError();
return -1;
}
int FDAPI_accept(int rfd, struct sockaddr *addr, socklen_t *addrlen) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
SOCKET sAccept = f_accept(socket, addr, addrlen);
if (sAccept != INVALID_SOCKET) {
return RFDMap::getInstance().addSocket(sAccept);
} else {
errno = f_WSAGetLastError();
if ((errno == ENOENT) || (errno == WSAEWOULDBLOCK)) {
errno = EAGAIN;
return -1;
}
}
}
} CATCH_AND_REPORT();
errno = EBADF;
return -1;
}
int FDAPI_setsockopt(int rfd, int level, int optname, const void *optval, socklen_t optlen) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
if (f_setsockopt(socket, level, optname, (const char*) optval, optlen) == 0) {
return 0;
} else {
errno = f_WSAGetLastError();
return -1;
}
}
} CATCH_AND_REPORT();
errno = EBADF;
return -1;
}
int FDAPI_fcntl(int rfd, int cmd, int flags = 0 ) {
try {
SocketInfo* socket_info = RFDMap::getInstance().lookupSocketInfo(rfd);
if (socket_info != NULL && socket_info->socket != INVALID_SOCKET) {
switch (cmd) {
case F_GETFL:
{
// Since in WinSock there is no way to determine if a socket
// is blocking, we keep track of this separately.
return socket_info->flags;
}
case F_SETFL:
{
u_long fionbio_flags = (flags & O_NONBLOCK);
if (SOCKET_ERROR == f_ioctlsocket(socket_info->socket,
FIONBIO,
&fionbio_flags)) {
errno = f_WSAGetLastError();
return -1;
} else {
socket_info->flags = flags;
return 0;
}
break;
}
default:
{
ASSERT(cmd == F_GETFL || cmd == F_SETFL);
return -1;
}
}
}
} CATCH_AND_REPORT();
errno = EBADF;
return -1;
}
int FDAPI_poll(struct pollfd *fds, nfds_t nfds, int timeout) {
try {
struct pollfd* pollCopy = new struct pollfd[nfds];
if (pollCopy == NULL) {
errno = ENOMEM;
return -1;
}
// NOTE: Treating the fds.fd as a Redis file descriptor and converting to a SOCKET for WSAPoll.
for (nfds_t n = 0; n < nfds; n ++) {
pollCopy[n].fd = RFDMap::getInstance().lookupSocket((RFD)(fds[n].fd));
pollCopy[n].events = fds[n].events;
pollCopy[n].revents = fds[n].revents;
}
if (WindowsVersion::getInstance().IsAtLeast_6_0()) {
static auto f_WSAPoll = dllfunctor_stdcall<int, WSAPOLLFD*, ULONG, INT>("ws2_32.dll", "WSAPoll");
// WSAPoll implementation has a bug that cause the client
// to wait forever on a non-existant endpoint
// See https://github.com/MSOpenTech/redis/issues/214
int ret = f_WSAPoll(pollCopy, nfds, timeout);
for (nfds_t n = 0; n < nfds; n++) {
fds[n].events = pollCopy[n].events;
fds[n].revents = pollCopy[n].revents;
}
delete pollCopy;
pollCopy = NULL;
return ret;
} else {
int ret;
fd_set readSet;
fd_set writeSet;
fd_set excepSet;
FD_ZERO(&readSet);
FD_ZERO(&writeSet);
FD_ZERO(&excepSet);
if (nfds >= FD_SETSIZE) {
errno = EINVAL;
return -1;
}
nfds_t i;
for (i = 0; i < nfds; i++) {
if (fds[i].fd == INVALID_SOCKET) {
continue;
}
if (pollCopy[i].fd >= FD_SETSIZE) {
errno = EINVAL;
return -1;
}
if (pollCopy[i].events & POLLIN) FD_SET(pollCopy[i].fd, &readSet);
if (pollCopy[i].events & POLLOUT) FD_SET(pollCopy[i].fd, &writeSet);
if (pollCopy[i].events & POLLERR) FD_SET(pollCopy[i].fd, &excepSet);
}
if (timeout < 0) {
ret = select(0, &readSet, &writeSet, &excepSet, NULL);
} else {
struct timeval tv;
tv.tv_sec = timeout / 1000;
tv.tv_usec = 1000 * (timeout % 1000);
ret = select(0, &readSet, &writeSet, &excepSet, &tv);
}
if (ret < 0) {
return ret;
}
for (i = 0; i < nfds; i++) {
fds[i].revents = 0;
if (f_WSAFDIsSet(pollCopy[i].fd, &readSet)) fds[i].revents |= POLLIN;
if (f_WSAFDIsSet(pollCopy[i].fd, &writeSet)) fds[i].revents |= POLLOUT;
if (f_WSAFDIsSet(pollCopy[i].fd, &excepSet)) fds[i].revents |= POLLERR;
}
delete pollCopy;
pollCopy = NULL;
return ret;
}
} CATCH_AND_REPORT();
errno = EBADF;
return -1;
}
int FDAPI_getsockopt(int rfd, int level, int optname, void *optval, socklen_t *optlen) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
return f_getsockopt(socket, level, optname, (char*) optval, optlen);
}
} CATCH_AND_REPORT();
errno = EBADF;
return -1;
}
int FDAPI_connect(int rfd, const struct sockaddr *addr, size_t addrlen) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
EnableFastLoopback(socket);
int result = f_connect(socket, addr, (int) addrlen);
errno = f_WSAGetLastError();
if ((errno == WSAEINVAL) || (errno == WSAEWOULDBLOCK) || (errno == WSA_IO_PENDING)) {
errno = EINPROGRESS;
}
return result;
}
} CATCH_AND_REPORT();
errno = EBADF;
return -1;
}
ssize_t FDAPI_read(int rfd, void *buf, size_t count) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
int retval = f_recv(socket, (char*) buf, (unsigned int) count, 0);
if (retval == -1) {
errno = GetLastError();
if (errno == WSAEWOULDBLOCK) {
errno = EAGAIN;
}
}
return retval;
} else {
int crt_fd = RFDMap::getInstance().lookupCrtFD(rfd);
if (crt_fd != INVALID_FD) {
int retval = crt_read(crt_fd, buf, (unsigned int) count);
if (retval == -1) {
errno = GetLastError();
}
return retval;
} else {
errno = EBADF;
return 0;
}
}
} CATCH_AND_REPORT();
errno = EBADF;
return -1;
}
ssize_t FDAPI_write(int rfd, const void *buf, size_t count) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
int ret = f_send(socket, (char*) buf, (unsigned int) count, 0);
if (ret == SOCKET_ERROR) {
set_errno_from_last_error();
}
return ret;
} else {
int crt_fd = RFDMap::getInstance().lookupCrtFD(rfd);
if (crt_fd != INVALID_FD) {
if (crt_fd == _fileno(stdout)) {
DWORD bytesWritten = 0;
if (FALSE != ParseAndPrintANSIString(GetStdHandle(STD_OUTPUT_HANDLE), buf, (DWORD) count, &bytesWritten)) {
return (int) bytesWritten;
} else {
errno = GetLastError();
return 0;
}
} else if (crt_fd == _fileno(stderr)) {
DWORD bytesWritten = 0;
if (FALSE != ParseAndPrintANSIString(GetStdHandle(STD_ERROR_HANDLE), buf, (DWORD) count, &bytesWritten)) {
return (int) bytesWritten;
} else {
errno = GetLastError();
return 0;
}
} else {
int retval = crt_write(crt_fd, buf, (unsigned int) count);
if (retval == -1) {
errno = GetLastError();
}
return retval;
}
} else {
errno = EBADF;
return 0;
}
}
} CATCH_AND_REPORT();
errno = EBADF;
return -1;
}
int FDAPI_fsync(int rfd) {
try {
int crt_fd = RFDMap::getInstance().lookupCrtFD(rfd);
if (crt_fd != INVALID_FD) {
HANDLE h = (HANDLE) crt_get_osfhandle(crt_fd);
if (h == INVALID_HANDLE_VALUE) {
errno = EBADF;
return -1;
}
if (!FlushFileBuffers(h)) {
DWORD err = GetLastError();
switch (err) {
case ERROR_INVALID_HANDLE:
errno = EINVAL;
break;
default:
errno = EIO;
}
return -1;
}
}
return 0;
} CATCH_AND_REPORT();
errno = EBADF;
return -1;
}
int FDAPI_fstat64(int rfd, struct __stat64 *buffer) {
try {
int crt_fd = RFDMap::getInstance().lookupCrtFD(rfd);
if (crt_fd != INVALID_FD) {
return _fstat64(crt_fd, buffer);
}
} CATCH_AND_REPORT();
errno = EBADF;
return -1;
}
int FDAPI_listen(int rfd, int backlog) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
EnableFastLoopback(socket);
int result = f_listen(socket, backlog);
if (result != 0){
errno = f_WSAGetLastError();
}
return result;
} else {
errno = EBADF;
return -1;
}
} CATCH_AND_REPORT();
errno = EBADF;
return -1;
}
int FDAPI_ftruncate(int rfd, PORT_LONGLONG length) {
try {
int crt_fd = RFDMap::getInstance().lookupCrtFD(rfd);
if (crt_fd != INVALID_FD) {
HANDLE h = (HANDLE) crt_get_osfhandle(crt_fd);
if (h == INVALID_HANDLE_VALUE) {
errno = EBADF;
return -1;
}
LARGE_INTEGER l, o;
l.QuadPart = length;
if (!SetFilePointerEx(h, l, &o, FILE_BEGIN)) return -1;
if (!SetEndOfFile(h)) return -1;
return 0;
}
} CATCH_AND_REPORT();
errno = EBADF;
return -1;
}
int FDAPI_bind(int rfd, const struct sockaddr *addr, socklen_t addrlen) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
return f_bind(socket, addr, addrlen);
} else {
errno = EBADF;
return 0;
}
} CATCH_AND_REPORT();
errno = EBADF;
return -1;
}
struct hostent* FDAPI_gethostbyname(const char *name) {
return f_gethostbyname(name);
}
u_short FDAPI_htons(u_short hostshort) {
return f_htons(hostshort);
}
u_long FDAPI_htonl(u_long hostlong) {
return f_htonl(hostlong);
}
int FDAPI_getpeername(int rfd, struct sockaddr *addr, socklen_t * addrlen) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
int result = f_getpeername(socket, addr, addrlen);
// Workaround for getpeername failing to retrieve the endpoint address
if (result != 0) {
SocketInfo* socket_info = RFDMap::getInstance().lookupSocketInfo(rfd);
if (socket_info != NULL) {
memcpy(addr, &(socket_info->socketAddrStorage), sizeof(SOCKADDR_STORAGE));
*addrlen = sizeof(SOCKADDR_STORAGE);
return 0;
}
}
return result;
}
} CATCH_AND_REPORT();
errno = EBADF;
return SOCKET_ERROR;
}
int FDAPI_getsockname(int rfd, struct sockaddr* addrsock, int* addrlen) {
try {
SOCKET socket = RFDMap::getInstance().lookupSocket(rfd);
if (socket != INVALID_SOCKET) {
return f_getsockname(socket, addrsock, addrlen);
}
} CATCH_AND_REPORT();
errno = EBADF;
return SOCKET_ERROR;
}
u_short FDAPI_ntohs(u_short netshort) {
return f_ntohs( netshort );
}
int FDAPI_setmode(int fd, int mode) {
return crt_setmode(fd, mode);
}
size_t FDAPI_fwrite(const void *buffer, size_t size, size_t count, FILE *file) {
return crt_fwrite(buffer, size, count, file);
}
int FDAPI_fclose(FILE *file) {
int crt_fd = crt_fileno(file);
if (crt_fd != INVALID_FD) {
RFDMap::getInstance().removeCrtFD(crt_fd);
}
return crt_fclose(file);
}
int FDAPI_fileno(FILE *file) {
int crt_fd = crt_fileno(file);
if (crt_fd != INVALID_FD) {
// If crt_fd is already mapped, addCrtFD() will return the existing rfd.
return RFDMap::getInstance().addCrtFD(crt_fd);
}
return -1;