Repository navigation
Expand file tree
/
Copy pathP2PeerConPipe.cpp
More file actions
1224 lines (1139 loc) · 53.2 KB
/
Copy pathP2PeerConPipe.cpp
File metadata and controls
1224 lines (1139 loc) · 53.2 KB
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 © 2002-2009, 2026 Ivyware Pty Ltd, Khrustal & Mann
// MELBOURNE, VICTORIA, AUSTRALIA, 3000
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//
// Description: P2PeerConPipe implementation
// NOTES: Manages P2Peer RS232 connections
//
#include "stdafx.h"
#include "P2PeerConPipe.h"
#include "P2Pwin32.h"
#ifdef _WIN32
# include <sddl.h>
# pragma comment(lib, "advapi32.lib") // ConvertStringSecurityDescriptorToSecurityDescriptor
#endif
//
// The descriptor a P2PeerConPipeAccess_Owner pipe is created with.
// NOTES: Protected (D:P), so nothing is inherited from anywhere, and three
// ACEs and no more:
// (A;;FA;;;SY) LocalSystem - full
// (A;;FA;;;BA) Administrators - full (they can take ownership
// regardless; denying is theatre)
// (A;;FA;;;OW) Owner Rights - full, so the creating account can
// still open the pipe it made
// : What is NOT here is the change. The platform's default descriptor
// for a named pipe grants READ to Everyone and to Anonymous; a client
// opening GENERIC_READ|GENERIC_WRITE failed on it anyway, but as a
// side effect of the access mask rather than as a decision. This is
// the decision
// : Byte for byte the descriptor P2PIdentityStore.cpp writes on an
// identity file, deliberately. Both are answering "which account may
// reach this endpoint", and two answers to one question that drift
// apart are worse than one answer that is wrong in one place
//
static LPCTSTR kPipeSddlOwner = _T("D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FA;;;OW)");
//
// Whether a pipe name names the LOCAL named-pipe device.
// NOTES: \\.\pipe\Name is NPFS on this machine and nothing else can be;
// \\host\pipe\Name goes out through the SMB redirector and is a
// network path even when host resolves back here. \\localhost\pipe\
// and \\127.0.0.1\pipe\ are therefore Wire by this test, which is
// the fail-closed direction and is meant
// : This is the CLIENT's half of the locality question. A client
// cannot see whether the server passed PIPE_REJECT_REMOTE_CLIENTS -
// but it does not need to, because the reject is what stops a REMOTE
// client, and the only claim being made here is about this end
// : THE PREFIX IS NOT THE WHOLE TEST, and treating it as one was a
// defect - found by a security review of this branch, finding 2.
// \\.\ is the DOS device namespace and, unlike \\?\, a path under it
// is still normalised: \\.\pipe\..\UNC\host\pipe\Name has the prefix
// this function matched, resolves through the redirector, and was
// answered Local. So the remainder is required to be a PIPE NAME and
// nothing else - one component, no separator - which is exactly what
// the platform allows a pipe name to be (every character except a
// backslash), so nothing legitimate is refused and nothing that can
// traverse is admitted
// : This is the CLIENT's half of the locality question. A client
// cannot see whether the server passed PIPE_REJECT_REMOTE_CLIENTS -
// but it does not need to, because the reject is what stops a REMOTE
// client, and the only claim being made here is about this end
// : It is what a client with NO HANDLE answers - a posture reading. A
// client that HAS one is answered by P2PeerConPipeHandleIsLocal()
// below as well, and both must be true. The name is what this end
// asked for; the handle is what it got
//
static bool
P2PeerConPipenameIsLocal ( LPCTSTR pszName )
{
if ( pszName == 0 || *pszName == 0 )
return false;
if ( _tcsnicmp ( pszName, _T("\\\\.\\pipe\\"), 9 ) != 0 &&
_tcsnicmp ( pszName, _T("//./pipe/"), 9 ) != 0 )
return false;
// The remainder is the pipe name. Empty is not a name, and a separator
// in it means the path leaves \\.\pipe\ for somewhere this function
// cannot vouch for - refer the note above
const TCHAR *pszLeaf = pszName + 9;
if ( *pszLeaf == 0 )
return false;
for ( const TCHAR *p = pszLeaf; *p != 0; ++p )
if ( *p == _T('\\') || *p == _T('/') )
return false;
return true;
}
#ifdef _WIN32
//
// Whether an OPEN pipe handle is served from this machine.
// NOTES: The kernel's own answer, and the half the name cannot give. A
// server process id is meaningless across a machine boundary, so the
// redirector cannot answer for one and the call fails on a pipe
// reached over SMB; it succeeds on a local pipe from the handle alone,
// with no rights beyond having opened it
// : ANY failure reads as not-local. This is the fail-closed direction
// for a class - a link that cannot be shown to be local is a wire -
// and it is the direction every other reading in this feature takes
// : Asked ONCE, in Connect(), and recorded. The note this replaces said
// a handle reading would cost a syscall "on every posture read", which
// was true of asking it from TrustClass(); it is not true of asking it
// where the handle is opened
//
static bool
P2PeerConPipeHandleIsLocal ( HANDLE hPipe )
{
if ( hPipe == 0 || hPipe == INVALID_HANDLE_VALUE )
return false;
ULONG ulServerPid = 0;
return GetNamedPipeServerProcessId ( hPipe, &ulServerPid ) ? true : false;
}
#endif
///////////////////////////////////////////////////////////////////////
// Constructors and destructor
const __time64_t
iLoginTimeoutSeconds = 20; // Login sequences must be
// processed within this time
P2PeerConPipe::P2PeerConPipe ( )
{
// Firstly
RenderThisSafe ( );
}
//
// Parameters: P2PaddrSTR strThatP2Paddr
// Identification address for that, or the other end
//
// LPCTSTR lpszPipename
// Pipe name
//
P2PeerConPipe::P2PeerConPipe ( P2PaddrSTR pThatP2PaddrSTR
, LPCTSTR lpszPipename
, P2Peerio *pP2Peerio )
: P2PeerCon ( pThatP2PaddrSTR, pP2Peerio )
{
// Firstly
RenderThisSafe();
m_sPipename = lpszPipename;
}
//
// short nIPort
// Listening port
//
P2PeerConPipe::P2PeerConPipe ( LPCTSTR lpszPipename
, P2Peerio *pP2Peerio )
: P2PeerCon ( pP2Peerio )
{
// Firstly
RenderThisSafe();
m_sPipename = lpszPipename;
}
P2PeerConPipe::~P2PeerConPipe ( )
{
// Resource collection
Drop ( 0 );
}
void
P2PeerConPipe::RenderThisSafe()
{
// Attributes
m_hFile = 0;
// Locality
// NOTES: The DEFAULT MOVED. Every pipe this transport creates now
// refuses remote clients and takes the descriptor above; the old
// call is P2PeerConPipeAccess_Legacy and has to be asked for
// : m_bPipeLocal is false because there is no handle yet, and it is
// never true of anything but a handle
// : m_bPipeRearm is false because a fresh object is the FIRST
// instance of whatever it creates; only AcceptSpawn says otherwise
m_ePipeAccess = P2PeerConPipeAccess_Owner;
m_bPipeLocal = false;
m_bPipeRearm = false;
}
P2PeerConPipe*
P2PeerConPipe::ServiceFactory ( P2PaddrSTR strP2PaddrThat
, LPCTSTR lpszPipename )
{
// Instanciate
P2PeerConPipe *pCon = new P2PeerConPipe ( );
// Attributes
pCon -> m_oThatP2Paddr = strP2PaddrThat;
pCon -> m_oP2Padomain = strP2PaddrThat;
pCon -> m_eP2PeerConMode = P2PeerCon_SERVICE;
pCon -> m_sPipename = lpszPipename;
// Protocol
// NOTES: Instance is cloned for accepted connections
pCon -> SetP2Peerio ( new P2Peerio( ) );
// Done
return pCon;
}
P2PeerConPipe*
P2PeerConPipe::ClientFactory ( P2PaddrSTR strP2PaddrThat
, LPCTSTR lpszPipename )
{
// Instanciate
P2PeerConPipe *pCon = new P2PeerConPipe ( );
// Attributes
pCon -> m_oThatP2Paddr = strP2PaddrThat;
pCon -> m_eP2PeerConMode = P2PeerCon_CLIENT;
pCon -> m_sPipename = lpszPipename;
// Protocol
pCon -> SetP2Peerio ( new P2Peerio( ) );
// Done
return pCon;
}
//
// Description: Splits listening connection into listening and
// accepted P2PeerCon'nections
// NOTES: Derived classes must delegate
//
//
// Parameters: P2PeerCon **pConListen = 0
// Previously manufactured listening instance
//
// P2PeerCon **pConAccept = 0
// Previously manufactured accept instance
//
P2PeerCon*
P2PeerConPipe::AcceptSpawn ( P2PeerCon *pConSpawn )
{
// Instanciation etc
if ( pConSpawn == NULL )
pConSpawn = new P2PeerConPipe ( );
// Settlement
// NOTES: Accept removes the allocated socket
P2PeerConPipe *pConSpawnPipe = (P2PeerConPipe *)pConSpawn;
P2PeerCon::AcceptSpawn ( pConSpawn );
pConSpawnPipe -> m_sPipename = m_sPipename;
pConSpawnPipe -> m_eP2PeerConMode = P2PeerCon_SERVICE;
this -> m_eP2PeerConMode = P2PeerCon_Accept;
// Locality
// NOTES: The roles swap here - THIS becomes the accepted connection and
// keeps the handle it created, the SPAWN becomes the service and
// re-arms with a CreateListenPipe() of its own. So the SETTING
// travels (or the second instance of a pipe would be a different
// pipe from the first) and the FACT does not: m_bPipeLocal stays
// false on the spawn until its own CreateNamedPipe succeeds, and
// stays whatever it was on this, which is what this handle was
// actually made with
// : ...and the spawn is told it is a RE-ARM. Its CreateNamedPipe
// will be a further instance of the pipe THIS still holds, so it
// must not ask for FILE_FLAG_FIRST_PIPE_INSTANCE - that would
// refuse this transport's own pipe. Refer CreateListenPipe()
pConSpawnPipe -> m_ePipeAccess = m_ePipeAccess;
pConSpawnPipe -> m_sPipeSddl = m_sPipeSddl;
pConSpawnPipe -> m_bPipeRearm = true;
// Accept admission control, PUT BACK THE RIGHT WAY ROUND
// NOTES: THE BASE'S ASSIGNMENT IS CORRECT FOR EVERY TRANSPORT WHOSE SPAWN
// IS THE CHILD, AND BACKWARDS FOR THIS ONE. P2PeerCon::AcceptSpawn
// zeroes the spawn's cap and marks the spawn as one of the counted
// children, because on P2PeerConWsa the spawn IS the accepted
// connection and the service is left alone. Here the roles swap -
// refer the note above - so the base has just zeroed the cap on the
// object that will evaluate it for the NEXT client, and pinned the
// slot to the object that is about to hold the listener.
// : What that cost, measured rather than reasoned about
// (p2p_pipecap, 2026-09-20):
// - the CAP survived exactly one accept. SetMaxAccepted(n) on a
// pipe service bound the first client and nothing after it,
// because from the second accept onwards AcceptAtCapacity() was
// being asked of a service whose m_xMaxAccepted was 0
// - the COUNT was off by one permanently, and in the direction that
// never frees. The increment landed on the SERVICE, which is not
// destroyed while it is serving, so the first client's departure
// gave nothing back. A cap of 1 would have admitted one client
// for the lifetime of the process
// : Only the ATTRIBUTION moves. The base's fetch_add is right in
// number - one accept, one slot - and is deliberately neither
// repeated nor undone here
// : The per-source pair moves with it although AcceptSourceKey() is 0
// on this transport and the bound therefore applies to nothing
// (P2PeerCon.h:226-230). Leaving one half of a pair swapped and
// the other not is how the next reader of this function gets it
// wrong. m_xAcceptSource needs no move for the same reason it
// needs no clear: with a zero key the base stored 0 into it and
// took no per-source slot
// : READ BEFORE ZEROED. this->m_xMaxAccepted is the source of the
// value being handed on, so the store into THIS has to come second
pConSpawnPipe -> m_xMaxAccepted . store ( m_xMaxAccepted.load ( ) );
pConSpawnPipe -> m_xMaxAcceptedPerSource . store ( m_xMaxAcceptedPerSource
.load ( ) );
pConSpawnPipe -> m_bAcceptCounted = false;
this -> m_xMaxAccepted . store ( 0 );
this -> m_xMaxAcceptedPerSource . store ( 0 );
this -> m_bAcceptCounted = true;
// Done
// NOTES: Spawned object is free floating
return pConSpawn;
}
///////////////////////////////////////////////////////////////////////
// IOCP Integration
//
//
// Description: Drops the encapsulated connection and performs the
// appropriate ON_P2PeerCon_CLOSE() notification
// NOTES: Should an EVENT already be attached the passed
// EVENT is simply cancelled.
//
//
// Parameters: P2Pevent *pEVENT
// Precipitating event. May be NULL
// NOTES: Control assumed over life cycle.
//
void
P2PeerConPipe::Drop ( P2Pevent *pEVENT )
{
// Firstly drop socket
// NOTES: Cancels all outstanding overlapped IO
if ( m_hFile )
{
if ( CloseHandle(m_hFile) &&
!pEVENT )
pEVENT =
EVERR->Module (L"%hs(%s-%s)", __FUNCTION__
, GetP2PaddrHub().c_wstr()
, (P2PaddrSTR)m_oThatP2Paddr )
->Message (L"closehandle(%s) failed\n"
L"ADVICE\t: Bug (SNHappen)"
, (LPCTSTR)m_sPipename )
->HResult ( GetLastError() );
m_hFile = 0;
m_hFileCPort = 0;
m_bPipeLocal = false; // the fact goes with the handle
}
// Always delegate
P2PeerCon::Drop ( pEVENT );
}
///////////////////////////////////////////////////////////////////////
// Connection state management
// NOTES: Referenced from P2PeerCon_MAP handlers only
//
// Description: Initiates listen processing for object.
// NOTES: Referenced from On_P2PeerCon_STARTUP handlers
// for listen type objects.
//
//
// Returns: bool
// Listen summary
//
bool
P2PeerConPipe::Listen ( )
{
// State confirmation
P2PeerCon::Listen ( );
// On_P2PeerCon_LISTEN() notification
// NOTES: Synchronous activity
PostP2Pmsg ( m_oThatP2Paddr, CN_P2PeerCon, P2P_Listen
, this, (P2PeerMsg *)0, m_hCPortP2PumpID );
// Tidy up and
return true;
}
//
// Description: Initiates listen processing for object.
// NOTES: Referenced from On_P2PeerCon_STARTUP handlers
// for listen type objects.
//
//
// Returns: bool
// Listen summary
//
void
P2PeerConPipe::OnListen ( )
{
// State confirmation
// NOTES: Delegate to base for the ON_P2PeerCon_LISTEN handler-state audit,
// consistent with P2PeerConWsa::OnListen(). Both real listen paths
// (P2PeerTarget::On_ConListen, P2PeerExplorer::On_XCidSvrListen) are
// dispatched under {CN_P2PeerCon, P2P_Listen}, so the audit holds.
// : Kept OUT of the shared pipe-creation helper (CreateListenPipe)
// because Accept() lazily (re)creates the pipe from the P2P_Accept
// re-arm state, where the P2P_Listen audit would (correctly) fail.
P2PeerCon::OnListen ( );
// Named pipe creation
CreateListenPipe ( );
}
//
// Creates the listening named pipe and binds it to the IO completion port.
// NOTES: State-agnostic - shared by OnListen() (true listen path) and the
// lazy re-arm inside Accept() (dispatched under P2P_Accept). Performs
// no pump-state confirmation; that audit lives in OnListen().
//
void
P2PeerConPipe::CreateListenPipe ( )
{
// Named pipe creation
// NOTES: FILE_FLAG_OVERLAPPED is mandatory when using IO
// completion ports
// : Normally this is done in Listen(). But, pipes are
// different whereby the listening P2PeerCon morphs into the
// accepted connection
ASSERT(m_hFile==0);
// Locality
// NOTES: PIPE_REJECT_REMOTE_CLIENTS and an explicit descriptor together,
// because they answer different halves and only both make the
// class true: the reject keeps the SMB redirector out, the DACL
// decides which local account may open what is left
// : Legacy reproduces the pre-revision call exactly - no reject,
// NULL descriptor - and the pipe it makes reads Wire. It exists
// so that a deployment which shares a pipe across accounts, or
// reaches one over SMB, upgrades by naming that rather than by
// finding out
// : On the Linux mapping CreateNamedPipe is socket/bind/listen on an
// AF_UNIX path and BOTH arguments are ignored (Msgcore Platform
// README, "where the substrate shows through" 2 and 4). There is
// no AF_UNIX equivalent of a pipe over SMB, so locality is a
// property of the address family and holds in every mode; what has
// no counterpart is the DACL, and access control there is the 0700
// directory plus the process umask. Hence Local for all three
// modes on that platform, and a comment rather than a pretence
// that the descriptor was applied
// Squatting
// NOTES: A named pipe carries the descriptor its FIRST instance was made
// with. A later CreateNamedPipe on the same name is a further
// instance of THAT pipe: it passes an access check against the
// existing descriptor, and the descriptor it brings is not the one
// the endpoint gets. So a local principal that creates the name
// first, with a DACL of their choosing, would have this transport
// join their pipe - traffic behind their DACL, the client's opens
// admitted on their terms - while the derivation below still read
// back the reject and the descriptor THIS end passed, and the
// class said Local
// : FILE_FLAG_FIRST_PIPE_INSTANCE is the kernel's answer: with it
// the create FAILS, ERROR_ACCESS_DENIED, if any instance of the
// name already exists. Passed on the FIRST instance this
// transport makes and NOT on the re-arm, because the re-arm is by
// definition a second instance of a pipe this transport already
// holds - the accepted connection is still open on it, under this
// transport's own descriptor - and the flag there would refuse the
// transport's own pipe. AcceptSpawn is what tells the spawn it is
// a re-arm
// : NOT passed under Legacy, which is the pre-revision call byte for
// byte and is documented as such. A legacy pipe reads Wire, so
// its policy is Full and a squatter gains nothing past the login
// gate; the flag is a property of the class this transport claims,
// and Legacy claims none
// : What this leaves open is stated rather than hidden: if the
// accepted sibling drops before the spawn re-arms, the name is
// briefly free, and a re-arm in that window joins whatever was
// created into it. The window is one pump dispatch wide and the
// spawn cannot see across it; closing it means reading the
// descriptor back off the created handle, which is a separate
// change
#ifdef _WIN32
DWORD dwOpenMode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED;
DWORD dwPipeMode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE;
SECURITY_ATTRIBUTES oSA;
PSECURITY_DESCRIPTOR pSD = NULL;
LPSECURITY_ATTRIBUTES pSA = NULL;
if ( m_ePipeAccess != P2PeerConPipeAccess_Legacy )
{
if ( !m_bPipeRearm )
dwOpenMode |= FILE_FLAG_FIRST_PIPE_INSTANCE;
LPCTSTR pszSddl = ( m_ePipeAccess == P2PeerConPipeAccess_Descriptor )
? (LPCTSTR)m_sPipeSddl
: kPipeSddlOwner;
// A descriptor that does not parse THROWS. Falling back to the
// platform default would hand the caller a wider pipe than the one
// they asked for, silently, which is the failure this whole change
// exists to remove
if ( !ConvertStringSecurityDescriptorToSecurityDescriptor (
pszSddl, SDDL_REVISION_1, &pSD, NULL ) )
EVERR->MODULE
->Message(L"SDDL(%s) for pipe %s does not parse\n"
L"ADVICE\t: Check the string given to SetPipeAccess"
L", or ask for P2PeerConPipeAccess_Owner"
, pszSddl, (LPCTSTR)m_sPipename )
->HResult( GetLastError() )->Throw();
oSA.nLength = sizeof(oSA);
oSA.lpSecurityDescriptor = pSD;
oSA.bInheritHandle = FALSE;
pSA = &oSA;
dwPipeMode |= PIPE_REJECT_REMOTE_CLIENTS;
}
#else
// The Linux mapping ignores the open mode outright - refer the note
// above - and has no FILE_FLAG_FIRST_PIPE_INSTANCE to pass. Squatting
// has no counterpart there either: bind() on an AF_UNIX path that exists
// fails, it does not join
DWORD dwOpenMode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED;
DWORD dwPipeMode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE;
void *pSA = NULL;
#endif
// Maximum number of instances
// NOTES: WAS A LITERAL 2 until 2026-09-20, and that number bounded this
// transport in place of the policy that is supposed to. It is
// OpenCodeWork.md item 2's "a documented bound that does not
// bound", and what SetMaxAccepted() now does is what it claimed to
// do all along
// : THE LITERAL WAS NOT WORTH 2 CLIENTS, IT WAS WORTH ONE. This
// transport must hold a spare LISTENING instance at all times: the
// accepted connection keeps the instance it was accepted on, and
// the spawned service re-arms on a fresh one. So n instances serve
// n-1 clients, and the second client's re-arm failed ERROR_PIPE_BUSY
// (231) out of this very call - inside accept processing, where the
// throw took the process with it. Measured, not read:
// p2p_pipecap --uncapped, 2026-09-20
// : WHAT THIS WIDENS, stated rather than buried. A service that sets
// no cap went from one concurrent client to 255. That is the
// correct direction only because the refusal above it now exists -
// P2PeerConPipe::OnAccept() consults AcceptAtCapacity() and drops
// the client cleanly - and a deployment that wants the old number
// asks for it in the one place that means it: SetMaxAccepted(1)
// : Ignored on the Linux mapping, which has no instance notion and
// listens with a backlog of 8 (Platform/p2psock.h:404). So this
// line was never the bound there and the two platforms only now
// agree on what bounds them
m_hFile = CreateNamedPipe ( m_sPipename
, dwOpenMode
, dwPipeMode
, PIPE_UNLIMITED_INSTANCES
, 64000 // output buffer size
, 64000 // input buffer size
, 1000 // time-out interval
, pSA );
const DWORD dwCreateErr = GetLastError ( );
#ifdef _WIN32
if ( pSD )
LocalFree ( pSD );
#endif
if ( m_hFile == INVALID_HANDLE_VALUE )
{
m_hFile = 0;
// The name was already taken, and this was meant to be its first
// instance. Named separately because the advice is different: the
// assignment is fine, it is the NAME that is held by somebody else -
// a previous server still running, or a squatter - and the refusal is
// the protection working rather than a configuration to check
#ifdef _WIN32
if ( dwCreateErr == ERROR_ACCESS_DENIED &&
( dwOpenMode & FILE_FLAG_FIRST_PIPE_INSTANCE ) != 0 )
// One line per call: Message()/Advice() VERIFY each formatted line is
// under 255 characters, and this was one Message of 324 before the
// name was substituted twice (3.4.1, refer ~P2PeerHub)
EVERR->MODULE
->Message(L"CreateNamedPipe(%s) refused: the name already has "
L"an instance and this service creates the first"
, (LPCTSTR)m_sPipename )
->Advice (L"Another process holds %s - a server still running, "
L"or a squatter"
, (LPCTSTR)m_sPipename )
->Advice (L"Refused rather than joined, because a joined pipe "
L"keeps the FIRST creator's descriptor, not this one's" )
->Advice (L"Stop the other holder, or choose a name" )
->HResult( dwCreateErr )->Throw();
#endif
EVERR->MODULE
->Message(L"CreateNamePipe(%s) failed\n"
L"ADVICE\t: Check assignment for %s"
, (LPCTSTR)m_sPipename, (LPCTSTR)m_sPipename )
->HResult( dwCreateErr )->Throw();
}
// The FACT, and DERIVED FROM THE ARGUMENTS THAT WERE ACTUALLY PASSED
// rather than recorded beside them.
// NOTES: This is a deliberate three lines rather than one assignment in
// the branch that asked for the reject. A flag set beside a
// request records the request; reading back the two values the
// kernel was handed records what the kernel was told. Delete
// either the |= or the descriptor above and this answer changes,
// and p2p_linktrust phase 9 goes red - which an adjacent
// "m_bPipeLocal = true" would not have done
// : BOTH halves, because the class needs both to be true. Neither
// one alone: a reject with the platform's descriptor still lets
// Everyone read the endpoint, and a descriptor without the reject
// still lets the redirector carry it off the machine
// : THREE halves since the squatting note above, and the third is
// what makes the first two MEAN anything: a reject and a
// descriptor were only APPLIED if this create was the pipe's first
// instance - which the flag makes the kernel guarantee - or a
// re-arm of a pipe whose first instance this transport made.
// Read back from the open mode that was passed, as the other two
// are, so deleting the |= above turns the class to Wire
// : On the Linux mapping neither argument reached the kernel - the
// call was socket/bind/listen on an AF_UNIX path - so neither can
// be read back. What makes the class true there is the address
// family, which is not an argument and cannot be got wrong. Refer
// the note above
#ifdef _WIN32
m_bPipeLocal = ( dwPipeMode & PIPE_REJECT_REMOTE_CLIENTS ) != 0 &&
pSA != NULL &&
( ( dwOpenMode & FILE_FLAG_FIRST_PIPE_INSTANCE ) != 0 ||
m_bPipeRearm );
#else
m_bPipeLocal = true;
#endif
// THE FENCE, asked again now that the class is a FACT
// NOTES: P2PeerHub::PostP2PeerCon already asked it, and at that moment
// this object had no handle: TrustClass() answered from
// m_ePipeAccess, which is an INTENTION and which SetPipeAccess()
// can still change afterwards. A service posted to a hub fenced at
// Local while it meant to make an Owner pipe, then told
// P2PeerConPipeAccess_Legacy before it listened, passed the fence
// and then created a wire - which is finding 3 of the branch review
// : Here the pipe EXISTS and m_bPipeLocal was read back out of the
// arguments the kernel was actually given, so this is the last
// moment before the endpoint can carry anything and the first at
// which the answer cannot change underneath it
// : THE HANDLE IS CLOSED BEFORE THE THROW. A listener that the hub
// will not hold must not be left with a created pipe: the name
// would be taken, and a later re-arm - or another service - would
// find it occupied by an endpoint nothing is listening on
// : Covers the re-arm too, which is the path an accepted child's
// sibling takes, so a fence raised or a mode changed between
// accepts is caught at the next one rather than at none
if ( TrustFenceRefuses ( ) )
{
const P2PeerConTrust_e eFloor = TrustFenceFloor ( );
const P2PeerConTrust_e eClass = EffectiveTrust ( );
CloseHandle ( m_hFile );
m_hFile = 0;
m_bPipeLocal = false;
// One line per call, under 255 characters each (3.4.1, refer the
// CreateNamedPipe refusal above)
EVERR->MODULE
->Message(L"Pipe %s is trust class %i and its hub holds no link "
L"below class %i"
, (LPCTSTR)m_sPipename, (int)eClass, (int)eFloor )
->Advice (L"0 wire, 1 kernel-local, 2 in-process" )
->Advice (L"SetPipeAccess() asked for a pipe of a class this hub "
L"was fenced to refuse - drop the "
L"P2PeerConPipeAccess_Legacy, or widen the fence with "
L"RequireTrustAtLeast()" )
->Advice (L"Listener not created" )
->Throw();
}
// Associate with IO Completion Port
// NOTES: All subsequent notifications received via queued
// IO Completion Packets
CreateIOCP ( m_hFile );
}
//
// Initiates accept connection processing for SERVICE object.
// NOTES: Usually referenced from ON_P2PeerCon_STARTUP handlers.
// : Accepted connections are intercepted in
// ON_P2PeerOLD_ACCEPT handlers
// : Refer Connect() for CLIENT side equivalent.
//
//
// Returns: bool
bool
P2PeerConPipe::Accept ( )
{
if (!m_hFile)
CreateListenPipe(); // create the pipe without the P2P_Listen state audit
// (this path runs under the P2P_Accept re-arm)
// State confirmation
P2PeerCon::Accept ( );
// Initiate wait for client connection
// NOTES: Must be a non-pended operation
if ( m_pOVERLAPPEDaccept == NULL )
m_pOVERLAPPEDaccept = MakeOVERLAPPED ( );
prepareOVERLAPPED ( m_pOVERLAPPEDaccept );
if ( !ConnectNamedPipe ( m_hFile
,(OVERLAPPED *)m_pOVERLAPPEDaccept ) &&
GetLastError() != ERROR_IO_PENDING )
{
releaseOVERLAPPED ( m_pOVERLAPPEDaccept );
HRESULT hr = GetLastError ( );
if ( hr != ERROR_PIPE_CONNECTED )
EVERR->Module (L"%hs(%s-%s)", __FUNCTION__
, GetP2PaddrHub().c_wstr()
, m_oThatP2Paddr.c_wstr() )
->Message (L"ConnectNamePipe() failed")
->HResult ( hr )->Throw();
// Accept must be simulated whenever client connects between
// CreateNamedPipe() and ConnectNamedPipe()
PostOVERLAPPED ( m_pOVERLAPPEDaccept );
}
// Accept-completion processing (spawn accepted connection + re-listen)
// is posted asynchronously from On_QueuedCompletionStatus, the
// m_pOVERLAPPEDaccept branch (P2P_Accept via ExtractAccept() + P2P_Listen),
// consistent with P2PeerConWsa::Accept() and P2PeerConDmx::Accept() which
// likewise post nothing at their tail. No inline P2P_Connect is emitted
// here: that event belongs to the outbound connect-completion path
// (see line ~247), not the inbound accept path.
return true;
}
//
// ACCEPT'ed connection processing
// NOTES: Processing must be performed for all accepted connections
// : Reference from within ON_P2PeerOLD_ACCEPT() handlers
//
//
// Parameters: P2PaddrSTR pThatP2PaddrSTR
// Address assigned to remote client
// NOTES: Assignment may be defered to the login
// phase by specifying a NULL value
// Returns: P2PeerCon*
// Accepted and spawned P2PeerConPipe object
//
P2PeerCon*
P2PeerConPipe::OnAccept ( )
{
// State confirmation
// NOTES: Audits the development cycle and traps illogical states
// that can propogate subtle bugs.
// : Low frequency check more than worth the overhead
if ( !CheckP2PmsgPumpState(CN_P2PeerCon,P2P_Accept) )
EVERR->Module (L"%hs(%s-%s)", __FUNCTION__
, GetP2PaddrHub().c_wstr()
, (P2PaddrSTR)m_oThatP2Paddr )
->Message(L"Requires ON_P2PeerOLD_ACCEPT handler state")
->Advice (L"Bug (SNHappen)" )
->Throw ( );
// Mode confirmation
// NOTES: Audits the development cycle and traps illogical states
// that can propogate subtle bugs.
// : Low frequency check more than worth the overhead
if ( m_eP2PeerConMode != P2PeerCon_SERVICE )
EVERR->Module (L"%hs(%s-%s)", __FUNCTION__
, GetP2PaddrHub().c_wstr()
, m_oThatP2Paddr.c_wstr() )
->Message(L"Requires P2PeerCon_SERVICE mode not %i"
, m_eP2PeerConMode )
->Advice (L"Bug (SNHappen)" )
->Throw ( );
// Accept admission control (OpenCodeWork.md item 2)
// NOTES: SetMaxAccepted() was enforced in P2PeerConWsa alone until
// 2026-09-19, so this transport was bounded only by the literal 2
// handed to CreateNamedPipe as nMaxInstances - a number it does not
// own and cannot be asked about. The DECISION has always been on
// the base (AcceptAtCapacity, P2PeerCon.h:255); what was missing is
// this call. P2PeerCon.h:237-238 says why it has to be made here
// rather than there: "the refusal itself is transport-specific,
// because only the transport knows how to discard a half-accepted
// endpoint".
// : BEFORE the swap below, deliberately. AcceptSpawn() is what turns
// THIS into the accepted connection and hands the service role to a
// new instance; refusing afterwards would mean unwinding that.
// Refused here, THIS is still the SERVICE and has simply not
// produced a child.
// : Returning NULL is already handled by the caller and needs no
// change there. P2PeerTarget::On_ConAccept seeds pConService with
// the listener (:2469) and only swaps if the listener MORPHED
// (:2471) - which it has not - so the accepted-client block at
// :2481 is skipped, no login deadline is armed for a connection
// that does not exist, and :2516 re-arms THIS with Accept().
// : THE DROP IS NOT THE SAME CALL ON BOTH PLATFORMS, and writing it
// as though it were is a bug this comment exists to stop being
// reintroduced. On Windows m_hFile is the pipe INSTANCE and
// ConnectNamedPipe leaves it alone, so DisconnectNamedPipe returns
// it to the disconnected state and the re-arm's ConnectNamedPipe
// has something to wait on. On Linux the shim MORPHS the handle:
// ConnectNamedPipe closes the listen socket and puts the accepted
// fd in its place (Platform/p2psock.h:432), and
// DisconnectNamedPipe is a no-op returning TRUE (:434). So the
// Windows call would leave the client connected AND leave m_hFile
// holding a connected socket that Accept() would then try to
// accept() on. Closing it and nulling it is the Linux drop, and
// Accept()'s `if (!m_hFile) CreateListenPipe()` rebuilds the
// listener - CreateNamedPipeW unlinks the stale socket path before
// it binds (:412), so the rebind is clean
// : Worth recording while here: that shim ignores nMaxInstances
// entirely and listens with a backlog of 8, so the "cap of 2" this
// transport was said to have is a WINDOWS-only accident. On Linux
// the pipe transport had no accept bound of any kind before this
// : NOT per-source. AcceptSourceKey() is 0 for this transport and
// deliberately so - a pipe instance is peer by construction, so a
// per-source share would divide a share of one. Refer
// P2PeerCon.h:226-230
// : AND THE HANDLE IS NOT THE ONLY THING THAT GOES WITH IT. The
// first draft of the Linux drop closed m_hFile and nulled it and
// stopped there, leaving m_hFileCPort holding the association of a
// file that no longer exists. The re-arm then reached the tail of
// CreateListenPipe(), where CreateIOCP() refuses outright on a
// non-zero m_hFileCPort - "IOCP already created", P2PeerCon.cpp:426
// - and THREW, inside accept processing, so the listener was never
// rebuilt. That reads exactly like a refusal that works, for as
// long as nobody knocks again, which is the thing p2p_pipecap
// phase 3 exists to tell apart: it saw the third client's open
// refused and the count back at 0, on the Linux gate, 2026-09-21
// : Every other place this transport drops a handle clears all three
// together - Drop() and OnClose() - and the comment there is the
// one that belongs here: the fact goes with the handle
if ( AcceptAtCapacity ( ) )
{
#ifdef _WIN32
DisconnectNamedPipe ( m_hFile );
#else
CloseHandle ( m_hFile );
m_hFile = 0;
m_hFileCPort = 0;
m_bPipeLocal = false;
#endif
if ( IsEVTRC )
EVTRC->Module (L"%hs[%s]", __FUNCTION__
, GetP2PaddrHub().c_wstr() )
->Message(L"Accept refused, at capacity %i"
, m_xMaxAccepted.load ( ) )
->Advice_T("Raise P2PeerCon::SetMaxAccepted(), or 0 to unbound")
->Cancel ( );
return NULL;
}
// Spawn accepted P2PeerCon
// NOTES: Effectively the roles are swapped, service becomes
// accepted connection and accepted connection becomes
// the service
P2PeerConPipe *pConAccept = this;
P2PeerCon *pConService = AcceptSpawn ( 0 );
if ( pConAccept == NULL )
return pConAccept;
// Associate with IO Completion Port
// NOTES: All subsequent notifications received via queued
// IO Completion Packets
//if ( !pConAccept->m_hFileCPort &&
// pConAccept->m_hFile )
// pConAccept -> CreateIOCP ( pConAccept->m_hFile );
// Activate P2PeerMsg receipt
// NOTES: Action is negated whenever OVERLAPPEDrecv object already
// exists
if ( !pConAccept->m_pOVERLAPPEDsend )
pConAccept -> m_pOVERLAPPEDsend = pConAccept -> MakeOVERLAPPED ( );
if ( !pConAccept->m_pOVERLAPPEDrecv )
pConAccept -> m_pOVERLAPPEDrecv = pConAccept -> MakeOVERLAPPED ( MAX_P2Psize );
if ( !pConAccept->m_pOVERLAPPEDrecv->bQueued )
pConAccept -> PostOVERLAPPED ( pConAccept->m_pOVERLAPPEDrecv );
// Tidy up, and
pConAccept -> SetState ( ConState_Send | ConState_Recv, 0 );
return pConService;
}
//
// Performs ACCEPT'ed connection processing for SERVICE connections
// NOTES: This processing must be performed for all accepted
// connections
// : Reference from within ON_P2PeerOLD_ACCEPT() handlers
//
//
// Parameters: const P2Paddr oThatP2Paddr
// Identification assigned to remote client
// NOTES: Assignment may be defered to the login
// phase by specifying a NULL value
//
void
P2PeerConPipe::OnAccept ( const P2Paddr oThatP2Paddr )
{
// State confirmation
// NOTES: Audits the development cycle and traps illogical states
// that can propogate subtle bugs.
// : Low frequency check more than worth the overhead
if ( !CheckP2PmsgPumpState(CN_P2PeerCon,P2P_Accept) )
EVERR->Module (L"%hs(%s-%s)", __FUNCTION__
, GetP2PaddrHub().c_wstr()
, (P2PaddrSTR)m_oThatP2Paddr )
->Message(L"Requires ON_P2PeerOLD_ACCEPT handler state\n"
L"ADVICE\t: Bug (SNHappen)" )
->Throw ( );
// To be sure, to be sure
if ( !oThatP2Paddr.IsNull() &&
!m_oThatP2Paddr.IsNull() &&
m_oThatP2Paddr != oThatP2Paddr )
EVERR->MODULE
->Message(L"Attempt to swap P2PeerID's from [%s] to [%s]"
, (P2PaddrSTR)m_oThatP2Paddr
, (P2PaddrSTR) oThatP2Paddr )
->Throw();
// Assign
if ( !oThatP2Paddr.IsNull() )
m_oThatP2Paddr = oThatP2Paddr;
//// Associate with IO Completion Port
//// NOTES: All subsequent notifications received via queued
//// IO Completion Packets
//m_hFileCPort = CreateIoCompletionPort ( (HANDLE)m_hFile
// , m_hCPort
// ,(ULONG_PTR)this
// , 0 );
//if ( m_hFileCPort == 0 )
// EVERR->Module ("%s(%s-%s)", __FUNCTION__
// , EncodeP2PeerID(m_oThisP2Paddr)
// , EncodeP2PeerID(m_oThatP2Paddr) )
// ->Message ("CreateIoCompletionPort() failed")
// ->WSAGROUP( GetLastError() )->Throw();
// Activate P2PeerMsg receipt
// NOTES: Action is negated whenever OVERLAPPEDrecv object already
// exists
if ( !m_pOVERLAPPEDrecv )
m_pOVERLAPPEDrecv = MakeOVERLAPPED ( MAX_P2Psize );
if ( !m_pOVERLAPPEDrecv->bQueued )
PostOVERLAPPED ( m_pOVERLAPPEDrecv );
if ( !m_pOVERLAPPEDsend )
m_pOVERLAPPEDsend = MakeOVERLAPPED ( );
// Tidy up, and
SetState ( ConState_Recv|ConState_Send, 0 );
return;
}
//
// Initiates accept connection processing for CLIENT object.
// NOTES: Usually referenced from ON_P2PeerCon_STARTUP handlers.
// : Successfull connections are intercepted in
// ON_P2PeerCon_CONNECT handlers
// : Refer Accept() for SERVICE side equivalent.
//
//
// Returns: bool
// Connection summary
//
bool
P2PeerConPipe::Connect ( )
{
// State confirmation
// NOTES: Audits the development cycle and traps illogical states
// that can propogate subtle bugs.
// : Low frequency check more than worth the overhead
if ( !CheckP2PmsgPumpState(CN_P2PeerCon,P2P_Startup) )
EVERR->Module (L"%hs(%s-%s)", __FUNCTION__
, GetP2PaddrHub().c_wstr()
, m_oThatP2Paddr.c_wstr() )
->Message(L"Requires ON_P2PeerCon_STARTUP handler state\n"
L"ADVICE\t: Bug (SNHappen)" )
->Throw ( );
// Open COM port
// NOTES: FILE_FLAG_OVERLAPPED is mandatory when using IO
// completion ports
// NOTES: SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION. Without them a
// pipe server may impersonate whoever opens it, at the default
// level, and act as that account - so a rogue server squatting the
// name is handed the client's token rather than merely its bytes.
// IDENTIFICATION lets the server ask who the client is, which is
// what a server legitimately wants, and stops it from being them,
// which nothing here ever wanted. securityRevision.md finding 3
// : Guarded because the flags are a Win32 CreateFile concept. The
// Linux mapping turns this call into an AF_UNIX connect and ignores
// its flags entirely; a server there learns the peer's credentials
// through SO_PEERCRED and has no way to assume them
#ifdef _WIN32
const DWORD dwOpenFlags = FILE_FLAG_OVERLAPPED
| SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION;
#else
const DWORD dwOpenFlags = FILE_FLAG_OVERLAPPED;
#endif