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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
|
/* $Id: socket.cpp $ */
/** @file
* IPRT - Network Sockets.
*/
/*
* Copyright (C) 2006-2010 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#ifdef RT_OS_WINDOWS
# include <winsock2.h>
#else /* !RT_OS_WINDOWS */
# include <errno.h>
# include <sys/stat.h>
# include <sys/socket.h>
# include <netinet/in.h>
# include <netinet/tcp.h>
# include <arpa/inet.h>
# ifdef IPRT_WITH_TCPIP_V6
# include <netinet6/in6.h>
# endif
# include <sys/un.h>
# include <netdb.h>
# include <unistd.h>
# include <fcntl.h>
# include <sys/uio.h>
#endif /* !RT_OS_WINDOWS */
#include <limits.h>
#include "internal/iprt.h"
#include <iprt/socket.h>
#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/err.h>
#include <iprt/mempool.h>
#include <iprt/poll.h>
#include <iprt/string.h>
#include <iprt/thread.h>
#include <iprt/time.h>
#include <iprt/mem.h>
#include <iprt/sg.h>
#include "internal/magics.h"
#include "internal/socket.h"
/*******************************************************************************
* Defined Constants And Macros *
*******************************************************************************/
/* non-standard linux stuff (it seems). */
#ifndef MSG_NOSIGNAL
# define MSG_NOSIGNAL 0
#endif
/* Windows has different names for SHUT_XXX. */
#ifndef SHUT_RDWR
# ifdef SD_BOTH
# define SHUT_RDWR SD_BOTH
# else
# define SHUT_RDWR 2
# endif
#endif
#ifndef SHUT_WR
# ifdef SD_SEND
# define SHUT_WR SD_SEND
# else
# define SHUT_WR 1
# endif
#endif
#ifndef SHUT_RD
# ifdef SD_RECEIVE
# define SHUT_RD SD_RECEIVE
# else
# define SHUT_RD 0
# endif
#endif
/* fixup backlevel OSes. */
#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
# define socklen_t int
#endif
/** How many pending connection. */
#define RTTCP_SERVER_BACKLOG 10
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
/**
* Socket handle data.
*
* This is mainly required for implementing RTPollSet on Windows.
*/
typedef struct RTSOCKETINT
{
/** Magic number (RTSOCKET_MAGIC). */
uint32_t u32Magic;
/** Exclusive user count.
* This is used to prevent two threads from accessing the handle concurrently.
* It can be higher than 1 if this handle is reference multiple times in a
* polling set (Windows). */
uint32_t volatile cUsers;
/** The native socket handle. */
RTSOCKETNATIVE hNative;
/** Indicates whether the handle has been closed or not. */
bool volatile fClosed;
#ifdef RT_OS_WINDOWS
/** The event semaphore we've associated with the socket handle.
* This is WSA_INVALID_EVENT if not done. */
WSAEVENT hEvent;
/** The pollset currently polling this socket. This is NIL if no one is
* polling. */
RTPOLLSET hPollSet;
/** The events we're polling for. */
uint32_t fPollEvts;
/** The events we're currently subscribing to with WSAEventSelect.
* This is ZERO if we're currently not subscribing to anything. */
uint32_t fSubscribedEvts;
#endif /* RT_OS_WINDOWS */
} RTSOCKETINT;
/**
* Address union used internally for things like getpeername and getsockname.
*/
typedef union RTSOCKADDRUNION
{
struct sockaddr Addr;
struct sockaddr_in Ipv4;
#ifdef IPRT_WITH_TCPIP_V6
struct sockaddr_in6 Ipv6;
#endif
} RTSOCKADDRUNION;
/**
* Get the last error as an iprt status code.
*
* @returns IPRT status code.
*/
DECLINLINE(int) rtSocketError(void)
{
#ifdef RT_OS_WINDOWS
return RTErrConvertFromWin32(WSAGetLastError());
#else
return RTErrConvertFromErrno(errno);
#endif
}
/**
* Resets the last error.
*/
DECLINLINE(void) rtSocketErrorReset(void)
{
#ifdef RT_OS_WINDOWS
WSASetLastError(0);
#else
errno = 0;
#endif
}
/**
* Get the last resolver error as an iprt status code.
*
* @returns iprt status code.
*/
int rtSocketResolverError(void)
{
#ifdef RT_OS_WINDOWS
return RTErrConvertFromWin32(WSAGetLastError());
#else
switch (h_errno)
{
case HOST_NOT_FOUND:
return VERR_NET_HOST_NOT_FOUND;
case NO_DATA:
return VERR_NET_ADDRESS_NOT_AVAILABLE;
case NO_RECOVERY:
return VERR_IO_GEN_FAILURE;
case TRY_AGAIN:
return VERR_TRY_AGAIN;
default:
return VERR_UNRESOLVED_ERROR;
}
#endif
}
/**
* Tries to lock the socket for exclusive usage by the calling thread.
*
* Call rtSocketUnlock() to unlock.
*
* @returns @c true if locked, @c false if not.
* @param pThis The socket structure.
*/
DECLINLINE(bool) rtSocketTryLock(RTSOCKETINT *pThis)
{
return ASMAtomicCmpXchgU32(&pThis->cUsers, 1, 0);
}
/**
* Unlocks the socket.
*
* @param pThis The socket structure.
*/
DECLINLINE(void) rtSocketUnlock(RTSOCKETINT *pThis)
{
ASMAtomicCmpXchgU32(&pThis->cUsers, 0, 1);
}
/**
* Creates an IPRT socket handle for a native one.
*
* @returns IPRT status code.
* @param ppSocket Where to return the IPRT socket handle.
* @param hNative The native handle.
*/
int rtSocketCreateForNative(RTSOCKETINT **ppSocket, RTSOCKETNATIVE hNative)
{
RTSOCKETINT *pThis = (RTSOCKETINT *)RTMemPoolAlloc(RTMEMPOOL_DEFAULT, sizeof(*pThis));
if (!pThis)
return VERR_NO_MEMORY;
pThis->u32Magic = RTSOCKET_MAGIC;
pThis->cUsers = 0;
pThis->hNative = hNative;
pThis->fClosed = false;
#ifdef RT_OS_WINDOWS
pThis->hEvent = WSA_INVALID_EVENT;
pThis->hPollSet = NIL_RTPOLLSET;
pThis->fPollEvts = 0;
pThis->fSubscribedEvts = 0;
#endif
*ppSocket = pThis;
return VINF_SUCCESS;
}
RTDECL(int) RTSocketFromNative(PRTSOCKET phSocket, RTHCINTPTR uNative)
{
AssertReturn(uNative != NIL_RTSOCKETNATIVE, VERR_INVALID_PARAMETER);
#ifndef RT_OS_WINDOWS
AssertReturn(uNative >= 0, VERR_INVALID_PARAMETER);
#endif
AssertPtrReturn(phSocket, VERR_INVALID_POINTER);
return rtSocketCreateForNative(phSocket, uNative);
}
/**
* Wrapper around socket().
*
* @returns IPRT status code.
* @param phSocket Where to store the handle to the socket on
* success.
* @param iDomain The protocol family (PF_XXX).
* @param iType The socket type (SOCK_XXX).
* @param iProtocol Socket parameter, usually 0.
*/
int rtSocketCreate(PRTSOCKET phSocket, int iDomain, int iType, int iProtocol)
{
/*
* Create the socket.
*/
RTSOCKETNATIVE hNative = socket(iDomain, iType, iProtocol);
if (hNative == NIL_RTSOCKETNATIVE)
return rtSocketError();
/*
* Wrap it.
*/
int rc = rtSocketCreateForNative(phSocket, hNative);
if (RT_FAILURE(rc))
{
#ifdef RT_OS_WINDOWS
closesocket(hNative);
#else
close(hNative);
#endif
}
return rc;
}
RTDECL(uint32_t) RTSocketRetain(RTSOCKET hSocket)
{
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, UINT32_MAX);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
return RTMemPoolRetain(pThis);
}
/**
* Worker for RTSocketRelease and RTSocketClose.
*
* @returns IPRT status code.
* @param pThis The socket handle instance data.
* @param fDestroy Whether we're reaching ref count zero.
*/
static int rtSocketCloseIt(RTSOCKETINT *pThis, bool fDestroy)
{
/*
* Invalidate the handle structure on destroy.
*/
if (fDestroy)
{
Assert(ASMAtomicReadU32(&pThis->u32Magic) == RTSOCKET_MAGIC);
ASMAtomicWriteU32(&pThis->u32Magic, RTSOCKET_MAGIC_DEAD);
}
int rc = VINF_SUCCESS;
if (ASMAtomicCmpXchgBool(&pThis->fClosed, true, false))
{
/*
* Close the native handle.
*/
RTSOCKETNATIVE hNative = pThis->hNative;
if (hNative != NIL_RTSOCKETNATIVE)
{
pThis->hNative = NIL_RTSOCKETNATIVE;
#ifdef RT_OS_WINDOWS
if (closesocket(hNative))
#else
if (close(hNative))
#endif
{
rc = rtSocketError();
#ifdef RT_OS_WINDOWS
AssertMsgFailed(("\"%s\": closesocket(%p) -> %Rrc\n", (uintptr_t)hNative, rc));
#else
AssertMsgFailed(("\"%s\": close(%d) -> %Rrc\n", hNative, rc));
#endif
}
}
#ifdef RT_OS_WINDOWS
/*
* Close the event.
*/
WSAEVENT hEvent = pThis->hEvent;
if (hEvent == WSA_INVALID_EVENT)
{
pThis->hEvent = WSA_INVALID_EVENT;
WSACloseEvent(hEvent);
}
#endif
}
return rc;
}
RTDECL(uint32_t) RTSocketRelease(RTSOCKET hSocket)
{
RTSOCKETINT *pThis = hSocket;
if (pThis == NIL_RTSOCKET)
return 0;
AssertPtrReturn(pThis, UINT32_MAX);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
/* get the refcount without killing it... */
uint32_t cRefs = RTMemPoolRefCount(pThis);
AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
if (cRefs == 1)
rtSocketCloseIt(pThis, true);
return RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
}
RTDECL(int) RTSocketClose(RTSOCKET hSocket)
{
RTSOCKETINT *pThis = hSocket;
if (pThis == NIL_RTSOCKET)
return VINF_SUCCESS;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
uint32_t cRefs = RTMemPoolRefCount(pThis);
AssertReturn(cRefs != UINT32_MAX, UINT32_MAX);
int rc = rtSocketCloseIt(pThis, cRefs == 1);
RTMemPoolRelease(RTMEMPOOL_DEFAULT, pThis);
return rc;
}
RTDECL(RTHCUINTPTR) RTSocketToNative(RTSOCKET hSocket)
{
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, RTHCUINTPTR_MAX);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, RTHCUINTPTR_MAX);
return (RTHCUINTPTR)pThis->hNative;
}
RTDECL(int) RTSocketSetInheritance(RTSOCKET hSocket, bool fInheritable)
{
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
int rc = VINF_SUCCESS;
#ifdef RT_OS_WINDOWS
if (!SetHandleInformation((HANDLE)pThis->hNative, HANDLE_FLAG_INHERIT, fInheritable ? HANDLE_FLAG_INHERIT : 0))
rc = RTErrConvertFromWin32(GetLastError());
#else
if (fcntl(pThis->hNative, F_SETFD, fInheritable ? 0 : FD_CLOEXEC) < 0)
rc = RTErrConvertFromErrno(errno);
#endif
return rc;
}
RTDECL(int) RTSocketRead(RTSOCKET hSocket, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
{
/*
* Validate input.
*/
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
AssertReturn(cbBuffer > 0, VERR_INVALID_PARAMETER);
AssertPtr(pvBuffer);
AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
/*
* Read loop.
* If pcbRead is NULL we have to fill the entire buffer!
*/
int rc = VINF_SUCCESS;
size_t cbRead = 0;
size_t cbToRead = cbBuffer;
for (;;)
{
rtSocketErrorReset();
#ifdef RT_OS_WINDOWS
int cbNow = cbToRead >= INT_MAX/2 ? INT_MAX/2 : (int)cbToRead;
#else
size_t cbNow = cbToRead;
#endif
ssize_t cbBytesRead = recv(pThis->hNative, (char *)pvBuffer + cbRead, cbNow, MSG_NOSIGNAL);
if (cbBytesRead <= 0)
{
rc = rtSocketError();
Assert(RT_FAILURE_NP(rc) || cbBytesRead == 0);
if (RT_SUCCESS_NP(rc))
{
if (!pcbRead)
rc = VERR_NET_SHUTDOWN;
else
{
*pcbRead = 0;
rc = VINF_SUCCESS;
}
}
break;
}
if (pcbRead)
{
/* return partial data */
*pcbRead = cbBytesRead;
break;
}
/* read more? */
cbRead += cbBytesRead;
if (cbRead == cbBuffer)
break;
/* next */
cbToRead = cbBuffer - cbRead;
}
rtSocketUnlock(pThis);
return rc;
}
RTDECL(int) RTSocketWrite(RTSOCKET hSocket, const void *pvBuffer, size_t cbBuffer)
{
/*
* Validate input.
*/
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
/*
* Try write all at once.
*/
int rc = VINF_SUCCESS;
#ifdef RT_OS_WINDOWS
int cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
#else
size_t cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
#endif
ssize_t cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
if (RT_LIKELY((size_t)cbWritten == cbBuffer && cbWritten >= 0))
rc = VINF_SUCCESS;
else if (cbWritten < 0)
rc = rtSocketError();
else
{
/*
* Unfinished business, write the remainder of the request. Must ignore
* VERR_INTERRUPTED here if we've managed to send something.
*/
size_t cbSentSoFar = 0;
for (;;)
{
/* advance */
cbBuffer -= (size_t)cbWritten;
if (!cbBuffer)
break;
cbSentSoFar += (size_t)cbWritten;
pvBuffer = (char const *)pvBuffer + cbWritten;
/* send */
#ifdef RT_OS_WINDOWS
cbNow = cbBuffer >= INT_MAX / 2 ? INT_MAX / 2 : (int)cbBuffer;
#else
cbNow = cbBuffer >= SSIZE_MAX ? SSIZE_MAX : cbBuffer;
#endif
cbWritten = send(pThis->hNative, (const char *)pvBuffer, cbNow, MSG_NOSIGNAL);
if (cbWritten >= 0)
AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%zu cbBuffer=%zu rtSocketError()=%d\n",
cbWritten, cbBuffer, rtSocketError()));
else
{
rc = rtSocketError();
if (rc != VERR_INTERNAL_ERROR || cbSentSoFar == 0)
break;
cbWritten = 0;
rc = VINF_SUCCESS;
}
}
}
rtSocketUnlock(pThis);
return rc;
}
RTDECL(int) RTSocketSgWrite(RTSOCKET hSocket, PCRTSGBUF pSgBuf)
{
/*
* Validate input.
*/
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
AssertPtrReturn(pSgBuf, VERR_INVALID_PARAMETER);
AssertReturn(pSgBuf->cSeg > 0, VERR_INVALID_PARAMETER);
AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
/*
* Construct message descriptor (translate pSgBuf) and send it.
*/
int rc = VINF_SUCCESS;
do
{
#ifdef RT_OS_WINDOWS
AssertCompileSize(WSABUF, sizeof(RTSGSEG));
AssertCompileMemberSize(WSABUF, buf, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
LPWSABUF paMsg = (LPWSABUF)RTMemTmpAllocZ(pSgBuf->cSeg * sizeof(WSABUF));
AssertPtrBreakStmt(paMsg, rc = VERR_NO_MEMORY);
for (unsigned i = 0; i < pSgBuf->cSeg; i++)
{
paMsg[i].buf = (char *)pSgBuf->pcaSeg[i].pvSeg;
paMsg[i].len = (u_long)pSgBuf->pcaSeg[i].cbSeg;
}
DWORD dwSent;
int hrc = WSASend(pThis->hNative, paMsg, pSgBuf->cSeg, &dwSent,
MSG_NOSIGNAL, NULL, NULL);
ssize_t cbWritten;
if (!hrc)
{
/* avoid overflowing ssize_t, the exact value isn't important */
cbWritten = RT_MIN(dwSent, INT_MAX);
}
else
cbWritten = -1;
#else
AssertCompileSize(struct iovec, sizeof(RTSGSEG));
AssertCompileMemberSize(struct iovec, iov_base, RT_SIZEOFMEMB(RTSGSEG, pvSeg));
AssertCompileMemberSize(struct iovec, iov_len, RT_SIZEOFMEMB(RTSGSEG, cbSeg));
struct iovec *paMsg = (struct iovec *)RTMemTmpAllocZ(pSgBuf->cSeg * sizeof(struct iovec));
AssertPtrBreakStmt(paMsg, rc = VERR_NO_MEMORY);
for (unsigned i = 0; i < pSgBuf->cSeg; i++)
{
paMsg[i].iov_base = pSgBuf->pcaSeg[i].pvSeg;
paMsg[i].iov_len = pSgBuf->pcaSeg[i].cbSeg;
}
struct msghdr msgHdr;
memset(&msgHdr, '\0', sizeof(msgHdr));
msgHdr.msg_iov = paMsg;
msgHdr.msg_iovlen = pSgBuf->cSeg;
ssize_t cbWritten = sendmsg(pThis->hNative, &msgHdr, MSG_NOSIGNAL);
#endif
RTMemTmpFree(paMsg);
if (RT_LIKELY(cbWritten >= 0))
rc = VINF_SUCCESS;
else
rc = rtSocketError();
} while (0);
rtSocketUnlock(pThis);
return rc;
}
RTDECL(int) RTSocketSelectOne(RTSOCKET hSocket, RTMSINTERVAL cMillies)
{
/*
* Validate input.
*/
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
/*
* Set up the file descriptor sets and do the select.
*/
fd_set fdsetR;
FD_ZERO(&fdsetR);
FD_SET(pThis->hNative, &fdsetR);
fd_set fdsetE = fdsetR;
int rc;
if (cMillies == RT_INDEFINITE_WAIT)
rc = select(pThis->hNative + 1, &fdsetR, NULL, &fdsetE, NULL);
else
{
struct timeval timeout;
timeout.tv_sec = cMillies / 1000;
timeout.tv_usec = (cMillies % 1000) * 1000;
rc = select(pThis->hNative + 1, &fdsetR, NULL, &fdsetE, &timeout);
}
if (rc > 0)
rc = VINF_SUCCESS;
else if (rc == 0)
rc = VERR_TIMEOUT;
else
rc = rtSocketError();
return rc;
}
RTDECL(int) RTSocketShutdown(RTSOCKET hSocket, bool fRead, bool fWrite)
{
/*
* Validate input, don't lock it because we might want to interrupt a call
* active on a different thread.
*/
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
AssertReturn(fRead || fWrite, VERR_INVALID_PARAMETER);
/*
* Do the job.
*/
int rc = VINF_SUCCESS;
int fHow;
if (fRead && fWrite)
fHow = SHUT_RDWR;
else if (fRead)
fHow = SHUT_RD;
else
fHow = SHUT_WR;
if (shutdown(pThis->hNative, fHow) == -1)
rc = rtSocketError();
return rc;
}
/**
* Converts from a native socket address to a generic IPRT network address.
*
* @returns IPRT status code.
* @param pSrc The source address.
* @param cbSrc The size of the source address.
* @param pAddr Where to return the generic IPRT network
* address.
*/
static int rtSocketConvertAddress(RTSOCKADDRUNION const *pSrc, size_t cbSrc, PRTNETADDR pAddr)
{
/*
* Convert the address.
*/
if ( cbSrc == sizeof(struct sockaddr_in)
&& pSrc->Addr.sa_family == AF_INET)
{
RT_ZERO(*pAddr);
pAddr->enmType = RTNETADDRTYPE_IPV4;
pAddr->uPort = RT_N2H_U16(pSrc->Ipv4.sin_port);
pAddr->uAddr.IPv4.u = pSrc->Ipv4.sin_addr.s_addr;
}
#ifdef IPRT_WITH_TCPIP_V6
else if ( cbSrc == sizeof(struct sockaddr_in6)
&& pSrc->Addr.sa_family == AF_INET6)
{
RT_ZERO(*pAddr);
pAddr->enmType = RTNETADDRTYPE_IPV6;
pAddr->uPort = RT_N2H_U16(pSrc->Ipv6.sin6_port);
pAddr->uAddr.IPv6.au32[0] = pSrc->Ipv6.sin6_addr.s6_addr32[0];
pAddr->uAddr.IPv6.au32[1] = pSrc->Ipv6.sin6_addr.s6_addr32[1];
pAddr->uAddr.IPv6.au32[2] = pSrc->Ipv6.sin6_addr.s6_addr32[2];
pAddr->uAddr.IPv6.au32[3] = pSrc->Ipv6.sin6_addr.s6_addr32[3];
}
#endif
else
return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
return VINF_SUCCESS;
}
RTDECL(int) RTSocketGetLocalAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
{
/*
* Validate input.
*/
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
/*
* Get the address and convert it.
*/
int rc;
RTSOCKADDRUNION u;
#ifdef RT_OS_WINDOWS
int cbAddr = sizeof(u);
#else
socklen_t cbAddr = sizeof(u);
#endif
RT_ZERO(u);
if (getsockname(pThis->hNative, &u.Addr, &cbAddr) == 0)
rc = rtSocketConvertAddress(&u, cbAddr, pAddr);
else
rc = rtSocketError();
return rc;
}
RTDECL(int) RTSocketGetPeerAddress(RTSOCKET hSocket, PRTNETADDR pAddr)
{
/*
* Validate input.
*/
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
AssertReturn(RTMemPoolRefCount(pThis) >= (pThis->cUsers ? 2U : 1U), VERR_CALLER_NO_REFERENCE);
/*
* Get the address and convert it.
*/
int rc;
RTSOCKADDRUNION u;
#ifdef RT_OS_WINDOWS
int cbAddr = sizeof(u);
#else
socklen_t cbAddr = sizeof(u);
#endif
RT_ZERO(u);
if (getpeername(pThis->hNative, &u.Addr, &cbAddr) == 0)
rc = rtSocketConvertAddress(&u, cbAddr, pAddr);
else
rc = rtSocketError();
return rc;
}
/**
* Wrapper around bind.
*
* @returns IPRT status code.
* @param hSocket The socket handle.
* @param pAddr The socket address to bind to.
* @param cbAddr The size of the address structure @a pAddr
* points to.
*/
int rtSocketBind(RTSOCKET hSocket, const struct sockaddr *pAddr, int cbAddr)
{
/*
* Validate input.
*/
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
int rc = VINF_SUCCESS;
if (bind(pThis->hNative, pAddr, cbAddr) != 0)
rc = rtSocketError();
rtSocketUnlock(pThis);
return rc;
}
/**
* Wrapper around listen.
*
* @returns IPRT status code.
* @param hSocket The socket handle.
* @param cMaxPending The max number of pending connections.
*/
int rtSocketListen(RTSOCKET hSocket, int cMaxPending)
{
/*
* Validate input.
*/
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
int rc = VINF_SUCCESS;
if (listen(pThis->hNative, cMaxPending) != 0)
rc = rtSocketError();
rtSocketUnlock(pThis);
return rc;
}
/**
* Wrapper around accept.
*
* @returns IPRT status code.
* @param hSocket The socket handle.
* @param phClient Where to return the client socket handle on
* success.
* @param pAddr Where to return the client address.
* @param pcbAddr On input this gives the size buffer size of what
* @a pAddr point to. On return this contains the
* size of what's stored at @a pAddr.
*/
int rtSocketAccept(RTSOCKET hSocket, PRTSOCKET phClient, struct sockaddr *pAddr, size_t *pcbAddr)
{
/*
* Validate input.
* Only lock the socket temporarily while we get the native handle, so that
* we can safely shutdown and destroy the socket from a different thread.
*/
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
/*
* Call accept().
*/
rtSocketErrorReset();
int rc = VINF_SUCCESS;
#ifdef RT_OS_WINDOWS
int cbAddr = (int)*pcbAddr;
#else
socklen_t cbAddr = *pcbAddr;
#endif
RTSOCKETNATIVE hNativeClient = accept(pThis->hNative, pAddr, &cbAddr);
if (hNativeClient != NIL_RTSOCKETNATIVE)
{
*pcbAddr = cbAddr;
/*
* Wrap the client socket.
*/
rc = rtSocketCreateForNative(phClient, hNativeClient);
if (RT_FAILURE(rc))
{
#ifdef RT_OS_WINDOWS
closesocket(hNativeClient);
#else
close(hNativeClient);
#endif
}
}
else
rc = rtSocketError();
rtSocketUnlock(pThis);
return rc;
}
/**
* Wrapper around connect.
*
* @returns IPRT status code.
* @param hSocket The socket handle.
* @param pAddr The socket address to connect to.
* @param cbAddr The size of the address structure @a pAddr
* points to.
*/
int rtSocketConnect(RTSOCKET hSocket, const struct sockaddr *pAddr, int cbAddr)
{
/*
* Validate input.
*/
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
int rc = VINF_SUCCESS;
if (connect(pThis->hNative, pAddr, cbAddr) != 0)
rc = rtSocketError();
rtSocketUnlock(pThis);
return rc;
}
/**
* Wrapper around setsockopt.
*
* @returns IPRT status code.
* @param hSocket The socket handle.
* @param iLevel The protocol level, e.g. IPPORTO_TCP.
* @param iOption The option, e.g. TCP_NODELAY.
* @param pvValue The value buffer.
* @param cbValue The size of the value pointed to by pvValue.
*/
int rtSocketSetOpt(RTSOCKET hSocket, int iLevel, int iOption, void const *pvValue, int cbValue)
{
/*
* Validate input.
*/
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
int rc = VINF_SUCCESS;
if (setsockopt(pThis->hNative, iLevel, iOption, (const char *)pvValue, cbValue) != 0)
rc = rtSocketError();
rtSocketUnlock(pThis);
return rc;
}
#ifdef RT_OS_WINDOWS
/**
* Internal RTPollSetAdd helper that returns the handle that should be added to
* the pollset.
*
* @returns Valid handle on success, INVALID_HANDLE_VALUE on failure.
* @param hSocket The socket handle.
* @param fEvents The events we're polling for.
* @param ph wher to put the primary handle.
*/
int rtSocketPollGetHandle(RTSOCKET hSocket, uint32_t fEvents, PHANDLE ph)
{
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, VERR_INVALID_HANDLE);
AssertReturn(rtSocketTryLock(pThis), VERR_CONCURRENT_ACCESS);
int rc = VINF_SUCCESS;
if (pThis->hEvent != WSA_INVALID_EVENT)
*ph = pThis->hEvent;
else
{
*ph = pThis->hEvent = WSACreateEvent();
if (pThis->hEvent == WSA_INVALID_EVENT)
rc = rtSocketError();
}
rtSocketUnlock(pThis);
return rc;
}
/**
* Undos the harm done by WSAEventSelect.
*
* @returns IPRT status code.
* @param pThis The socket handle.
*/
static int rtSocketPollClearEventAndMakeBlocking(RTSOCKETINT *pThis)
{
int rc = VINF_SUCCESS;
if (pThis->fSubscribedEvts)
{
if (WSAEventSelect(pThis->hNative, WSA_INVALID_EVENT, 0) == 0)
{
pThis->fSubscribedEvts = 0;
u_long fNonBlocking = 0;
int rc2 = ioctlsocket(pThis->hNative, FIONBIO, &fNonBlocking);
if (rc2 != 0)
{
rc = rtSocketError();
AssertMsgFailed(("%Rrc; rc2=%d\n", rc, rc2));
}
}
else
{
rc = rtSocketError();
AssertMsgFailed(("%Rrc\n", rc));
}
}
return rc;
}
/**
* Updates the mask of events we're subscribing to.
*
* @returns IPRT status code.
* @param pThis The socket handle.
* @param fEvents The events we want to subscribe to.
*/
static int rtSocketPollUpdateEvents(RTSOCKETINT *pThis, uint32_t fEvents)
{
LONG fNetworkEvents = 0;
if (fEvents & RTPOLL_EVT_READ)
fNetworkEvents |= FD_READ;
if (fEvents & RTPOLL_EVT_WRITE)
fNetworkEvents |= FD_WRITE;
if (fEvents & RTPOLL_EVT_ERROR)
fNetworkEvents |= FD_CLOSE;
if (WSAEventSelect(pThis->hNative, pThis->hEvent, fNetworkEvents) == 0)
{
pThis->fSubscribedEvts = fEvents;
return VINF_SUCCESS;
}
int rc = rtSocketError();
AssertMsgFailed(("fNetworkEvents=%#x rc=%Rrc\n", fNetworkEvents, rtSocketError()));
return rc;
}
/**
* Checks for pending events.
*
* @returns Event mask or 0.
* @param pThis The socket handle.
* @param fEvents The desired events.
*/
static uint32_t rtSocketPollCheck(RTSOCKETINT *pThis, uint32_t fEvents)
{
int rc = VINF_SUCCESS;
uint32_t fRetEvents = 0;
/* Make sure WSAEnumNetworkEvents returns what we want. */
if ((pThis->fSubscribedEvts & fEvents) != fEvents)
rc = rtSocketPollUpdateEvents(pThis, pThis->fSubscribedEvts | fEvents);
/* Get the event mask, ASSUMES that WSAEnumNetworkEvents doesn't clear stuff. */
WSANETWORKEVENTS NetEvts;
RT_ZERO(NetEvts);
if (WSAEnumNetworkEvents(pThis->hNative, pThis->hEvent, &NetEvts) == 0)
{
if ( (NetEvts.lNetworkEvents & FD_READ)
&& (fEvents & RTPOLL_EVT_READ)
&& NetEvts.iErrorCode[FD_READ_BIT] == 0)
fRetEvents |= RTPOLL_EVT_READ;
if ( (NetEvts.lNetworkEvents & FD_WRITE)
&& (fEvents & RTPOLL_EVT_WRITE)
&& NetEvts.iErrorCode[FD_WRITE_BIT] == 0)
fRetEvents |= RTPOLL_EVT_WRITE;
if (fEvents & RTPOLL_EVT_ERROR)
{
if (NetEvts.lNetworkEvents & FD_CLOSE)
fRetEvents |= RTPOLL_EVT_ERROR;
else
for (uint32_t i = 0; i < FD_MAX_EVENTS; i++)
if ( (NetEvts.lNetworkEvents & (1L << i))
&& NetEvts.iErrorCode[i] != 0)
fRetEvents |= RTPOLL_EVT_ERROR;
}
}
else
rc = rtSocketError();
/* Fall back on select if we hit an error above. */
if (RT_FAILURE(rc))
{
/** @todo */
}
return fRetEvents;
}
/**
* Internal RTPoll helper that polls the socket handle and, if @a fNoWait is
* clear, starts whatever actions we've got running during the poll call.
*
* @returns 0 if no pending events, actions initiated if @a fNoWait is clear.
* Event mask (in @a fEvents) and no actions if the handle is ready
* already.
* UINT32_MAX (asserted) if the socket handle is busy in I/O or a
* different poll set.
*
* @param hSocket The socket handle.
* @param hPollSet The poll set handle (for access checks).
* @param fEvents The events we're polling for.
* @param fFinalEntry Set if this is the final entry for this handle
* in this poll set. This can be used for dealing
* with duplicate entries.
* @param fNoWait Set if it's a zero-wait poll call. Clear if
* we'll wait for an event to occur.
*
* @remarks There is a potential race wrt duplicate handles when @a fNoWait is
* @c true, we don't currently care about that oddity...
*/
uint32_t rtSocketPollStart(RTSOCKET hSocket, RTPOLLSET hPollSet, uint32_t fEvents, bool fFinalEntry, bool fNoWait)
{
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, UINT32_MAX);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, UINT32_MAX);
if (rtSocketTryLock(pThis))
pThis->hPollSet = hPollSet;
else
{
AssertReturn(pThis->hPollSet == hPollSet, UINT32_MAX);
ASMAtomicIncU32(&pThis->cUsers);
}
/* (rtSocketPollCheck will reset the event object). */
uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
if ( !fRetEvents
&& !fNoWait)
{
pThis->fPollEvts |= fEvents;
if ( fFinalEntry
&& pThis->fSubscribedEvts != pThis->fPollEvts)
{
int rc = rtSocketPollUpdateEvents(pThis, pThis->fPollEvts);
if (RT_FAILURE(rc))
{
pThis->fPollEvts = 0;
fRetEvents = UINT32_MAX;
}
}
}
if (fRetEvents || fNoWait)
{
if (pThis->cUsers == 1)
{
rtSocketPollClearEventAndMakeBlocking(pThis);
pThis->hPollSet = NIL_RTPOLLSET;
}
ASMAtomicDecU32(&pThis->cUsers);
}
return fRetEvents;
}
/**
* Called after a WaitForMultipleObjects returned in order to check for pending
* events and stop whatever actions that rtSocketPollStart() initiated.
*
* @returns Event mask or 0.
*
* @param hSocket The socket handle.
* @param fEvents The events we're polling for.
* @param fFinalEntry Set if this is the final entry for this handle
* in this poll set. This can be used for dealing
* with duplicate entries. Only keep in mind that
* this method is called in reverse order, so the
* first call will have this set (when the entire
* set was processed).
*/
uint32_t rtSocketPollDone(RTSOCKET hSocket, uint32_t fEvents, bool fFinalEntry)
{
RTSOCKETINT *pThis = hSocket;
AssertPtrReturn(pThis, 0);
AssertReturn(pThis->u32Magic == RTSOCKET_MAGIC, 0);
Assert(pThis->cUsers > 0);
Assert(pThis->hPollSet != NIL_RTPOLLSET);
/* Harvest events and clear the event mask for the next round of polling. */
uint32_t fRetEvents = rtSocketPollCheck(pThis, fEvents);
pThis->fPollEvts = 0;
/* Make the socket blocking again and unlock the handle. */
if (pThis->cUsers == 1)
{
rtSocketPollClearEventAndMakeBlocking(pThis);
pThis->hPollSet = NIL_RTPOLLSET;
}
ASMAtomicDecU32(&pThis->cUsers);
return fRetEvents;
}
#endif /* RT_OS_WINDOWS */
|