/
DirectoryServer.cs
847 lines (723 loc) · 34.2 KB
/
DirectoryServer.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace System.DirectoryServices.ActiveDirectory
{
public abstract class DirectoryServer : IDisposable
{
private bool _disposed;
internal DirectoryContext context = null!;
internal string replicaName = null!;
internal DirectoryEntryManager directoryEntryMgr = null!;
// internal variables for the public properties
internal bool siteInfoModified;
internal string? cachedSiteName;
internal string? cachedSiteObjectName;
internal string? cachedServerObjectName;
internal string? cachedNtdsaObjectName;
internal Guid cachedNtdsaObjectGuid = Guid.Empty;
internal ReadOnlyStringCollection? cachedPartitions;
internal const int DS_REPSYNC_ASYNCHRONOUS_OPERATION = 0x00000001;
internal const int DS_REPSYNC_ALL_SOURCES = 0x00000010;
internal const int DS_REPSYNCALL_ID_SERVERS_BY_DN = 0x00000004;
internal const int DS_REPL_NOTSUPPORTED = 50;
private ReplicationConnectionCollection? _inbound;
private ReplicationConnectionCollection? _outbound;
#region constructors
protected DirectoryServer()
{
}
#endregion constructors
#region IDisposable
~DirectoryServer() => Dispose(false);
public void Dispose()
{
Dispose(true);
// Take yourself off of the Finalization queue
// to prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
// private Dispose method
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
// check if this is an explicit Dispose
// only then clean up the directory entries
if (disposing)
{
// dispose all directory entries
foreach (DirectoryEntry entry in directoryEntryMgr.GetCachedDirectoryEntries())
{
entry.Dispose();
}
}
_disposed = true;
}
}
#endregion IDisposable
#region public methods
public override string ToString() => Name;
public void MoveToAnotherSite(string siteName)
{
CheckIfDisposed();
// validate siteName
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
if (siteName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName));
}
// the dc is really being moved to a different site
if (Utils.Compare(SiteName, siteName) != 0)
{
DirectoryEntry? newParentEntry = null;
try
{
// Bind to the target site's server container
// Get the distinguished name for the site
string parentDN = "CN=Servers,CN=" + siteName + "," + directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SitesContainer);
newParentEntry = DirectoryEntryManager.GetDirectoryEntry(context, parentDN);
string serverName = (this is DomainController) ? ((DomainController)this).ServerObjectName : ((AdamInstance)this).ServerObjectName;
DirectoryEntry serverEntry = directoryEntryMgr.GetCachedDirectoryEntry(serverName);
// force binding (needed otherwise S.DS throw an exception while releasing the COM interface pointer)
_ = (string?)PropertyManager.GetPropertyValue(context, serverEntry, PropertyManager.DistinguishedName);
// move the object to the servers container of the target site
serverEntry.MoveTo(newParentEntry);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
newParentEntry?.Dispose();
}
// remove stale cached directory entries
// invalidate the cached properties that get affected by this
siteInfoModified = true;
cachedSiteName = null;
if (cachedSiteObjectName != null)
{
directoryEntryMgr.RemoveIfExists(cachedSiteObjectName);
cachedSiteObjectName = null;
}
if (cachedServerObjectName != null)
{
directoryEntryMgr.RemoveIfExists(cachedServerObjectName);
cachedServerObjectName = null;
}
if (cachedNtdsaObjectName != null)
{
directoryEntryMgr.RemoveIfExists(cachedNtdsaObjectName);
cachedNtdsaObjectName = null;
}
}
}
public DirectoryEntry GetDirectoryEntry()
{
CheckIfDisposed();
string serverName = (this is DomainController) ? ((DomainController)this).ServerObjectName : ((AdamInstance)this).ServerObjectName;
return DirectoryEntryManager.GetDirectoryEntry(context, serverName);
}
#endregion public methods
#region public abstract methods
public abstract void CheckReplicationConsistency();
public abstract ReplicationCursorCollection GetReplicationCursors(string partition);
public abstract ReplicationOperationInformation GetReplicationOperationInformation();
public abstract ReplicationNeighborCollection GetReplicationNeighbors(string partition);
public abstract ReplicationNeighborCollection GetAllReplicationNeighbors();
public abstract ReplicationFailureCollection GetReplicationConnectionFailures();
public abstract ActiveDirectoryReplicationMetadata GetReplicationMetadata(string objectPath);
public abstract void SyncReplicaFromServer(string partition, string sourceServer);
public abstract void TriggerSyncReplicaFromNeighbors(string partition);
public abstract void SyncReplicaFromAllServers(string partition, SyncFromAllServersOptions options);
#endregion public abstract methods
#region public properties
public string Name
{
get
{
CheckIfDisposed();
return replicaName;
}
}
public ReadOnlyStringCollection Partitions
{
get
{
CheckIfDisposed();
return cachedPartitions ??= new ReadOnlyStringCollection(GetPartitions());
}
}
#endregion public properties
#region public abstract properties
public abstract string? IPAddress { get; }
public abstract string SiteName { get; }
public abstract SyncUpdateCallback? SyncFromAllServersCallback { get; set; }
public abstract ReplicationConnectionCollection InboundConnections { get; }
public abstract ReplicationConnectionCollection OutboundConnections { get; }
#endregion public abstract properties
#region private methods
internal ArrayList GetPartitions()
{
ArrayList partitionList = new ArrayList();
DirectoryEntry? rootDSE = null;
DirectoryEntry? serverNtdsaEntry = null;
try
{
// get the writable partitions
rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
// don't need range retrieval for root dse attributes
foreach (string partition in rootDSE.Properties[PropertyManager.NamingContexts])
{
partitionList.Add(partition);
}
// also the read only partitions
string ntdsaName = (this is DomainController) ? ((DomainController)this).NtdsaObjectName : ((AdamInstance)this).NtdsaObjectName;
serverNtdsaEntry = DirectoryEntryManager.GetDirectoryEntry(context, ntdsaName);
// use range retrieval
ArrayList propertyNames = new ArrayList();
propertyNames.Add(PropertyManager.HasPartialReplicaNCs);
Hashtable? values = null;
try
{
values = Utils.GetValuesWithRangeRetrieval(serverNtdsaEntry, null, propertyNames, SearchScope.Base);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
ArrayList readOnlyPartitions = (ArrayList)values[PropertyManager.HasPartialReplicaNCs.ToLowerInvariant()]!;
Debug.Assert(readOnlyPartitions != null);
foreach (string readOnlyPartition in readOnlyPartitions)
{
partitionList.Add(readOnlyPartition);
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
rootDSE?.Dispose();
serverNtdsaEntry?.Dispose();
}
return partitionList;
}
internal void CheckIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
internal DirectoryContext Context => context;
private static readonly string[] s_name = new string[] { "name" };
private static readonly string[] s_cn = new string[] { "cn" };
private static readonly string[] s_objectClassCn = new string[] { "objectClass", "cn" };
internal unsafe void CheckConsistencyHelper(IntPtr dsHandle, SafeLibraryHandle libHandle)
{
// call DsReplicaConsistencyCheck
var replicaConsistencyCheck = (delegate* unmanaged<IntPtr, int, int, int>)global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaConsistencyCheck");
if (replicaConsistencyCheck == null)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastPInvokeError());
}
int result = replicaConsistencyCheck(dsHandle, 0, 0);
if (result != 0)
throw ExceptionHelper.GetExceptionFromErrorCode(result, Name);
}
internal unsafe IntPtr GetReplicationInfoHelper(IntPtr dsHandle, int type, int secondaryType, string? partition, ref bool advanced, int context, SafeLibraryHandle libHandle)
{
IntPtr info = (IntPtr)0;
int result = 0;
bool needToTryAgain = true;
// first try to use the DsReplicaGetInfo2W API which does not exist on win2k machine
// call DsReplicaGetInfo2W
var dsReplicaGetInfo2W = (delegate* unmanaged<IntPtr, int, char*, IntPtr, char*, char*, int, int, IntPtr*, int>)global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfo2W");
if (dsReplicaGetInfo2W == null)
{
// a win2k machine which does not have it.
var dsReplicaGetInfoW = (delegate* unmanaged<IntPtr, int, char*, IntPtr, IntPtr*, int>)global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfoW");
if (dsReplicaGetInfoW == null)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastPInvokeError());
}
fixed (char* partitionPtr = partition)
{
result = dsReplicaGetInfoW(dsHandle, secondaryType, partitionPtr, (IntPtr)0, &info);
}
advanced = false;
needToTryAgain = false;
}
else
{
fixed (char* partitionPtr = partition)
{
result = dsReplicaGetInfo2W(dsHandle, type, partitionPtr, (IntPtr)0, null, null, 0, context, &info);
}
}
// check the result
if (needToTryAgain && result == DS_REPL_NOTSUPPORTED)
{
// this is the case that client is xp/win2k3, dc is win2k
var dsReplicaGetInfoW = (delegate* unmanaged<IntPtr, int, char*, IntPtr, IntPtr*, int>)global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaGetInfoW");
if (dsReplicaGetInfoW == null)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastPInvokeError());
}
fixed (char* partitionPtr = partition)
{
result = dsReplicaGetInfoW(dsHandle, secondaryType, partitionPtr, (IntPtr)0, &info);
}
advanced = false;
}
if (result != 0)
{
if (partition != null)
{
// this is the case of meta data
if (type == (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_METADATA_2_FOR_OBJ)
{
if (result == Interop.Errors.ERROR_DS_DRA_BAD_DN || result == Interop.Errors.ERROR_DS_NAME_UNPARSEABLE)
throw new ArgumentException(ExceptionHelper.GetErrorMessage(result, false), "objectPath");
DirectoryEntry verifyEntry = DirectoryEntryManager.GetDirectoryEntry(this.context, partition);
try
{
verifyEntry.RefreshCache(s_name);
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072020) | // dir_error on server side
e.ErrorCode == unchecked((int)0x80072030)) // object not exists
throw new ArgumentException(SR.DSNoObject, "objectPath");
else if (e.ErrorCode == unchecked((int)0x80005000) | // bad path name
e.ErrorCode == unchecked((int)0x80072032)) // ERROR_DS_INVALID_DN_SYNTAX
throw new ArgumentException(SR.DSInvalidPath, "objectPath");
}
}
else
{
if (!Partitions.Contains(partition))
throw new ArgumentException(SR.ServerNotAReplica, nameof(partition));
}
}
throw ExceptionHelper.GetExceptionFromErrorCode(result, Name);
}
return info;
}
internal ReplicationCursorCollection ConstructReplicationCursors(IntPtr dsHandle, bool advanced, IntPtr info, string partition, DirectoryServer server, SafeLibraryHandle libHandle)
{
int context = 0;
int count = 0;
ReplicationCursorCollection collection = new ReplicationCursorCollection(server);
// construct the collection
if (advanced)
{
// using paging to get all the results
while (true)
{
try
{
if (info != (IntPtr)0)
{
DS_REPL_CURSORS_3 cursors = new DS_REPL_CURSORS_3();
Marshal.PtrToStructure(info, cursors);
count = cursors.cNumCursors;
if (count > 0)
collection.AddHelper(partition, cursors, advanced, info);
context = cursors.dwEnumerationContext;
// we already get all the results or there is no result
if (context == -1 || count == 0)
break;
}
else
{
// should not happen, treat as no result is returned.
break;
}
}
finally
{
FreeReplicaInfo(DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_3_FOR_NC, info, libHandle);
}
// get the next batch of results
info = GetReplicationInfoHelper(dsHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_3_FOR_NC, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_FOR_NC, partition, ref advanced, context, libHandle);
}
}
else
{
try
{
if (info != (IntPtr)0)
{
// structure of DS_REPL_CURSORS_3 and DS_REPL_CURSORS actually are the same
DS_REPL_CURSORS cursors = new DS_REPL_CURSORS();
Marshal.PtrToStructure(info, cursors);
collection.AddHelper(partition, cursors, advanced, info);
}
}
finally
{
FreeReplicaInfo(DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_FOR_NC, info, libHandle);
}
}
return collection;
}
internal ReplicationOperationInformation ConstructPendingOperations(IntPtr info, DirectoryServer server, SafeLibraryHandle libHandle)
{
ReplicationOperationInformation replicationInfo = new ReplicationOperationInformation();
ReplicationOperationCollection collection = new ReplicationOperationCollection(server);
replicationInfo.collection = collection;
int count = 0;
try
{
if (info != (IntPtr)0)
{
DS_REPL_PENDING_OPS operations = new DS_REPL_PENDING_OPS();
Marshal.PtrToStructure(info, operations);
count = operations.cNumPendingOps;
if (count > 0)
{
collection.AddHelper(operations, info);
replicationInfo.startTime = DateTime.FromFileTime(operations.ftimeCurrentOpStarted);
replicationInfo.currentOp = collection.GetFirstOperation();
}
}
}
finally
{
FreeReplicaInfo(DS_REPL_INFO_TYPE.DS_REPL_INFO_PENDING_OPS, info, libHandle);
}
return replicationInfo;
}
internal ReplicationNeighborCollection ConstructNeighbors(IntPtr info, DirectoryServer server, SafeLibraryHandle libHandle)
{
ReplicationNeighborCollection collection = new ReplicationNeighborCollection(server);
int count = 0;
try
{
if (info != (IntPtr)0)
{
DS_REPL_NEIGHBORS neighbors = new DS_REPL_NEIGHBORS();
Marshal.PtrToStructure(info, neighbors);
Debug.Assert(neighbors != null);
count = neighbors.cNumNeighbors;
if (count > 0)
collection.AddHelper(neighbors, info);
}
}
finally
{
FreeReplicaInfo(DS_REPL_INFO_TYPE.DS_REPL_INFO_NEIGHBORS, info, libHandle);
}
return collection;
}
internal ReplicationFailureCollection ConstructFailures(IntPtr info, DirectoryServer server, SafeLibraryHandle libHandle)
{
ReplicationFailureCollection collection = new ReplicationFailureCollection(server);
int count = 0;
try
{
if (info != (IntPtr)0)
{
DS_REPL_KCC_DSA_FAILURES failures = new DS_REPL_KCC_DSA_FAILURES();
Marshal.PtrToStructure(info, failures);
count = failures.cNumEntries;
if (count > 0)
collection.AddHelper(failures, info);
}
}
finally
{
FreeReplicaInfo(DS_REPL_INFO_TYPE.DS_REPL_INFO_KCC_DSA_CONNECT_FAILURES, info, libHandle);
}
return collection;
}
internal ActiveDirectoryReplicationMetadata ConstructMetaData(bool advanced, IntPtr info, DirectoryServer server, SafeLibraryHandle libHandle)
{
ActiveDirectoryReplicationMetadata collection = new ActiveDirectoryReplicationMetadata(server);
int count = 0;
if (advanced)
{
try
{
if (info != (IntPtr)0)
{
DS_REPL_OBJ_META_DATA_2 objMetaData = new DS_REPL_OBJ_META_DATA_2();
Marshal.PtrToStructure(info, objMetaData);
count = objMetaData.cNumEntries;
if (count > 0)
{
collection.AddHelper(count, info, true);
}
}
}
finally
{
FreeReplicaInfo(DS_REPL_INFO_TYPE.DS_REPL_INFO_METADATA_2_FOR_OBJ, info, libHandle);
}
}
else
{
try
{
DS_REPL_OBJ_META_DATA objMetadata = new DS_REPL_OBJ_META_DATA();
Marshal.PtrToStructure(info, objMetadata);
count = objMetadata.cNumEntries;
if (count > 0)
{
collection.AddHelper(count, info, false);
}
}
finally
{
FreeReplicaInfo(DS_REPL_INFO_TYPE.DS_REPL_INFO_METADATA_FOR_OBJ, info, libHandle);
}
}
return collection;
}
internal bool SyncAllCallbackRoutine(IntPtr data, IntPtr update)
{
if (SyncFromAllServersCallback == null)
{
// user does not specify callback, resume the DsReplicaSyncAll execution
return true;
}
else
{
// user specifies callback
// our callback is invoked, update should not be NULL, do assertion here
Debug.Assert(update != (IntPtr)0);
DS_REPSYNCALL_UPDATE syncAllUpdate = new DS_REPSYNCALL_UPDATE();
Marshal.PtrToStructure(update, syncAllUpdate);
// get the event type
SyncFromAllServersEvent eventType = syncAllUpdate.eventType;
// get the error information
IntPtr temp = syncAllUpdate.pErrInfo;
SyncFromAllServersOperationException? exception = null;
if (temp != (IntPtr)0)
{
// error information is available
exception = ExceptionHelper.CreateSyncAllException(temp, true);
if (exception == null)
{
// this is the special case that we ignore the failure when SyncAllOptions.CheckServerAlivenessOnly is specified
return true;
}
}
string? targetName = null;
string? sourceName = null;
temp = syncAllUpdate.pSync;
if (temp != (IntPtr)0)
{
DS_REPSYNCALL_SYNC sync = new DS_REPSYNCALL_SYNC();
Marshal.PtrToStructure(temp, sync);
targetName = Marshal.PtrToStringUni(sync.pszDstId);
sourceName = Marshal.PtrToStringUni(sync.pszSrcId);
}
// invoke the client callback
SyncUpdateCallback clientCallback = SyncFromAllServersCallback;
return clientCallback(eventType, targetName, sourceName, exception);
}
}
internal unsafe void SyncReplicaAllHelper(IntPtr handle, SyncReplicaFromAllServersCallback syncAllCallback, string partition, SyncFromAllServersOptions option, SyncUpdateCallback? callback, SafeLibraryHandle libHandle)
{
void* pErrors = null;
if (!Partitions.Contains(partition))
throw new ArgumentException(SR.ServerNotAReplica, nameof(partition));
// we want to return the dn instead of DNS guid
// call DsReplicaSyncAllW
var dsReplicaSyncAllW = (delegate* unmanaged<IntPtr, char*, int, IntPtr, IntPtr, void**, int>)global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaSyncAllW");
if (dsReplicaSyncAllW == null)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastPInvokeError());
}
int result;
fixed (char* partitionPtr = partition)
{
IntPtr syncAllFunctionPointer = Marshal.GetFunctionPointerForDelegate(syncAllCallback);
result = dsReplicaSyncAllW(handle, partitionPtr, (int)option | DS_REPSYNCALL_ID_SERVERS_BY_DN, syncAllFunctionPointer, (IntPtr)0, &pErrors);
GC.KeepAlive(syncAllCallback);
}
try
{
// error happens during the synchronization
if (pErrors is not null)
{
SyncFromAllServersOperationException? e = ExceptionHelper.CreateSyncAllException((IntPtr)pErrors, false);
if (e == null)
return;
else
throw e;
}
else
{
// API does not return error infor occurred during synchronization, but result is not success.
if (result != 0)
throw new SyncFromAllServersOperationException(ExceptionHelper.GetErrorMessage(result, false));
}
}
finally
{
// release the memory
if (pErrors is not null)
global::Interop.Kernel32.LocalFree(pErrors);
}
}
private unsafe void FreeReplicaInfo(DS_REPL_INFO_TYPE type, IntPtr value, SafeLibraryHandle libHandle)
{
if (value != (IntPtr)0)
{
// call DsReplicaFreeInfo
var dsReplicaFreeInfo = (delegate* unmanaged<int, IntPtr, int>)global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaFreeInfo");
if (dsReplicaFreeInfo == null)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastPInvokeError());
}
dsReplicaFreeInfo((int)type, value);
}
}
internal unsafe void SyncReplicaHelper(IntPtr dsHandle, bool isADAM, string partition, string? sourceServer, int option, SafeLibraryHandle libHandle)
{
int structSize = Marshal.SizeOf(typeof(Guid));
IntPtr unmanagedGuid = (IntPtr)0;
Guid guid = Guid.Empty;
AdamInstance? adamServer = null;
DomainController? dcServer = null;
unmanagedGuid = Marshal.AllocHGlobal(structSize);
try
{
if (sourceServer != null)
{
DirectoryContext newContext = Utils.GetNewDirectoryContext(sourceServer, DirectoryContextType.DirectoryServer, context);
if (isADAM)
{
adamServer = AdamInstance.GetAdamInstance(newContext);
guid = adamServer.NtdsaObjectGuid;
}
else
{
dcServer = DomainController.GetDomainController(newContext);
guid = dcServer.NtdsaObjectGuid;
}
Marshal.StructureToPtr(guid, unmanagedGuid, false);
}
// call DsReplicaSyncW
var dsReplicaSyncW = (delegate* unmanaged<IntPtr, char*, IntPtr, int, int>)global::Interop.Kernel32.GetProcAddress(libHandle, "DsReplicaSyncW");
if (dsReplicaSyncW == null)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastPInvokeError());
}
fixed (char* partitionPtr = partition)
{
int result = dsReplicaSyncW(dsHandle, partitionPtr, unmanagedGuid, (int)option);
// check the result
if (result != 0)
{
if (!Partitions.Contains(partition))
throw new ArgumentException(SR.ServerNotAReplica, nameof(partition));
string? serverDownName = null;
// this is the error returned when the server that we want to sync from is down
if (result == Interop.Errors.RPC_S_SERVER_UNAVAILABLE)
serverDownName = sourceServer;
// this is the error returned when the server that we want to get synced is down
else if (result == Interop.Errors.RPC_S_CALL_FAILED)
serverDownName = Name;
throw ExceptionHelper.GetExceptionFromErrorCode(result, serverDownName);
}
}
}
finally
{
if (unmanagedGuid != (IntPtr)0)
Marshal.FreeHGlobal(unmanagedGuid);
adamServer?.Dispose();
dcServer?.Dispose();
}
}
internal ReplicationConnectionCollection GetInboundConnectionsHelper()
{
if (_inbound == null)
{
// construct the replicationconnection collection
_inbound = new ReplicationConnectionCollection();
DirectoryContext newContext = Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context);
// this is the first time that user tries to retrieve this property, so get it from the directory
string serverName = (this is DomainController) ? ((DomainController)this).ServerObjectName : ((AdamInstance)this).ServerObjectName;
string srchDN = "CN=NTDS Settings," + serverName;
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context), srchDN);
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=nTDSConnection)(objectCategory=nTDSConnection))",
s_cn,
SearchScope.OneLevel);
SearchResultCollection? srchResults = null;
try
{
srchResults = adSearcher.FindAll();
foreach (SearchResult r in srchResults)
{
ReplicationConnection con = new ReplicationConnection(newContext, r.GetDirectoryEntry(), (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.Cn)!);
_inbound.Add(con);
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(newContext, e);
}
finally
{
srchResults?.Dispose();
de.Dispose();
}
}
return _inbound;
}
internal ReplicationConnectionCollection GetOutboundConnectionsHelper()
{
// this is the first time that user tries to retrieve this property, so get it from the directory
if (_outbound == null)
{
// search base is the site container
string siteName = (this is DomainController) ? ((DomainController)this).SiteObjectName : ((AdamInstance)this).SiteObjectName;
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context), siteName);
string serverName = (this is DomainController) ? ((DomainController)this).ServerObjectName : ((AdamInstance)this).ServerObjectName;
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=nTDSConnection)(objectCategory=nTDSConnection)(fromServer=CN=NTDS Settings," + serverName + "))",
s_objectClassCn,
SearchScope.Subtree);
SearchResultCollection? results = null;
DirectoryContext newContext = Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context);
try
{
results = adSearcher.FindAll();
_outbound = new ReplicationConnectionCollection();
foreach (SearchResult result in results)
{
ReplicationConnection con = new ReplicationConnection(newContext, result.GetDirectoryEntry(), (string)result.Properties["cn"][0]!);
_outbound.Add(con);
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(newContext, e);
}
finally
{
results?.Dispose();
de.Dispose();
}
}
return _outbound;
}
#endregion private methods
}
}