-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
FileSystemProvider.cs
10037 lines (8775 loc) · 396 KB
/
FileSystemProvider.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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Provider;
using System.Management.Automation.Runspaces;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Microsoft.Win32.SafeHandles;
using Dbg = System.Management.Automation;
namespace Microsoft.PowerShell.Commands
{
#region FileSystemProvider
/// <summary>
/// Defines the implementation of a File System Provider. This provider
/// allows for stateless namespace navigation of the file system.
/// </summary>
[CmdletProvider(FileSystemProvider.ProviderName, ProviderCapabilities.Credentials | ProviderCapabilities.Filter | ProviderCapabilities.ShouldProcess)]
[OutputType(typeof(FileSecurity), ProviderCmdlet = ProviderCmdlet.SetAcl)]
[OutputType(typeof(string), typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.ResolvePath)]
[OutputType(typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.PushLocation)]
[OutputType(typeof(byte), typeof(string), ProviderCmdlet = ProviderCmdlet.GetContent)]
[OutputType(typeof(FileInfo), ProviderCmdlet = ProviderCmdlet.GetItem)]
[OutputType(typeof(FileInfo), typeof(DirectoryInfo), ProviderCmdlet = ProviderCmdlet.GetChildItem)]
[OutputType(typeof(FileSecurity), typeof(DirectorySecurity), ProviderCmdlet = ProviderCmdlet.GetAcl)]
[OutputType(typeof(bool), typeof(string), typeof(FileInfo), typeof(DirectoryInfo), ProviderCmdlet = ProviderCmdlet.GetItem)]
[OutputType(typeof(bool), typeof(string), typeof(DateTime), typeof(System.IO.FileInfo), typeof(System.IO.DirectoryInfo), ProviderCmdlet = ProviderCmdlet.GetItemProperty)]
[OutputType(typeof(string), typeof(System.IO.FileInfo), ProviderCmdlet = ProviderCmdlet.NewItem)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This coupling is required")]
public sealed partial class FileSystemProvider : NavigationCmdletProvider,
IContentCmdletProvider,
IPropertyCmdletProvider,
ISecurityDescriptorCmdletProvider,
ICmdletProviderSupportsHelp
{
// 4MB gives the best results without spiking the resources on the remote connection for file transfers between pssessions.
// NOTE: The script used to copy file data from session (PSCopyFromSessionHelper) has a
// maximum fragment size value for security. If FILETRANSFERSIZE changes make sure the
// copy script will accomodate the new value.
private const int FILETRANSFERSIZE = 4 * 1024 * 1024;
// The name of the key in an exception's Data dictionary when attempting
// to copy an item onto itself.
private const string SelfCopyDataKey = "SelfCopy";
/// <summary>
/// An instance of the PSTraceSource class used for trace output
/// using "FileSystemProvider" as the category.
/// </summary>
[Dbg.TraceSourceAttribute("FileSystemProvider", "The namespace navigation provider for the file system")]
private static readonly Dbg.PSTraceSource s_tracer =
Dbg.PSTraceSource.GetTracer("FileSystemProvider", "The namespace navigation provider for the file system");
/// <summary>
/// Gets the name of the provider.
/// </summary>
public const string ProviderName = "FileSystem";
/// <summary>
/// Initializes a new instance of the FileSystemProvider class. Since this
/// object needs to be stateless, the constructor does nothing.
/// </summary>
public FileSystemProvider()
{
}
private Collection<WildcardPattern> _excludeMatcher = null;
private static readonly System.IO.EnumerationOptions _enumerationOptions = new System.IO.EnumerationOptions
{
MatchType = MatchType.Win32,
MatchCasing = MatchCasing.CaseInsensitive,
AttributesToSkip = 0 // Default is to skip Hidden and System files, so we clear this to retain existing behavior
};
/// <summary>
/// Converts all / in the path to \
/// </summary>
/// <param name="path">
/// The path to normalize.
/// </param>
/// <returns>
/// The path with all / normalized to \
/// </returns>
private static string NormalizePath(string path)
{
return GetCorrectCasedPath(path.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator));
}
/// <summary>
/// Get the correct casing for a path. This method assumes it's being called by NormalizePath()
/// so that the path is already normalized.
/// </summary>
/// <param name="path">
/// The path to retrieve.
/// </param>
/// <returns>
/// The path with accurate casing if item exists, otherwise it returns path that was passed in.
/// </returns>
private static string GetCorrectCasedPath(string path)
{
// Only apply to directories where there are issues with some tools if the casing
// doesn't match the source like git
if (Directory.Exists(path))
{
string exactPath = string.Empty;
int itemsToSkip = 0;
if (Utils.PathIsUnc(path))
{
// With the Split method, a UNC path like \\server\share, we need to skip
// trying to enumerate the server and share, so skip the first two empty
// strings, then server, and finally share name.
itemsToSkip = 4;
}
foreach (string item in path.Split(StringLiterals.DefaultPathSeparator))
{
if (itemsToSkip-- > 0)
{
// This handles the UNC server and share and 8.3 short path syntax
exactPath += item + StringLiterals.DefaultPathSeparator;
continue;
}
else if (string.IsNullOrEmpty(exactPath))
{
// This handles the drive letter or / root path start
exactPath = item + StringLiterals.DefaultPathSeparator;
}
else if (string.IsNullOrEmpty(item))
{
// This handles the trailing slash case
if (!exactPath.EndsWith(StringLiterals.DefaultPathSeparator))
{
exactPath += StringLiterals.DefaultPathSeparator;
}
break;
}
else if (item.Contains('~'))
{
// This handles short path names
exactPath += StringLiterals.DefaultPathSeparator + item;
}
else
{
// Use GetFileSystemEntries to get the correct casing of this element
try
{
var entries = Directory.GetFileSystemEntries(exactPath, item);
if (entries.Length > 0)
{
exactPath = entries[0];
}
else
{
// If previous call didn't return anything, something failed so we just return the path we were given
return path;
}
}
catch
{
// If we can't enumerate, we stop and just return the original path
return path;
}
}
}
return exactPath;
}
else
{
return path;
}
}
/// <summary>
/// Checks if the item exist at the specified path. if it exists then creates
/// appropriate directoryinfo or fileinfo object.
/// </summary>
/// <param name="path">
/// Refers to the item for which we are checking for existence and creating filesysteminfo object.
/// </param>
/// <param name="isContainer">
/// Return true if path points to a directory else returns false.
/// </param>
/// <returns>FileInfo or DirectoryInfo object.</returns>
/// <exception cref="System.ArgumentNullException">
/// The path is null.
/// </exception>
/// <exception cref="System.IO.IOException">
/// I/O error occurs.
/// </exception>
/// <exception cref="System.UnauthorizedAccessException">
/// An I/O error or a specific type of security error.
/// </exception>
private static FileSystemInfo GetFileSystemInfo(string path, out bool isContainer)
{
// We use 'FileInfo.Attributes' (not 'FileInfo.Exist')
// because we want to get exceptions
// like UnauthorizedAccessException or IOException.
FileSystemInfo fsinfo = new FileInfo(path);
var attr = fsinfo.Attributes;
var exists = (int)attr != -1;
isContainer = exists && attr.HasFlag(FileAttributes.Directory);
if (exists)
{
if (isContainer)
{
return new DirectoryInfo(path);
}
else
{
return fsinfo;
}
}
return null;
}
/// <summary>
/// Overrides the method of CmdletProvider, considering the additional
/// dynamic parameters of FileSystemProvider.
/// </summary>
/// <returns>
/// whether the filter or attribute filter is set.
/// </returns>
internal override bool IsFilterSet()
{
bool attributeFilterSet = false;
GetChildDynamicParameters fspDynamicParam = DynamicParameters as GetChildDynamicParameters;
if (fspDynamicParam != null)
{
attributeFilterSet = (
(fspDynamicParam.Attributes != null)
|| (fspDynamicParam.Directory)
|| (fspDynamicParam.File)
|| (fspDynamicParam.Hidden)
|| (fspDynamicParam.ReadOnly)
|| (fspDynamicParam.System));
}
return (attributeFilterSet || base.IsFilterSet());
}
/// <summary>
/// Gets the dynamic parameters for get-childnames on the
/// FileSystemProvider.
/// We currently only support one dynamic parameter,
/// "Attributes" that returns an enum evaluator for the
/// given expression.
/// </summary>
/// <param name="path">
/// If the path was specified on the command line, this is the path
/// to the item for which to get the dynamic parameters.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
protected override object GetChildNamesDynamicParameters(string path)
{
return new GetChildDynamicParameters();
}
/// <summary>
/// Gets the dynamic parameters for get-childitems on the
/// FileSystemProvider.
/// We currently only support one dynamic parameter,
/// "Attributes" that returns an enum evaluator for the
/// given expression.
/// </summary>
/// <param name="path">
/// If the path was specified on the command line, this is the path
/// to the item for which to get the dynamic parameters.
/// </param>
/// <param name="recurse">
/// Ignored.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
protected override object GetChildItemsDynamicParameters(string path, bool recurse)
{
return new GetChildDynamicParameters();
}
/// <summary>
/// Gets the dynamic parameters for Copy-Item on the FileSystemProvider.
/// </summary>
/// <param name="path">Source for the copy operation.</param>
/// <param name="destination">Destination for the copy operation.</param>
/// <param name="recurse">Whether to recurse.</param>
/// <returns></returns>
protected override object CopyItemDynamicParameters(string path, string destination, bool recurse)
{
return new CopyItemDynamicParameters();
}
#region ICmdletProviderSupportsHelp members
/// <summary>
/// Implementation of ICmdletProviderSupportsHelp interface.
/// Gets provider-specific help content for the corresponding cmdlet.
/// </summary>
/// <param name="helpItemName">
/// Name of command that the help is requested for.
/// </param>
/// <param name="path">
/// Not used here.
/// </param>
/// <returns>
/// The MAML help XML that should be presented to the user.
/// </returns>
public string GetHelpMaml(string helpItemName, string path)
{
// Get the verb and noun from helpItemName
//
string verb = null;
string noun = null;
XmlReader reader = null;
try
{
if (!string.IsNullOrEmpty(helpItemName))
{
CmdletInfo.SplitCmdletName(helpItemName, out verb, out noun);
}
else
{
return string.Empty;
}
if (string.IsNullOrEmpty(verb) || string.IsNullOrEmpty(noun))
{
return string.Empty;
}
// Load the help file from the current UI culture subfolder
XmlDocument document = new XmlDocument();
CultureInfo currentUICulture = CultureInfo.CurrentUICulture;
string fullHelpPath = Path.Combine(
string.IsNullOrEmpty(this.ProviderInfo.ApplicationBase) ? string.Empty : this.ProviderInfo.ApplicationBase,
currentUICulture.ToString(),
string.IsNullOrEmpty(this.ProviderInfo.HelpFile) ? string.Empty : this.ProviderInfo.HelpFile);
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = null;
reader = XmlReader.Create(fullHelpPath, settings);
document.Load(reader);
// Add "msh" and "command" namespaces from the MAML schema
XmlNamespaceManager nsMgr = new XmlNamespaceManager(document.NameTable);
nsMgr.AddNamespace("msh", HelpCommentsParser.mshURI);
nsMgr.AddNamespace("command", HelpCommentsParser.commandURI);
// Compose XPath query to select the appropriate node based on the cmdlet
string xpathQuery = string.Format(
CultureInfo.InvariantCulture,
HelpCommentsParser.ProviderHelpCommandXPath,
"[@id='FileSystem']",
verb,
noun);
// Execute the XPath query and return its MAML snippet
XmlNode result = document.SelectSingleNode(xpathQuery, nsMgr);
if (result != null)
{
return result.OuterXml;
}
}
catch (XmlException)
{
return string.Empty;
}
catch (PathTooLongException)
{
return string.Empty;
}
catch (IOException)
{
return string.Empty;
}
catch (UnauthorizedAccessException)
{
return string.Empty;
}
catch (NotSupportedException)
{
return string.Empty;
}
catch (SecurityException)
{
return string.Empty;
}
catch (XPathException)
{
return string.Empty;
}
finally
{
if (reader != null)
{
((IDisposable)reader).Dispose();
}
}
return string.Empty;
}
#endregion
#region CmdletProvider members
/// <summary>
/// Starts the File System provider. This method sets the Home for the
/// provider to providerInfo.Home if specified, and %USERPROFILE%
/// otherwise.
/// </summary>
/// <param name="providerInfo">
/// The ProviderInfo object that holds the provider's configuration.
/// </param>
/// <returns>
/// The updated ProviderInfo object that holds the provider's configuration.
/// </returns>
protected override ProviderInfo Start(ProviderInfo providerInfo)
{
// Set the home folder for the user
if (providerInfo != null && string.IsNullOrEmpty(providerInfo.Home))
{
// %USERPROFILE% - indicate where a user's home directory is located in the file system.
string homeDirectory = Environment.GetEnvironmentVariable(Platform.CommonEnvVariableNames.Home);
if (!string.IsNullOrEmpty(homeDirectory))
{
if (Directory.Exists(homeDirectory))
{
s_tracer.WriteLine("Home = {0}", homeDirectory);
providerInfo.Home = homeDirectory;
}
else
{
s_tracer.WriteLine("Not setting home directory {0} - does not exist", homeDirectory);
}
}
}
// OneDrive placeholder support (issue #8315)
// make it so OneDrive placeholders are perceived as such with *all* their attributes accessible
#if !UNIX
// The placeholder mode management APIs Rtl(Set|Query)(Process|Thread)PlaceholderCompatibilityMode
// are only supported starting with Windows 10 version 1803 (build 17134)
Version minBuildForPlaceHolderAPIs = new Version(10, 0, 17134, 0);
if (Environment.OSVersion.Version >= minBuildForPlaceHolderAPIs)
{
// let's be safe, don't change the PlaceHolderCompatibilityMode if the current one is not what we expect
if (NativeMethods.RtlQueryProcessPlaceholderCompatibilityMode() == NativeMethods.PHCM_DISGUISE_PLACEHOLDER)
{
NativeMethods.RtlSetProcessPlaceholderCompatibilityMode(NativeMethods.PHCM_EXPOSE_PLACEHOLDERS);
}
}
#endif
return providerInfo;
}
#endregion CmdletProvider members
#region DriveCmdletProvider members
/// <summary>
/// Determines if the specified drive can be mounted.
/// </summary>
/// <param name="drive">
/// The drive that is going to be mounted.
/// </param>
/// <returns>
/// The same drive that was passed in, if the drive can be mounted.
/// null if the drive cannot be mounted.
/// </returns>
/// <exception cref="System.ArgumentNullException">
/// drive is null.
/// </exception>
/// <exception cref="System.ArgumentException">
/// drive root is null or empty.
/// </exception>
protected override PSDriveInfo NewDrive(PSDriveInfo drive)
{
// verify parameters
if (drive == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(drive));
}
if (string.IsNullOrEmpty(drive.Root))
{
throw PSTraceSource.NewArgumentException("drive.Root");
}
// -Persist switch parameter is supported only for Network paths.
if (drive.Persist && !PathIsNetworkPath(drive.Root))
{
ErrorRecord er = new ErrorRecord(new NotSupportedException(FileSystemProviderStrings.PersistNotSupported), "DriveRootNotNetworkPath", ErrorCategory.InvalidArgument, drive);
ThrowTerminatingError(er);
}
if (IsNetworkMappedDrive(drive))
{
// MapNetworkDrive facilitates to map the newly
// created PS Drive to a network share.
this.MapNetworkDrive(drive);
}
// The drive is valid if the item exists or the
// drive is not a fixed drive. We want to allow
// a drive to exist for floppies and other such\
// removable media, even if the media isn't in place.
bool driveIsFixed = true;
PSDriveInfo result = null;
try
{
// See if the drive is a fixed drive.
string pathRoot = Path.GetPathRoot(drive.Root);
DriveInfo driveInfo = new DriveInfo(pathRoot);
if (driveInfo.DriveType != DriveType.Fixed)
{
driveIsFixed = false;
}
// The current drive is a network drive.
if (driveInfo.DriveType == DriveType.Network)
{
drive.IsNetworkDrive = true;
}
}
catch (ArgumentException) // swallow ArgumentException incl. ArgumentNullException
{
}
bool validDrive = true;
if (driveIsFixed)
{
// Since the drive is fixed, ensure the root is valid.
validDrive = Directory.Exists(drive.Root);
}
if (validDrive)
{
result = drive;
}
else
{
string error = StringUtil.Format(FileSystemProviderStrings.DriveRootError, drive.Root);
Exception e = new IOException(error);
WriteError(new ErrorRecord(e, "DriveRootError", ErrorCategory.ReadError, drive));
}
drive.Trace();
return result;
}
/// <summary>
/// MapNetworkDrive facilitates to map the newly created PS Drive to a network share.
/// </summary>
/// <param name="drive">The PSDrive info that would be used to create a new PS drive.</param>
private void MapNetworkDrive(PSDriveInfo drive)
{
// Porting note: mapped network drives are only supported on Windows
if (Platform.IsWindows)
{
WinMapNetworkDrive(drive);
}
else
{
throw new PlatformNotSupportedException();
}
}
private static bool _WNetApiAvailable = true;
private void WinMapNetworkDrive(PSDriveInfo drive)
{
if (drive != null && !string.IsNullOrEmpty(drive.Root))
{
const int CONNECT_UPDATE_PROFILE = 0x00000001;
const int CONNECT_NOPERSIST = 0x00000000;
const int RESOURCE_GLOBALNET = 0x00000002;
const int RESOURCETYPE_ANY = 0x00000000;
const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000;
const int RESOURCEUSAGE_CONNECTABLE = 0x00000001;
const int ERROR_NO_NETWORK = 1222;
// By default the connection is not persisted.
int CONNECT_TYPE = CONNECT_NOPERSIST;
string driveName = null;
byte[] passwd = null;
string userName = null;
if (drive.Persist)
{
if (IsSupportedDriveForPersistence(drive))
{
CONNECT_TYPE = CONNECT_UPDATE_PROFILE;
driveName = drive.Name + ":";
drive.DisplayRoot = drive.Root;
}
else
{
// error.
ErrorRecord er = new ErrorRecord(new InvalidOperationException(FileSystemProviderStrings.InvalidDriveName), "DriveNameNotSupportedForPersistence", ErrorCategory.InvalidOperation, drive);
ThrowTerminatingError(er);
}
}
// If alternate credentials is supplied then use them to get connected to network share.
if (drive.Credential != null && !drive.Credential.Equals(PSCredential.Empty))
{
userName = drive.Credential.UserName;
passwd = SecureStringHelper.GetData(drive.Credential.Password);
}
try
{
NetResource resource = new NetResource();
resource.Comment = null;
resource.DisplayType = RESOURCEDISPLAYTYPE_GENERIC;
resource.LocalName = driveName;
resource.Provider = null;
resource.RemoteName = drive.Root;
resource.Scope = RESOURCE_GLOBALNET;
resource.Type = RESOURCETYPE_ANY;
resource.Usage = RESOURCEUSAGE_CONNECTABLE;
int code = ERROR_NO_NETWORK;
if (_WNetApiAvailable)
{
try
{
code = NativeMethods.WNetAddConnection2(ref resource, passwd, userName, CONNECT_TYPE);
}
catch (System.DllNotFoundException)
{
_WNetApiAvailable = false;
}
}
if (code != 0)
{
ErrorRecord er = new ErrorRecord(new System.ComponentModel.Win32Exception(code), "CouldNotMapNetworkDrive", ErrorCategory.InvalidOperation, drive);
ThrowTerminatingError(er);
}
if (CONNECT_TYPE == CONNECT_UPDATE_PROFILE)
{
// Update the current PSDrive to be a persisted drive.
drive.IsNetworkDrive = true;
// PsDrive.Root is updated to the name of the Drive for
// drives targeting network path and being persisted.
drive.Root = driveName + @"\";
}
}
finally
{
// Clear the password in the memory.
if (passwd != null)
{
Array.Clear(passwd, 0, passwd.Length - 1);
}
}
}
}
/// <summary>
/// ShouldMapNetworkDrive is a helper function used to detect if the
/// requested PSDrive to be created has to be mapped to a network drive.
/// </summary>
/// <param name="drive"></param>
/// <returns></returns>
private static bool IsNetworkMappedDrive(PSDriveInfo drive)
{
bool shouldMapNetworkDrive = (drive != null && !string.IsNullOrEmpty(drive.Root) && PathIsNetworkPath(drive.Root)) &&
(drive.Persist || (drive.Credential != null && !drive.Credential.Equals(PSCredential.Empty)));
return shouldMapNetworkDrive;
}
/// <summary>
/// RemoveDrive facilitates to remove network mapped persisted PSDrvie.
/// </summary>
/// <param name="drive">
/// PSDrive info.
/// </param>
/// <returns>PSDrive info.
/// </returns>
protected override PSDriveInfo RemoveDrive(PSDriveInfo drive)
{
#if UNIX
return drive;
#else
return WinRemoveDrive(drive);
#endif
}
private PSDriveInfo WinRemoveDrive(PSDriveInfo drive)
{
if (IsNetworkMappedDrive(drive))
{
const int CONNECT_UPDATE_PROFILE = 0x00000001;
const int ERROR_NO_NETWORK = 1222;
int flags = 0;
string driveName;
if (drive.IsNetworkDrive)
{
// Here we are removing only persisted network drives.
flags = CONNECT_UPDATE_PROFILE;
driveName = drive.Name + ":";
}
else
{
// OSGTFS: 608188 PSDrive leaves a connection open after the drive is removed
// if a drive is not persisted or networkdrive, we need to use the actual root to remove the drive.
driveName = drive.Root;
}
// You need to actually remove the drive.
int code = ERROR_NO_NETWORK;
if (_WNetApiAvailable)
{
try
{
code = NativeMethods.WNetCancelConnection2(driveName, flags, true);
}
catch (System.DllNotFoundException)
{
_WNetApiAvailable = false;
}
}
if (code != 0)
{
ErrorRecord er = new ErrorRecord(new System.ComponentModel.Win32Exception(code), "CouldRemoveNetworkDrive", ErrorCategory.InvalidOperation, drive);
ThrowTerminatingError(er);
}
}
return drive;
}
/// <summary>
/// IsSupportedDriveForPersistence is a helper method used to
/// check if the psdrive can be persisted or not.
/// </summary>
/// <param name="drive">
/// PS Drive Info.
/// </param>
/// <returns>True if the drive can be persisted or else false.</returns>
private static bool IsSupportedDriveForPersistence(PSDriveInfo drive)
{
bool isSupportedDriveForPersistence = false;
if (drive != null && !string.IsNullOrEmpty(drive.Name) && drive.Name.Length == 1)
{
char driveChar = Convert.ToChar(drive.Name, CultureInfo.InvariantCulture);
if (char.ToUpperInvariant(driveChar) >= 'A' && char.ToUpperInvariant(driveChar) <= 'Z')
{
isSupportedDriveForPersistence = true;
}
}
return isSupportedDriveForPersistence;
}
/// <summary>
/// Return the UNC path for a given network drive
/// using the Windows API.
/// </summary>
/// <param name="driveName"></param>
/// <returns></returns>
internal static string GetUNCForNetworkDrive(string driveName)
{
#if UNIX
return driveName;
#else
return WinGetUNCForNetworkDrive(driveName);
#endif
}
private static string WinGetUNCForNetworkDrive(string driveName)
{
const int ERROR_NO_NETWORK = 1222;
string uncPath = null;
if (!string.IsNullOrEmpty(driveName) && driveName.Length == 1)
{
// By default buffer size is set to 300 which would generally be sufficient in most of the cases.
int bufferSize = 300;
#if DEBUG
// In Debug mode buffer size is initially set to 3 and if additional buffer is required, the
// required buffer size is allocated and the WNetGetConnection API is executed with the newly
// allocated buffer size.
bufferSize = 3;
#endif
StringBuilder uncBuffer = new StringBuilder(bufferSize);
driveName += ':';
// Call the windows API
int errorCode = ERROR_NO_NETWORK;
try
{
errorCode = NativeMethods.WNetGetConnection(driveName, uncBuffer, ref bufferSize);
}
catch (System.DllNotFoundException)
{
return null;
}
// error code 234 is returned whenever the required buffer size is greater
// than the specified buffer size.
if (errorCode == 234)
{
uncBuffer = new StringBuilder(bufferSize);
errorCode = NativeMethods.WNetGetConnection(driveName, uncBuffer, ref bufferSize);
}
if (errorCode != 0)
{
throw new System.ComponentModel.Win32Exception(errorCode);
}
uncPath = uncBuffer.ToString();
}
return uncPath;
}
/// <summary>
/// Get the substituted path of a NetWork type MS-DOS device that is created by 'subst' command.
/// When a MS-DOS device is of NetWork type, it could be:
/// 1. Substitute a path in a drive that maps to a network location. For example:
/// net use z: \\scratch2\scratch\
/// subst y: z:\abc\
/// 2. Substitute a network location directly. For example:
/// subst y: \\scratch2\scratch\
/// </summary>
/// <param name="driveName"></param>
/// <returns></returns>
internal static string GetSubstitutedPathForNetworkDosDevice(string driveName)
{
#if UNIX
throw new PlatformNotSupportedException();
#else
return WinGetSubstitutedPathForNetworkDosDevice(driveName);
#endif
}
private static string WinGetSubstitutedPathForNetworkDosDevice(string driveName)
{
string associatedPath = null;
if (!string.IsNullOrEmpty(driveName) && driveName.Length == 1)
{
// By default buffer size is set to 300 which would generally be sufficient in most of the cases.
int bufferSize = 300;
var pathInfo = new StringBuilder(bufferSize);
driveName += ':';
// Call the windows API
while (true)
{
pathInfo.EnsureCapacity(bufferSize);
int retValue = NativeMethods.QueryDosDevice(driveName, pathInfo, bufferSize);
if (retValue > 0)
{
// If the drive letter is a substed path, the result will be in the format of
// - "\??\C:\RealPath" for local path
// - "\??\UNC\RealPath" for network path
associatedPath = pathInfo.ToString();
if (associatedPath.StartsWith("\\??\\", StringComparison.OrdinalIgnoreCase))
{
associatedPath = associatedPath.Remove(0, 4);
if (associatedPath.StartsWith("UNC", StringComparison.OrdinalIgnoreCase))
{
associatedPath = associatedPath.Remove(0, 3);
associatedPath = "\\" + associatedPath;
}
else if (associatedPath.EndsWith(':'))
{
// The substed path is the root path of a drive. For example: subst Y: C:\
associatedPath += Path.DirectorySeparatorChar;
}
}
else
{
// The drive name is not a substed path, then we return the root path of the drive
associatedPath = driveName + "\\";
}
break;
}
// Windows API call failed
int errorCode = Marshal.GetLastWin32Error();
if (errorCode != 122)
{
// ERROR_INSUFFICIENT_BUFFER = 122
// For an error other than "insufficient buffer", throw it
throw new Win32Exception((int)errorCode);
}
// We got the "insufficient buffer" error. In this case we extend
// the buffer size, unless it's unreasonably too large.
if (bufferSize >= 32767)
{
// "The Windows API has many functions that also have Unicode versions to permit
// an extended-length path for a maximum total path length of 32,767 characters"
// See https://msdn.microsoft.com/library/aa365247.aspx#maxpath
string errorMsg = StringUtil.Format(FileSystemProviderStrings.SubstitutePathTooLong, driveName);
throw new InvalidOperationException(errorMsg);
}
// Extend the buffer size and try again.
bufferSize *= 10;
if (bufferSize > 32767)
{
bufferSize = 32767;
}
}
}
return associatedPath;
}
/// <summary>
/// Get the root path for a network drive or MS-DOS device.
/// </summary>
/// <param name="driveInfo"></param>
/// <returns></returns>
internal static string GetRootPathForNetworkDriveOrDosDevice(DriveInfo driveInfo)
{
Dbg.Diagnostics.Assert(driveInfo.DriveType == DriveType.Network, "Caller should make sure it is a network drive.");
string driveName = driveInfo.Name.Substring(0, 1);
string rootPath = null;
try
{
rootPath = GetUNCForNetworkDrive(driveName);
}
catch (Win32Exception)
{
if (driveInfo.IsReady)
{
// The drive is ready but we failed to find the UNC path based on the drive name.
// In this case, it's possibly a MS-DOS device created by 'subst' command that
// - substitutes a network location directly, or
// - substitutes a path in a drive that maps to a network location
rootPath = GetSubstitutedPathForNetworkDosDevice(driveName);
}
else
{
throw;
}
}
return rootPath;
}
/// <summary>
/// Returns a collection of all logical drives in the system.
/// </summary>