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
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
|
/* $Id$ */
/** @file
* IPRT - Local IPC, Windows Implementation Using Named Pipes.
*/
/*
* Copyright (C) 2008-2022 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 *
*********************************************************************************************************************************/
#define LOG_GROUP RTLOGGROUP_LOCALIPC
/*
* We have to force NT 5.0 here because of
* ConvertStringSecurityDescriptorToSecurityDescriptor. Note that because of
* FILE_FLAG_FIRST_PIPE_INSTANCE this code actually requires W2K SP2+.
*/
#ifndef _WIN32_WINNT
# define _WIN32_WINNT 0x0500 /* for ConvertStringSecurityDescriptorToSecurityDescriptor */
#elif _WIN32_WINNT < 0x0500
# undef _WIN32_WINNT
# define _WIN32_WINNT 0x0500
#endif
#define UNICODE /* For the SDDL_ strings. */
#include <iprt/win/windows.h>
#include <sddl.h>
#include "internal/iprt.h"
#include <iprt/localipc.h>
#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/critsect.h>
#include <iprt/ctype.h>
#include <iprt/err.h>
#include <iprt/ldr.h>
#include <iprt/log.h>
#include <iprt/mem.h>
#include <iprt/param.h>
#include <iprt/string.h>
#include <iprt/thread.h>
#include <iprt/time.h>
#include <iprt/utf16.h>
#include "internal/magics.h"
#include "internal-r3-win.h"
/*********************************************************************************************************************************
* Defined Constants And Macros *
*********************************************************************************************************************************/
/** Pipe prefix string. */
#define RTLOCALIPC_WIN_PREFIX L"\\\\.\\pipe\\IPRT-"
/** DACL for block all network access and local users other than the creator/owner.
*
* ACE format: (ace_type;ace_flags;rights;object_guid;inherit_object_guid;account_sid)
*
* Note! FILE_GENERIC_WRITE (SDDL_FILE_WRITE) is evil here because it includes
* the FILE_CREATE_PIPE_INSTANCE(=FILE_APPEND_DATA) flag. Thus the hardcoded
* value 0x0012019b in the client ACE. The server-side still needs
* setting FILE_CREATE_PIPE_INSTANCE although.
* It expands to:
* 0x00000001 - FILE_READ_DATA
* 0x00000008 - FILE_READ_EA
* 0x00000080 - FILE_READ_ATTRIBUTES
* 0x00020000 - READ_CONTROL
* 0x00100000 - SYNCHRONIZE
* 0x00000002 - FILE_WRITE_DATA
* 0x00000010 - FILE_WRITE_EA
* 0x00000100 - FILE_WRITE_ATTRIBUTES
* = 0x0012019b (client)
* + (only for server):
* 0x00000004 - FILE_CREATE_PIPE_INSTANCE
* = 0x0012019f
*
* @todo Triple check this!
* @todo EVERYONE -> AUTHENTICATED USERS or something more appropriate?
* @todo Have trouble allowing the owner FILE_CREATE_PIPE_INSTANCE access, so for now I'm hacking
* it just to get progress - the service runs as local system.
* The CREATOR OWNER and PERSONAL SELF works (the former is only involved in inheriting
* it seems, which is why it won't work. The latter I've no idea about. Perhaps the solution
* is to go the annoying route of OpenProcessToken, QueryTokenInformation,
* ConvertSidToStringSid and then use the result... Suggestions are very welcome
*/
#define RTLOCALIPC_WIN_SDDL_BASE \
SDDL_DACL SDDL_DELIMINATOR \
SDDL_ACE_BEGIN SDDL_ACCESS_DENIED L";;" SDDL_GENERIC_ALL L";;;" SDDL_NETWORK SDDL_ACE_END \
SDDL_ACE_BEGIN SDDL_ACCESS_ALLOWED L";;" SDDL_FILE_ALL L";;;" SDDL_LOCAL_SYSTEM SDDL_ACE_END
#define RTLOCALIPC_WIN_SDDL_SERVER \
RTLOCALIPC_WIN_SDDL_BASE \
SDDL_ACE_BEGIN SDDL_ACCESS_ALLOWED L";;" L"0x0012019f" L";;;" SDDL_EVERYONE SDDL_ACE_END
#define RTLOCALIPC_WIN_SDDL_CLIENT \
RTLOCALIPC_WIN_SDDL_BASE \
SDDL_ACE_BEGIN SDDL_ACCESS_ALLOWED L";;" L"0x0012019b" L";;;" SDDL_EVERYONE SDDL_ACE_END
// SDDL_ACE_BEGIN SDDL_ACCESS_ALLOWED L";;" SDDL_GENERIC_ALL L";;;" SDDL_PERSONAL_SELF SDDL_ACE_END \
// SDDL_ACE_BEGIN SDDL_ACCESS_ALLOWED L";CIOI;" SDDL_GENERIC_ALL L";;;" SDDL_CREATOR_OWNER SDDL_ACE_END
// SDDL_ACE_BEGIN SDDL_ACCESS_ALLOWED L";;" L"0x0012019b" L";;;" SDDL_EVERYONE SDDL_ACE_END
// SDDL_ACE_BEGIN SDDL_ACCESS_ALLOWED L";;" SDDL_FILE_ALL L";;;" SDDL_LOCAL_SYSTEM SDDL_ACE_END
/*********************************************************************************************************************************
* Structures and Typedefs *
*********************************************************************************************************************************/
/**
* Local IPC service instance, Windows.
*/
typedef struct RTLOCALIPCSERVERINT
{
/** The magic (RTLOCALIPCSERVER_MAGIC). */
uint32_t u32Magic;
/** The creation flags. */
uint32_t fFlags;
/** Critical section protecting the structure. */
RTCRITSECT CritSect;
/** The number of references to the instance.
* @remarks The reference counting isn't race proof. */
uint32_t volatile cRefs;
/** Indicates that there is a pending cancel request. */
bool volatile fCancelled;
/** The named pipe handle. */
HANDLE hNmPipe;
/** The handle to the event object we're using for overlapped I/O. */
HANDLE hEvent;
/** The overlapped I/O structure. */
OVERLAPPED OverlappedIO;
/** The full pipe name (variable length). */
RTUTF16 wszName[1];
} RTLOCALIPCSERVERINT;
/** Pointer to a local IPC server instance (Windows). */
typedef RTLOCALIPCSERVERINT *PRTLOCALIPCSERVERINT;
/**
* Local IPC session instance, Windows.
*
* This is a named pipe and we should probably merge the pipe code with this to
* save work and code duplication.
*/
typedef struct RTLOCALIPCSESSIONINT
{
/** The magic (RTLOCALIPCSESSION_MAGIC). */
uint32_t u32Magic;
/** Critical section protecting the structure. */
RTCRITSECT CritSect;
/** The number of references to the instance.
* @remarks The reference counting isn't race proof. */
uint32_t volatile cRefs;
/** Set if the zero byte read that the poll code using is pending. */
bool fZeroByteRead;
/** Indicates that there is a pending cancel request. */
bool volatile fCancelled;
/** Set if this is the server side, clear if the client. */
bool fServerSide;
/** The named pipe handle. */
HANDLE hNmPipe;
struct
{
RTTHREAD hActiveThread;
/** The handle to the event object we're using for overlapped I/O. */
HANDLE hEvent;
/** The overlapped I/O structure. */
OVERLAPPED OverlappedIO;
}
/** Overlapped reads. */
Read,
/** Overlapped writes. */
Write;
#if 0 /* Non-blocking writes are not yet supported. */
/** Bounce buffer for writes. */
uint8_t *pbBounceBuf;
/** Amount of used buffer space. */
size_t cbBounceBufUsed;
/** Amount of allocated buffer space. */
size_t cbBounceBufAlloc;
#endif
/** Buffer for the zero byte read.
* Used in RTLocalIpcSessionWaitForData(). */
uint8_t abBuf[8];
} RTLOCALIPCSESSIONINT;
/** Pointer to a local IPC session instance (Windows). */
typedef RTLOCALIPCSESSIONINT *PRTLOCALIPCSESSIONINT;
/*********************************************************************************************************************************
* Internal Functions *
*********************************************************************************************************************************/
static int rtLocalIpcWinCreateSession(PRTLOCALIPCSESSIONINT *ppSession, HANDLE hNmPipeSession);
/*********************************************************************************************************************************
* Global Variables *
*********************************************************************************************************************************/
static bool volatile g_fResolvedApis = false;
/** advapi32.dll API ConvertStringSecurityDescriptorToSecurityDescriptorW. */
static decltype(ConvertStringSecurityDescriptorToSecurityDescriptorW) *g_pfnSSDLToSecDescW = NULL;
/**
* Builds and allocates the security descriptor required for securing the local pipe.
*
* @return IPRT status code.
* @param ppDesc Where to store the allocated security descriptor on success.
* Must be free'd using LocalFree().
* @param fServer Whether it's for a server or client instance.
*/
static int rtLocalIpcServerWinAllocSecurityDescriptior(PSECURITY_DESCRIPTOR *ppDesc, bool fServer)
{
/*
* Resolve the API the first time around.
*/
if (!g_fResolvedApis)
{
g_pfnSSDLToSecDescW = (decltype(g_pfnSSDLToSecDescW))RTLdrGetSystemSymbol("advapi32.dll", "ConvertStringSecurityDescriptorToSecurityDescriptorW");
ASMCompilerBarrier();
g_fResolvedApis = true;
}
int rc;
PSECURITY_DESCRIPTOR pSecDesc = NULL;
if (g_pfnSSDLToSecDescW)
{
/*
* We'll create a security descriptor from a SDDL that denies
* access to network clients (this is local IPC after all), it
* makes some further restrictions to prevent non-authenticated
* users from screwing around.
*/
PCRTUTF16 pwszSDDL = fServer ? RTLOCALIPC_WIN_SDDL_SERVER : RTLOCALIPC_WIN_SDDL_CLIENT;
if (g_pfnSSDLToSecDescW(pwszSDDL, SDDL_REVISION_1, &pSecDesc, NULL))
{
AssertPtr(pSecDesc);
*ppDesc = pSecDesc;
return VINF_SUCCESS;
}
rc = RTErrConvertFromWin32(GetLastError());
}
else
{
/* Windows OSes < W2K SP2 not supported for now, bail out. */
/** @todo Implement me! */
rc = VERR_NOT_SUPPORTED;
}
return rc;
}
/**
* Creates a named pipe instance.
*
* This is used by both RTLocalIpcServerCreate and RTLocalIpcServerListen.
*
* @return IPRT status code.
* @param phNmPipe Where to store the named pipe handle on success.
* This will be set to INVALID_HANDLE_VALUE on failure.
* @param pwszPipeName The named pipe name, full, UTF-16 encoded.
* @param fFirst Set on the first call (from RTLocalIpcServerCreate),
* otherwise clear. Governs the
* FILE_FLAG_FIRST_PIPE_INSTANCE flag.
*/
static int rtLocalIpcServerWinCreatePipeInstance(PHANDLE phNmPipe, PCRTUTF16 pwszPipeName, bool fFirst)
{
*phNmPipe = INVALID_HANDLE_VALUE;
PSECURITY_DESCRIPTOR pSecDesc;
int rc = rtLocalIpcServerWinAllocSecurityDescriptior(&pSecDesc, fFirst /* Server? */);
if (RT_SUCCESS(rc))
{
SECURITY_ATTRIBUTES SecAttrs;
SecAttrs.nLength = sizeof(SECURITY_ATTRIBUTES);
SecAttrs.lpSecurityDescriptor = pSecDesc;
SecAttrs.bInheritHandle = FALSE;
DWORD fOpenMode = PIPE_ACCESS_DUPLEX
| PIPE_WAIT
| FILE_FLAG_OVERLAPPED;
if ( fFirst
&& ( g_enmWinVer >= kRTWinOSType_XP
|| ( g_enmWinVer == kRTWinOSType_2K
&& g_WinOsInfoEx.wServicePackMajor >= 2) ) )
fOpenMode |= FILE_FLAG_FIRST_PIPE_INSTANCE; /* Introduced with W2K SP2 */
HANDLE hNmPipe = CreateNamedPipeW(pwszPipeName, /* lpName */
fOpenMode, /* dwOpenMode */
PIPE_TYPE_BYTE, /* dwPipeMode */
PIPE_UNLIMITED_INSTANCES, /* nMaxInstances */
PAGE_SIZE, /* nOutBufferSize (advisory) */
PAGE_SIZE, /* nInBufferSize (ditto) */
30*1000, /* nDefaultTimeOut = 30 sec */
&SecAttrs); /* lpSecurityAttributes */
LocalFree(pSecDesc);
if (hNmPipe != INVALID_HANDLE_VALUE)
*phNmPipe = hNmPipe;
else
rc = RTErrConvertFromWin32(GetLastError());
}
return rc;
}
/**
* Validates the user specified name.
*
* @returns IPRT status code.
* @param pszName The name to validate.
* @param pcwcFullName Where to return the UTF-16 length of the full name.
* @param fNative Whether it's a native name or a portable name.
*/
static int rtLocalIpcWinValidateName(const char *pszName, size_t *pcwcFullName, bool fNative)
{
AssertPtrReturn(pszName, VERR_INVALID_POINTER);
AssertReturn(*pszName, VERR_INVALID_NAME);
if (!fNative)
{
size_t cwcName = RT_ELEMENTS(RTLOCALIPC_WIN_PREFIX) - 1;
for (;;)
{
char ch = *pszName++;
if (!ch)
break;
AssertReturn(!RT_C_IS_CNTRL(ch), VERR_INVALID_NAME);
AssertReturn((unsigned)ch < 0x80, VERR_INVALID_NAME);
AssertReturn(ch != '\\', VERR_INVALID_NAME);
AssertReturn(ch != '/', VERR_INVALID_NAME);
cwcName++;
}
*pcwcFullName = cwcName;
}
else
{
int rc = RTStrCalcUtf16LenEx(pszName, RTSTR_MAX, pcwcFullName);
AssertRCReturn(rc, rc);
}
return VINF_SUCCESS;
}
/**
* Constructs the full pipe name as UTF-16.
*
* @returns IPRT status code.
* @param pszName The user supplied name. ASSUMES reasonable length
* for now, so no long path prefixing needed.
* @param pwszFullName The output buffer.
* @param cwcFullName The output buffer size excluding the terminator.
* @param fNative Whether the user supplied name is a native or
* portable one.
*/
static int rtLocalIpcWinConstructName(const char *pszName, PRTUTF16 pwszFullName, size_t cwcFullName, bool fNative)
{
if (!fNative)
{
static RTUTF16 const s_wszPrefix[] = RTLOCALIPC_WIN_PREFIX;
Assert(cwcFullName * sizeof(RTUTF16) > sizeof(s_wszPrefix));
memcpy(pwszFullName, s_wszPrefix, sizeof(s_wszPrefix));
cwcFullName -= RT_ELEMENTS(s_wszPrefix) - 1;
pwszFullName += RT_ELEMENTS(s_wszPrefix) - 1;
}
return RTStrToUtf16Ex(pszName, RTSTR_MAX, &pwszFullName, cwcFullName + 1, NULL);
}
RTDECL(int) RTLocalIpcServerCreate(PRTLOCALIPCSERVER phServer, const char *pszName, uint32_t fFlags)
{
/*
* Validate parameters.
*/
AssertPtrReturn(phServer, VERR_INVALID_POINTER);
*phServer = NIL_RTLOCALIPCSERVER;
AssertReturn(!(fFlags & ~RTLOCALIPC_FLAGS_VALID_MASK), VERR_INVALID_FLAGS);
size_t cwcFullName;
int rc = rtLocalIpcWinValidateName(pszName, &cwcFullName, RT_BOOL(fFlags & RTLOCALIPC_FLAGS_NATIVE_NAME));
if (RT_SUCCESS(rc))
{
/*
* Allocate and initialize the instance data.
*/
size_t cbThis = RT_UOFFSETOF_DYN(RTLOCALIPCSERVERINT, wszName[cwcFullName + 1]);
PRTLOCALIPCSERVERINT pThis = (PRTLOCALIPCSERVERINT)RTMemAllocVar(cbThis);
AssertReturn(pThis, VERR_NO_MEMORY);
pThis->u32Magic = RTLOCALIPCSERVER_MAGIC;
pThis->cRefs = 1; /* the one we return */
pThis->fCancelled = false;
rc = rtLocalIpcWinConstructName(pszName, pThis->wszName, cwcFullName, RT_BOOL(fFlags & RTLOCALIPC_FLAGS_NATIVE_NAME));
if (RT_SUCCESS(rc))
{
rc = RTCritSectInit(&pThis->CritSect);
if (RT_SUCCESS(rc))
{
pThis->hEvent = CreateEvent(NULL /*lpEventAttributes*/, TRUE /*bManualReset*/,
FALSE /*bInitialState*/, NULL /*lpName*/);
if (pThis->hEvent != NULL)
{
RT_ZERO(pThis->OverlappedIO);
pThis->OverlappedIO.Internal = STATUS_PENDING;
pThis->OverlappedIO.hEvent = pThis->hEvent;
rc = rtLocalIpcServerWinCreatePipeInstance(&pThis->hNmPipe, pThis->wszName, true /* fFirst */);
if (RT_SUCCESS(rc))
{
*phServer = pThis;
return VINF_SUCCESS;
}
BOOL fRc = CloseHandle(pThis->hEvent);
AssertMsg(fRc, ("%d\n", GetLastError())); NOREF(fRc);
}
else
rc = RTErrConvertFromWin32(GetLastError());
int rc2 = RTCritSectDelete(&pThis->CritSect);
AssertRC(rc2);
}
}
RTMemFree(pThis);
}
return rc;
}
/**
* Retains a reference to the server instance.
*
* @returns
* @param pThis The server instance.
*/
DECLINLINE(void) rtLocalIpcServerRetain(PRTLOCALIPCSERVERINT pThis)
{
uint32_t cRefs = ASMAtomicIncU32(&pThis->cRefs);
Assert(cRefs < UINT32_MAX / 2 && cRefs); NOREF(cRefs);
}
/**
* Call when the reference count reaches 0.
*
* Caller owns the critsect.
*
* @returns VINF_OBJECT_DESTROYED
* @param pThis The instance to destroy.
*/
DECL_NO_INLINE(static, int) rtLocalIpcServerWinDestroy(PRTLOCALIPCSERVERINT pThis)
{
Assert(pThis->u32Magic == ~RTLOCALIPCSERVER_MAGIC);
pThis->u32Magic = ~RTLOCALIPCSERVER_MAGIC;
BOOL fRc = CloseHandle(pThis->hNmPipe);
AssertMsg(fRc, ("%d\n", GetLastError())); NOREF(fRc);
pThis->hNmPipe = INVALID_HANDLE_VALUE;
fRc = CloseHandle(pThis->hEvent);
AssertMsg(fRc, ("%d\n", GetLastError())); NOREF(fRc);
pThis->hEvent = NULL;
RTCritSectLeave(&pThis->CritSect);
RTCritSectDelete(&pThis->CritSect);
RTMemFree(pThis);
return VINF_OBJECT_DESTROYED;
}
/**
* Server instance destructor.
*
* @returns VINF_OBJECT_DESTROYED
* @param pThis The server instance.
*/
DECL_NO_INLINE(static, int) rtLocalIpcServerDtor(PRTLOCALIPCSERVERINT pThis)
{
RTCritSectEnter(&pThis->CritSect);
return rtLocalIpcServerWinDestroy(pThis);
}
/**
* Releases a reference to the server instance.
*
* @returns VINF_SUCCESS if only release, VINF_OBJECT_DESTROYED if destroyed.
* @param pThis The server instance.
*/
DECLINLINE(int) rtLocalIpcServerRelease(PRTLOCALIPCSERVERINT pThis)
{
uint32_t cRefs = ASMAtomicDecU32(&pThis->cRefs);
Assert(cRefs < UINT32_MAX / 2);
if (!cRefs)
return rtLocalIpcServerDtor(pThis);
return VINF_SUCCESS;
}
/**
* Releases a reference to the server instance and leaves the critsect.
*
* @returns VINF_SUCCESS if only release, VINF_OBJECT_DESTROYED if destroyed.
* @param pThis The server instance.
*/
DECLINLINE(int) rtLocalIpcServerReleaseAndUnlock(PRTLOCALIPCSERVERINT pThis)
{
uint32_t cRefs = ASMAtomicDecU32(&pThis->cRefs);
Assert(cRefs < UINT32_MAX / 2);
if (!cRefs)
return rtLocalIpcServerWinDestroy(pThis);
return RTCritSectLeave(&pThis->CritSect);
}
RTDECL(int) RTLocalIpcServerDestroy(RTLOCALIPCSERVER hServer)
{
/*
* Validate input.
*/
if (hServer == NIL_RTLOCALIPCSERVER)
return VINF_SUCCESS;
PRTLOCALIPCSERVERINT pThis = (PRTLOCALIPCSERVERINT)hServer;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTLOCALIPCSERVER_MAGIC, VERR_INVALID_HANDLE);
/*
* Cancel any thread currently busy using the server,
* leaving the cleanup to it.
*/
AssertReturn(ASMAtomicCmpXchgU32(&pThis->u32Magic, ~RTLOCALIPCSERVER_MAGIC, RTLOCALIPCSERVER_MAGIC), VERR_WRONG_ORDER);
RTCritSectEnter(&pThis->CritSect);
/* Cancel everything. */
ASMAtomicUoWriteBool(&pThis->fCancelled, true);
if (pThis->cRefs > 1)
{
BOOL fRc = SetEvent(pThis->hEvent);
AssertMsg(fRc, ("%d\n", GetLastError())); NOREF(fRc);
}
return rtLocalIpcServerReleaseAndUnlock(pThis);
}
RTDECL(int) RTLocalIpcServerGrantGroupAccess(RTLOCALIPCSERVER hServer, RTGID gid)
{
RT_NOREF_PV(hServer); RT_NOREF(gid);
return VERR_NOT_SUPPORTED;
}
RTDECL(int) RTLocalIpcServerListen(RTLOCALIPCSERVER hServer, PRTLOCALIPCSESSION phClientSession)
{
/*
* Validate input.
*/
PRTLOCALIPCSERVERINT pThis = (PRTLOCALIPCSERVERINT)hServer;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTLOCALIPCSERVER_MAGIC, VERR_INVALID_HANDLE);
AssertPtrReturn(phClientSession, VERR_INVALID_POINTER);
/*
* Enter the critsect before inspecting the object further.
*/
int rc = RTCritSectEnter(&pThis->CritSect);
AssertRCReturn(rc, rc);
rtLocalIpcServerRetain(pThis);
if (!pThis->fCancelled)
{
ResetEvent(pThis->hEvent);
RTCritSectLeave(&pThis->CritSect);
/*
* Try connect a client. We need to use overlapped I/O here because
* of the cancellation done by RTLocalIpcServerCancel and RTLocalIpcServerDestroy.
*/
SetLastError(NO_ERROR);
BOOL fRc = ConnectNamedPipe(pThis->hNmPipe, &pThis->OverlappedIO);
DWORD dwErr = fRc ? NO_ERROR : GetLastError();
if ( !fRc
&& dwErr == ERROR_IO_PENDING)
{
WaitForSingleObject(pThis->hEvent, INFINITE);
DWORD dwIgnored;
fRc = GetOverlappedResult(pThis->hNmPipe, &pThis->OverlappedIO, &dwIgnored, FALSE /* bWait*/);
dwErr = fRc ? NO_ERROR : GetLastError();
}
RTCritSectEnter(&pThis->CritSect);
if ( !pThis->fCancelled /* Event signalled but not cancelled? */
&& pThis->u32Magic == RTLOCALIPCSERVER_MAGIC)
{
/*
* Still alive, some error or an actual client.
*
* If it's the latter we'll have to create a new pipe instance that
* replaces the current one for the server. The current pipe instance
* will be assigned to the client session.
*/
if ( fRc
|| dwErr == ERROR_PIPE_CONNECTED)
{
HANDLE hNmPipe;
rc = rtLocalIpcServerWinCreatePipeInstance(&hNmPipe, pThis->wszName, false /* fFirst */);
if (RT_SUCCESS(rc))
{
HANDLE hNmPipeSession = pThis->hNmPipe; /* consumed */
pThis->hNmPipe = hNmPipe;
rc = rtLocalIpcWinCreateSession(phClientSession, hNmPipeSession);
}
else
{
/*
* We failed to create a new instance for the server, disconnect
* the client and fail. Don't try service the client here.
*/
fRc = DisconnectNamedPipe(pThis->hNmPipe);
AssertMsg(fRc, ("%d\n", GetLastError()));
}
}
else
rc = RTErrConvertFromWin32(dwErr);
}
else
{
/*
* Cancelled.
*
* Cancel the overlapped io if it didn't complete (must be done
* in the this thread) or disconnect the client.
*/
Assert(pThis->fCancelled);
if ( fRc
|| dwErr == ERROR_PIPE_CONNECTED)
fRc = DisconnectNamedPipe(pThis->hNmPipe);
else if (dwErr == ERROR_IO_PENDING)
fRc = CancelIo(pThis->hNmPipe);
else
fRc = TRUE;
AssertMsg(fRc, ("%d\n", GetLastError()));
rc = VERR_CANCELLED;
}
}
else
{
/*pThis->fCancelled = false; - Terrible interface idea. Add API to clear fCancelled if ever required. */
rc = VERR_CANCELLED;
}
rtLocalIpcServerReleaseAndUnlock(pThis);
return rc;
}
RTDECL(int) RTLocalIpcServerCancel(RTLOCALIPCSERVER hServer)
{
/*
* Validate input.
*/
PRTLOCALIPCSERVERINT pThis = (PRTLOCALIPCSERVERINT)hServer;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTLOCALIPCSERVER_MAGIC, VERR_INVALID_HANDLE);
/*
* Enter the critical section, then set the cancellation flag
* and signal the event (to wake up anyone in/at WaitForSingleObject).
*/
rtLocalIpcServerRetain(pThis);
int rc = RTCritSectEnter(&pThis->CritSect);
if (RT_SUCCESS(rc))
{
ASMAtomicUoWriteBool(&pThis->fCancelled, true);
BOOL fRc = SetEvent(pThis->hEvent);
if (fRc)
rc = VINF_SUCCESS;
else
{
DWORD dwErr = GetLastError();
AssertMsgFailed(("dwErr=%u\n", dwErr));
rc = RTErrConvertFromWin32(dwErr);
}
rtLocalIpcServerReleaseAndUnlock(pThis);
}
else
rtLocalIpcServerRelease(pThis);
return rc;
}
/**
* Create a session instance for a new server client or a client connect.
*
* @returns IPRT status code.
*
* @param ppSession Where to store the session handle on success.
* @param hNmPipeSession The named pipe handle if server calling,
* INVALID_HANDLE_VALUE if client connect. This will
* be consumed by this session, meaning on failure to
* create the session it will be closed.
*/
static int rtLocalIpcWinCreateSession(PRTLOCALIPCSESSIONINT *ppSession, HANDLE hNmPipeSession)
{
AssertPtr(ppSession);
/*
* Allocate and initialize the session instance data.
*/
int rc;
PRTLOCALIPCSESSIONINT pThis = (PRTLOCALIPCSESSIONINT)RTMemAllocZ(sizeof(*pThis));
if (pThis)
{
pThis->u32Magic = RTLOCALIPCSESSION_MAGIC;
pThis->cRefs = 1; /* our ref */
pThis->fCancelled = false;
pThis->fZeroByteRead = false;
pThis->fServerSide = hNmPipeSession != INVALID_HANDLE_VALUE;
pThis->hNmPipe = hNmPipeSession;
#if 0 /* Non-blocking writes are not yet supported. */
pThis->pbBounceBuf = NULL;
pThis->cbBounceBufAlloc = 0;
pThis->cbBounceBufUsed = 0;
#endif
rc = RTCritSectInit(&pThis->CritSect);
if (RT_SUCCESS(rc))
{
pThis->Read.hEvent = CreateEvent(NULL /*lpEventAttributes*/, TRUE /*bManualReset*/,
FALSE /*bInitialState*/, NULL /*lpName*/);
if (pThis->Read.hEvent != NULL)
{
pThis->Read.OverlappedIO.Internal = STATUS_PENDING;
pThis->Read.OverlappedIO.hEvent = pThis->Read.hEvent;
pThis->Read.hActiveThread = NIL_RTTHREAD;
pThis->Write.hEvent = CreateEvent(NULL /*lpEventAttributes*/, TRUE /*bManualReset*/,
FALSE /*bInitialState*/, NULL /*lpName*/);
if (pThis->Write.hEvent != NULL)
{
pThis->Write.OverlappedIO.Internal = STATUS_PENDING;
pThis->Write.OverlappedIO.hEvent = pThis->Write.hEvent;
pThis->Write.hActiveThread = NIL_RTTHREAD;
*ppSession = pThis;
return VINF_SUCCESS;
}
CloseHandle(pThis->Read.hEvent);
}
/* bail out */
rc = RTErrConvertFromWin32(GetLastError());
RTCritSectDelete(&pThis->CritSect);
}
RTMemFree(pThis);
}
else
rc = VERR_NO_MEMORY;
if (hNmPipeSession != INVALID_HANDLE_VALUE)
{
BOOL fRc = CloseHandle(hNmPipeSession);
AssertMsg(fRc, ("%d\n", GetLastError())); NOREF(fRc);
}
return rc;
}
RTDECL(int) RTLocalIpcSessionConnect(PRTLOCALIPCSESSION phSession, const char *pszName, uint32_t fFlags)
{
/*
* Validate input.
*/
AssertPtrReturn(phSession, VERR_INVALID_POINTER);
AssertReturn(!(fFlags & ~RTLOCALIPC_C_FLAGS_VALID_MASK), VERR_INVALID_FLAGS);
size_t cwcFullName;
int rc = rtLocalIpcWinValidateName(pszName, &cwcFullName, RT_BOOL(fFlags & RTLOCALIPC_C_FLAGS_NATIVE_NAME));
if (RT_SUCCESS(rc))
{
/*
* Create a session (shared with server client session creation).
*/
PRTLOCALIPCSESSIONINT pThis;
rc = rtLocalIpcWinCreateSession(&pThis, INVALID_HANDLE_VALUE);
if (RT_SUCCESS(rc))
{
/*
* Try open the pipe.
*/
PSECURITY_DESCRIPTOR pSecDesc;
rc = rtLocalIpcServerWinAllocSecurityDescriptior(&pSecDesc, false /*fServer*/);
if (RT_SUCCESS(rc))
{
PRTUTF16 pwszFullName = RTUtf16Alloc((cwcFullName + 1) * sizeof(RTUTF16));
if (pwszFullName)
rc = rtLocalIpcWinConstructName(pszName, pwszFullName, cwcFullName,
RT_BOOL(fFlags & RTLOCALIPC_C_FLAGS_NATIVE_NAME));
else
rc = VERR_NO_UTF16_MEMORY;
if (RT_SUCCESS(rc))
{
SECURITY_ATTRIBUTES SecAttrs;
SecAttrs.nLength = sizeof(SECURITY_ATTRIBUTES);
SecAttrs.lpSecurityDescriptor = pSecDesc;
SecAttrs.bInheritHandle = FALSE;
/* The SECURITY_XXX flags are needed in order to prevent the server from impersonating with
this thread's security context (supported at least back to NT 3.51). See @bugref{9773}. */
HANDLE hPipe = CreateFileW(pwszFullName,
GENERIC_READ | GENERIC_WRITE,
0 /*no sharing*/,
&SecAttrs,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS,
NULL /*no template handle*/);
if (hPipe != INVALID_HANDLE_VALUE)
{
pThis->hNmPipe = hPipe;
LocalFree(pSecDesc);
RTUtf16Free(pwszFullName);
/*
* We're done!
*/
*phSession = pThis;
return VINF_SUCCESS;
}
rc = RTErrConvertFromWin32(GetLastError());
}
RTUtf16Free(pwszFullName);
LocalFree(pSecDesc);
}
/* destroy the session handle. */
CloseHandle(pThis->Read.hEvent);
CloseHandle(pThis->Write.hEvent);
RTCritSectDelete(&pThis->CritSect);
RTMemFree(pThis);
}
}
return rc;
}
/**
* Cancells all pending I/O operations, forcing the methods to return with
* VERR_CANCELLED (unless they've got actual data to return).
*
* Used by RTLocalIpcSessionCancel and RTLocalIpcSessionClose.
*
* @returns IPRT status code.
* @param pThis The client session instance.
*/
static int rtLocalIpcWinCancel(PRTLOCALIPCSESSIONINT pThis)
{
ASMAtomicUoWriteBool(&pThis->fCancelled, true);
/*
* Call CancelIo since this call cancels both read and write oriented operations.
*/
if ( pThis->fZeroByteRead
|| pThis->Read.hActiveThread != NIL_RTTHREAD
|| pThis->Write.hActiveThread != NIL_RTTHREAD)
CancelIo(pThis->hNmPipe);
/*
* Set both event semaphores.
*/
BOOL fRc = SetEvent(pThis->Read.hEvent);
AssertMsg(fRc, ("%d\n", GetLastError())); NOREF(fRc);
fRc = SetEvent(pThis->Write.hEvent);
AssertMsg(fRc, ("%d\n", GetLastError())); NOREF(fRc);
return VINF_SUCCESS;
}
/**
* Retains a reference to the session instance.
*
* @param pThis The client session instance.
*/
DECLINLINE(void) rtLocalIpcSessionRetain(PRTLOCALIPCSESSIONINT pThis)
{
uint32_t cRefs = ASMAtomicIncU32(&pThis->cRefs);
Assert(cRefs < UINT32_MAX / 2 && cRefs); NOREF(cRefs);
}
RTDECL(uint32_t) RTLocalIpcSessionRetain(RTLOCALIPCSESSION hSession)
{
PRTLOCALIPCSESSIONINT pThis = (PRTLOCALIPCSESSIONINT)hSession;
AssertPtrReturn(pThis, UINT32_MAX);
AssertReturn(pThis->u32Magic == RTLOCALIPCSESSION_MAGIC, UINT32_MAX);
uint32_t cRefs = ASMAtomicIncU32(&pThis->cRefs);
Assert(cRefs < UINT32_MAX / 2 && cRefs);
return cRefs;
}
/**
* Call when the reference count reaches 0.
*
* Caller owns the critsect.
*
* @returns VINF_OBJECT_DESTROYED
* @param pThis The instance to destroy.
*/
DECL_NO_INLINE(static, int) rtLocalIpcSessionWinDestroy(PRTLOCALIPCSESSIONINT pThis)
{
BOOL fRc = CloseHandle(pThis->hNmPipe);
AssertMsg(fRc, ("%d\n", GetLastError())); NOREF(fRc);
pThis->hNmPipe = INVALID_HANDLE_VALUE;
fRc = CloseHandle(pThis->Write.hEvent);
AssertMsg(fRc, ("%d\n", GetLastError()));
pThis->Write.hEvent = NULL;
fRc = CloseHandle(pThis->Read.hEvent);
AssertMsg(fRc, ("%d\n", GetLastError()));
pThis->Read.hEvent = NULL;
int rc2 = RTCritSectLeave(&pThis->CritSect); AssertRC(rc2);
RTCritSectDelete(&pThis->CritSect);
RTMemFree(pThis);
return VINF_OBJECT_DESTROYED;
}
/**
* Releases a reference to the session instance and unlock it.
*
* @returns VINF_SUCCESS or VINF_OBJECT_DESTROYED as appropriate.
* @param pThis The session instance.
*/
DECLINLINE(int) rtLocalIpcSessionReleaseAndUnlock(PRTLOCALIPCSESSIONINT pThis)
{
uint32_t cRefs = ASMAtomicDecU32(&pThis->cRefs);
Assert(cRefs < UINT32_MAX / 2);
if (!cRefs)
return rtLocalIpcSessionWinDestroy(pThis);
int rc2 = RTCritSectLeave(&pThis->CritSect); AssertRC(rc2);
Log(("rtLocalIpcSessionReleaseAndUnlock: %u refs left\n", cRefs));
return VINF_SUCCESS;
}
RTDECL(uint32_t) RTLocalIpcSessionRelease(RTLOCALIPCSESSION hSession)
{
if (hSession == NIL_RTLOCALIPCSESSION)
return 0;
PRTLOCALIPCSESSIONINT pThis = (PRTLOCALIPCSESSIONINT)hSession;
AssertPtrReturn(pThis, UINT32_MAX);
AssertReturn(pThis->u32Magic == RTLOCALIPCSESSION_MAGIC, UINT32_MAX);
uint32_t cRefs = ASMAtomicDecU32(&pThis->cRefs);
Assert(cRefs < UINT32_MAX / 2);
if (cRefs)
Log(("RTLocalIpcSessionRelease: %u refs left\n", cRefs));
else
{
RTCritSectEnter(&pThis->CritSect);
rtLocalIpcSessionWinDestroy(pThis);
}
return cRefs;
}
RTDECL(int) RTLocalIpcSessionClose(RTLOCALIPCSESSION hSession)
{
/*
* Validate input.
*/
if (hSession == NIL_RTLOCALIPCSESSION)
return VINF_SUCCESS;
PRTLOCALIPCSESSIONINT pThis = (PRTLOCALIPCSESSIONINT)hSession;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTLOCALIPCSESSION_MAGIC, VERR_INVALID_HANDLE);
/*
* Invalidate the instance, cancel all outstanding I/O and drop our reference.
*/
RTCritSectEnter(&pThis->CritSect);
rtLocalIpcWinCancel(pThis);
return rtLocalIpcSessionReleaseAndUnlock(pThis);
}
/**
* Handles WaitForSingleObject return value when waiting for a zero byte read.
*
* The zero byte read is started by the RTLocalIpcSessionWaitForData method and
* left pending when the function times out. This saves us the problem of
* CancelIo messing with all active I/O operations and the trouble of restarting
* the zero byte read the next time the method is called. However should
* RTLocalIpcSessionRead be called after a failed RTLocalIpcSessionWaitForData
* call, the zero byte read will still be pending and it must wait for it to
* complete before the OVERLAPPEDIO structure can be reused.
*
* Thus, both functions will do WaitForSingleObject and share this routine to
* handle the outcome.
*
* @returns IPRT status code.
* @param pThis The session instance.
* @param rcWait The WaitForSingleObject return code.
*/
static int rtLocalIpcWinGetZeroReadResult(PRTLOCALIPCSESSIONINT pThis, DWORD rcWait)
{
int rc;
DWORD cbRead = 42;
if (rcWait == WAIT_OBJECT_0)
{
if (GetOverlappedResult(pThis->hNmPipe, &pThis->Read.OverlappedIO, &cbRead, !pThis->fCancelled /*fWait*/))
{
Assert(cbRead == 0);
rc = VINF_SUCCESS;
pThis->fZeroByteRead = false;
}
else if (pThis->fCancelled)
rc = VERR_CANCELLED;
else
rc = RTErrConvertFromWin32(GetLastError());
}
else
{
/* We try get the result here too, just in case we're lucky, but no waiting. */
DWORD dwErr = GetLastError();
if (GetOverlappedResult(pThis->hNmPipe, &pThis->Read.OverlappedIO, &cbRead, FALSE /*fWait*/))
{
Assert(cbRead == 0);
rc = VINF_SUCCESS;
pThis->fZeroByteRead = false;
}
else if (rcWait == WAIT_TIMEOUT)
rc = VERR_TIMEOUT;
else if (rcWait == WAIT_ABANDONED)
rc = VERR_INVALID_HANDLE;
else
rc = RTErrConvertFromWin32(dwErr);
}
return rc;
}
RTDECL(int) RTLocalIpcSessionRead(RTLOCALIPCSESSION hSession, void *pvBuf, size_t cbToRead, size_t *pcbRead)
{
PRTLOCALIPCSESSIONINT pThis = (PRTLOCALIPCSESSIONINT)hSession;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTLOCALIPCSESSION_MAGIC, VERR_INVALID_HANDLE);
AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
/* pcbRead is optional. */
int rc = RTCritSectEnter(&pThis->CritSect);
if (RT_SUCCESS(rc))
{
rtLocalIpcSessionRetain(pThis);
if (pThis->Read.hActiveThread == NIL_RTTHREAD)
{
pThis->Read.hActiveThread = RTThreadSelf();
size_t cbTotalRead = 0;
while (cbToRead > 0)
{
DWORD cbRead = 0;
if (!pThis->fCancelled)
{
/*
* Wait for pending zero byte read, if necessary.
* Note! It cannot easily be cancelled due to concurrent current writes.
*/
if (!pThis->fZeroByteRead)
{ /* likely */ }
else
{
RTCritSectLeave(&pThis->CritSect);
DWORD rcWait = WaitForSingleObject(pThis->Read.OverlappedIO.hEvent, RT_MS_1MIN);
RTCritSectEnter(&pThis->CritSect);
rc = rtLocalIpcWinGetZeroReadResult(pThis, rcWait);
if (RT_SUCCESS(rc) || rc == VERR_TIMEOUT)
continue;
break;
}
/*
* Kick of a an overlapped read. It should return immediately if
* there is bytes in the buffer. If not, we'll cancel it and see
* what we get back.
*/
rc = ResetEvent(pThis->Read.OverlappedIO.hEvent); Assert(rc == TRUE);
RTCritSectLeave(&pThis->CritSect);
if (ReadFile(pThis->hNmPipe, pvBuf,
cbToRead <= ~(DWORD)0 ? (DWORD)cbToRead : ~(DWORD)0,
&cbRead, &pThis->Read.OverlappedIO))
{
RTCritSectEnter(&pThis->CritSect);
rc = VINF_SUCCESS;
}
else if (GetLastError() == ERROR_IO_PENDING)
{
WaitForSingleObject(pThis->Read.OverlappedIO.hEvent, INFINITE);
RTCritSectEnter(&pThis->CritSect);
if (GetOverlappedResult(pThis->hNmPipe, &pThis->Read.OverlappedIO, &cbRead, TRUE /*fWait*/))
rc = VINF_SUCCESS;
else
{
if (pThis->fCancelled)
rc = VERR_CANCELLED;
else
rc = RTErrConvertFromWin32(GetLastError());
break;
}
}
else
{
rc = RTErrConvertFromWin32(GetLastError());
AssertMsgFailedBreak(("%Rrc\n", rc));
}
}
else
{
rc = VERR_CANCELLED;
break;
}
/* Advance. */
cbToRead -= cbRead;
cbTotalRead += cbRead;
pvBuf = (uint8_t *)pvBuf + cbRead;
}
if (pcbRead)
{
*pcbRead = cbTotalRead;
if ( RT_FAILURE(rc)
&& cbTotalRead
&& rc != VERR_INVALID_POINTER)
rc = VINF_SUCCESS;
}
pThis->Read.hActiveThread = NIL_RTTHREAD;
}
else
rc = VERR_WRONG_ORDER;
rtLocalIpcSessionReleaseAndUnlock(pThis);
}
return rc;
}
RTDECL(int) RTLocalIpcSessionReadNB(RTLOCALIPCSESSION hSession, void *pvBuf, size_t cbToRead, size_t *pcbRead)
{
PRTLOCALIPCSESSIONINT pThis = (PRTLOCALIPCSESSIONINT)hSession;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTLOCALIPCSESSION_MAGIC, VERR_INVALID_HANDLE);
AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
AssertPtrReturn(pcbRead, VERR_INVALID_POINTER);
*pcbRead = 0;
int rc = RTCritSectEnter(&pThis->CritSect);
if (RT_SUCCESS(rc))
{
rtLocalIpcSessionRetain(pThis);
if (pThis->Read.hActiveThread == NIL_RTTHREAD)
{
pThis->Read.hActiveThread = RTThreadSelf();
for (;;)
{
DWORD cbRead = 0;
if (!pThis->fCancelled)
{
/*
* Wait for pending zero byte read, if necessary.
* Note! It cannot easily be cancelled due to concurrent current writes.
*/
if (!pThis->fZeroByteRead)
{ /* likely */ }
else
{
RTCritSectLeave(&pThis->CritSect);
DWORD rcWait = WaitForSingleObject(pThis->Read.OverlappedIO.hEvent, 0);
RTCritSectEnter(&pThis->CritSect);
rc = rtLocalIpcWinGetZeroReadResult(pThis, rcWait);
if (RT_SUCCESS(rc))
continue;
if (rc == VERR_TIMEOUT)
rc = VINF_TRY_AGAIN;
break;
}
/*
* Figure out how much we can read (cannot try and cancel here
* like in the anonymous pipe code).
*/
DWORD cbAvailable;
if (PeekNamedPipe(pThis->hNmPipe, NULL, 0, NULL, &cbAvailable, NULL))
{
if (cbAvailable == 0 || cbToRead == 0)
{
*pcbRead = 0;
rc = VINF_TRY_AGAIN;
break;
}
}
else
{
rc = RTErrConvertFromWin32(GetLastError());
break;
}
if (cbAvailable > cbToRead)
cbAvailable = (DWORD)cbToRead;
/*
* Kick of a an overlapped read. It should return immediately, so we
* don't really need to leave the critsect here.
*/
rc = ResetEvent(pThis->Read.OverlappedIO.hEvent); Assert(rc == TRUE);
if (ReadFile(pThis->hNmPipe, pvBuf, cbAvailable, &cbRead, &pThis->Read.OverlappedIO))
{
*pcbRead = cbRead;
rc = VINF_SUCCESS;
}
else if (GetLastError() == ERROR_IO_PENDING)
{
DWORD rcWait = WaitForSingleObject(pThis->Read.OverlappedIO.hEvent, 0);
if (rcWait == WAIT_TIMEOUT)
{
RTCritSectLeave(&pThis->CritSect);
rcWait = WaitForSingleObject(pThis->Read.OverlappedIO.hEvent, INFINITE);
RTCritSectEnter(&pThis->CritSect);
}
if (GetOverlappedResult(pThis->hNmPipe, &pThis->Read.OverlappedIO, &cbRead, TRUE /*fWait*/))
{
*pcbRead = cbRead;
rc = VINF_SUCCESS;
}
else
{
if (pThis->fCancelled)
rc = VERR_CANCELLED;
else
rc = RTErrConvertFromWin32(GetLastError());
}
}
else
{
rc = RTErrConvertFromWin32(GetLastError());
AssertMsgFailedBreak(("%Rrc\n", rc));
}
}
else
rc = VERR_CANCELLED;
break;
}
pThis->Read.hActiveThread = NIL_RTTHREAD;
}
else
rc = VERR_WRONG_ORDER;
rtLocalIpcSessionReleaseAndUnlock(pThis);
}
return rc;
}
#if 0 /* Non-blocking writes are not yet supported. */
/**
* Common worker for handling I/O completion.
*
* This is used by RTLocalIpcSessionClose and RTLocalIpcSessionWrite.
*
* @returns IPRT status code.
* @param pThis The pipe instance handle.
*/
static int rtLocalIpcSessionWriteCheckCompletion(PRTLOCALIPCSESSIONINT pThis)
{
int rc;
DWORD rcWait = WaitForSingleObject(pThis->OverlappedIO.hEvent, 0);
if (rcWait == WAIT_OBJECT_0)
{
DWORD cbWritten = 0;
if (GetOverlappedResult(pThis->hNmPipe, &pThis->OverlappedIO, &cbWritten, TRUE))
{
for (;;)
{
if (cbWritten >= pThis->cbBounceBufUsed)
{
pThis->fIOPending = false;
rc = VINF_SUCCESS;
break;
}
/* resubmit the remainder of the buffer - can this actually happen? */
memmove(&pThis->pbBounceBuf[0], &pThis->pbBounceBuf[cbWritten], pThis->cbBounceBufUsed - cbWritten);
rc = ResetEvent(pThis->OverlappedIO.hEvent); Assert(rc == TRUE);
if (!WriteFile(pThis->hNmPipe, pThis->pbBounceBuf, (DWORD)pThis->cbBounceBufUsed,
&cbWritten, &pThis->OverlappedIO))
{
DWORD dwErr = GetLastError();
if (dwErr == ERROR_IO_PENDING)
rc = VINF_TRY_AGAIN;
else
{
pThis->fIOPending = false;
if (dwErr == ERROR_NO_DATA)
rc = VERR_BROKEN_PIPE;
else
rc = RTErrConvertFromWin32(dwErr);
}
break;
}
Assert(cbWritten > 0);
}
}
else
{
pThis->fIOPending = false;
rc = RTErrConvertFromWin32(GetLastError());
}
}
else if (rcWait == WAIT_TIMEOUT)
rc = VINF_TRY_AGAIN;
else
{
pThis->fIOPending = false;
if (rcWait == WAIT_ABANDONED)
rc = VERR_INVALID_HANDLE;
else
rc = RTErrConvertFromWin32(GetLastError());
}
return rc;
}
#endif
RTDECL(int) RTLocalIpcSessionWrite(RTLOCALIPCSESSION hSession, const void *pvBuf, size_t cbToWrite)
{
PRTLOCALIPCSESSIONINT pThis = (PRTLOCALIPCSESSIONINT)hSession;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTLOCALIPCSESSION_MAGIC, VERR_INVALID_HANDLE);
AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
AssertReturn(cbToWrite, VERR_INVALID_PARAMETER);
int rc = RTCritSectEnter(&pThis->CritSect);
if (RT_SUCCESS(rc))
{
rtLocalIpcSessionRetain(pThis);
if (pThis->Write.hActiveThread == NIL_RTTHREAD)
{
pThis->Write.hActiveThread = RTThreadSelf();
/*
* Try write everything. No bounce buffering necessary.
*/
size_t cbTotalWritten = 0;
while (cbToWrite > 0)
{
DWORD cbWritten = 0;
if (!pThis->fCancelled)
{
BOOL fRc = ResetEvent(pThis->Write.OverlappedIO.hEvent); Assert(fRc == TRUE);
RTCritSectLeave(&pThis->CritSect);
DWORD const cbToWriteInThisIteration = cbToWrite <= ~(DWORD)0 ? (DWORD)cbToWrite : ~(DWORD)0;
fRc = WriteFile(pThis->hNmPipe, pvBuf, cbToWriteInThisIteration, &cbWritten, &pThis->Write.OverlappedIO);
if (fRc)
rc = VINF_SUCCESS;
else
{
DWORD dwErr = GetLastError();
if (dwErr == ERROR_IO_PENDING)
{
DWORD rcWait = WaitForSingleObject(pThis->Write.OverlappedIO.hEvent, INFINITE);
if (rcWait == WAIT_OBJECT_0)
{
if (GetOverlappedResult(pThis->hNmPipe, &pThis->Write.OverlappedIO, &cbWritten, TRUE /*fWait*/))
rc = VINF_SUCCESS;
else
rc = RTErrConvertFromWin32(GetLastError());
}
else if (rcWait == WAIT_TIMEOUT)
rc = VERR_TIMEOUT;
else if (rcWait == WAIT_ABANDONED)
rc = VERR_INVALID_HANDLE;
else
rc = RTErrConvertFromWin32(GetLastError());
}
else if (dwErr == ERROR_NO_DATA)
rc = VERR_BROKEN_PIPE;
else
rc = RTErrConvertFromWin32(dwErr);
}
if (cbWritten > cbToWriteInThisIteration) /* paranoia^3 */
cbWritten = cbToWriteInThisIteration;
RTCritSectEnter(&pThis->CritSect);
if (RT_FAILURE(rc))
break;
}
else
{
rc = VERR_CANCELLED;
break;
}
/* Advance. */
pvBuf = (char const *)pvBuf + cbWritten;
cbTotalWritten += cbWritten;
cbToWrite -= cbWritten;
}
pThis->Write.hActiveThread = NIL_RTTHREAD;
}
else
rc = VERR_WRONG_ORDER;
rtLocalIpcSessionReleaseAndUnlock(pThis);
}
return rc;
}
RTDECL(int) RTLocalIpcSessionFlush(RTLOCALIPCSESSION hSession)
{
PRTLOCALIPCSESSIONINT pThis = (PRTLOCALIPCSESSIONINT)hSession;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTLOCALIPCSESSION_MAGIC, VERR_INVALID_HANDLE);
int rc = RTCritSectEnter(&pThis->CritSect);
if (RT_SUCCESS(rc))
{
if (pThis->Write.hActiveThread == NIL_RTTHREAD)
{
/* No flushing on Windows needed since RTLocalIpcSessionWrite will block until
* all data was written (or an error occurred). */
/** @todo r=bird: above comment is misinformed.
* Implement this as soon as we want an explicit asynchronous version of
* RTLocalIpcSessionWrite on Windows. */
rc = VINF_SUCCESS;
}
else
rc = VERR_WRONG_ORDER;
RTCritSectLeave(&pThis->CritSect);
}
return rc;
}
RTDECL(int) RTLocalIpcSessionWaitForData(RTLOCALIPCSESSION hSession, uint32_t cMillies)
{
PRTLOCALIPCSESSIONINT pThis = (PRTLOCALIPCSESSIONINT)hSession;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTLOCALIPCSESSION_MAGIC, VERR_INVALID_HANDLE);
uint64_t const msStart = RTTimeMilliTS();
int rc = RTCritSectEnter(&pThis->CritSect);
if (RT_SUCCESS(rc))
{
rtLocalIpcSessionRetain(pThis);
if (pThis->Read.hActiveThread == NIL_RTTHREAD)
{
pThis->Read.hActiveThread = RTThreadSelf();
/*
* Wait loop.
*/
for (unsigned iLoop = 0;; iLoop++)
{
/*
* Check for cancellation before we continue.
*/
if (!pThis->fCancelled)
{ /* likely */ }
else
{
rc = VERR_CANCELLED;
break;
}
/*
* Prep something we can wait on.
*/
HANDLE hWait = INVALID_HANDLE_VALUE;
if (pThis->fZeroByteRead)
hWait = pThis->Read.OverlappedIO.hEvent;
else
{
/* Peek at the pipe buffer and see how many bytes it contains. */
DWORD cbAvailable;
if ( PeekNamedPipe(pThis->hNmPipe, NULL, 0, NULL, &cbAvailable, NULL)
&& cbAvailable)
{
rc = VINF_SUCCESS;
break;
}
/* Start a zero byte read operation that we can wait on. */
if (cMillies == 0)
{
rc = VERR_TIMEOUT;
break;
}
BOOL fRc = ResetEvent(pThis->Read.OverlappedIO.hEvent); Assert(fRc == TRUE); NOREF(fRc);
DWORD cbRead = 0;
if (ReadFile(pThis->hNmPipe, pThis->abBuf, 0 /*cbToRead*/, &cbRead, &pThis->Read.OverlappedIO))
{
rc = VINF_SUCCESS;
if (iLoop > 10)
RTThreadYield();
}
else if (GetLastError() == ERROR_IO_PENDING)
{
pThis->fZeroByteRead = true;
hWait = pThis->Read.OverlappedIO.hEvent;
}
else
rc = RTErrConvertFromWin32(GetLastError());
if (RT_FAILURE(rc))
break;
}
/*
* Check for timeout.
*/
DWORD cMsMaxWait = INFINITE; /* (MSC maybe used uninitialized) */
if (cMillies == RT_INDEFINITE_WAIT)
cMsMaxWait = INFINITE;
else if ( hWait != INVALID_HANDLE_VALUE
|| iLoop > 10)
{
uint64_t cMsElapsed = RTTimeMilliTS() - msStart;
if (cMsElapsed <= cMillies)
cMsMaxWait = cMillies - (uint32_t)cMsElapsed;
else if (iLoop == 0)
cMsMaxWait = cMillies ? 1 : 0;
else
{
rc = VERR_TIMEOUT;
break;
}
}
/*
* Wait and collect the result.
*/
if (hWait != INVALID_HANDLE_VALUE)
{
RTCritSectLeave(&pThis->CritSect);
DWORD rcWait = WaitForSingleObject(hWait, cMsMaxWait);
int rc2 = RTCritSectEnter(&pThis->CritSect);
AssertRC(rc2);
rc = rtLocalIpcWinGetZeroReadResult(pThis, rcWait);
break;
}
}
pThis->Read.hActiveThread = NIL_RTTHREAD;
}
rtLocalIpcSessionReleaseAndUnlock(pThis);
}
return rc;
}
RTDECL(int) RTLocalIpcSessionCancel(RTLOCALIPCSESSION hSession)
{
PRTLOCALIPCSESSIONINT pThis = (PRTLOCALIPCSESSIONINT)hSession;
AssertPtrReturn(pThis, VERR_INVALID_HANDLE);
AssertReturn(pThis->u32Magic == RTLOCALIPCSESSION_MAGIC, VERR_INVALID_HANDLE);
/*
* Enter the critical section, then set the cancellation flag
* and signal the event (to wake up anyone in/at WaitForSingleObject).
*/
int rc = RTCritSectEnter(&pThis->CritSect);
if (RT_SUCCESS(rc))
{
rtLocalIpcSessionRetain(pThis);
rc = rtLocalIpcWinCancel(pThis);
rtLocalIpcSessionReleaseAndUnlock(pThis);
}
return rc;
}
RTDECL(int) RTLocalIpcSessionQueryProcess(RTLOCALIPCSESSION hSession, PRTPROCESS pProcess)
{
RT_NOREF_PV(hSession); RT_NOREF_PV(pProcess);
return VERR_NOT_SUPPORTED;
}
RTDECL(int) RTLocalIpcSessionQueryUserId(RTLOCALIPCSESSION hSession, PRTUID pUid)
{
RT_NOREF_PV(hSession); RT_NOREF_PV(pUid);
return VERR_NOT_SUPPORTED;
}
RTDECL(int) RTLocalIpcSessionQueryGroupId(RTLOCALIPCSESSION hSession, PRTGID pGid)
{
RT_NOREF_PV(hSession); RT_NOREF_PV(pGid);
return VERR_NOT_SUPPORTED;
}
|