forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnblockFile.cs
More file actions
229 lines (207 loc) · 8.07 KB
/
Copy pathUnblockFile.cs
File metadata and controls
229 lines (207 loc) · 8.07 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Runtime.InteropServices;
#endregion
namespace Microsoft.PowerShell.Commands
{
/// <summary>Removes the Zone.Identifier stream from a file.</summary>
[Cmdlet(VerbsSecurity.Unblock, "File", DefaultParameterSetName = "ByPath", SupportsShouldProcess = true,
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097033")]
public sealed class UnblockFileCommand : PSCmdlet
{
#if UNIX
private const string MacBlockAttribute = "com.apple.quarantine";
private const int RemovexattrFollowSymLink = 0;
#endif
/// <summary>
/// The path of the file to unblock.
/// </summary>
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByPath")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Path
{
get
{
return _paths;
}
set
{
_paths = value;
}
}
/// <summary>
/// The literal path of the file to unblock.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = "ByLiteralPath", ValueFromPipelineByPropertyName = true)]
[Alias("PSPath", "LP")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] LiteralPath
{
get
{
return _paths;
}
set
{
_paths = value;
}
}
private string[] _paths;
/// <summary>
/// Generate the type(s)
/// </summary>
protected override void ProcessRecord()
{
List<string> pathsToProcess = new List<string>();
ProviderInfo provider = null;
if (string.Equals(this.ParameterSetName, "ByLiteralPath", StringComparison.OrdinalIgnoreCase))
{
foreach (string path in _paths)
{
string newPath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);
if (IsValidFileForUnblocking(newPath))
{
pathsToProcess.Add(newPath);
}
}
}
else
{
// Resolve paths
foreach (string path in _paths)
{
try
{
Collection<string> newPaths = Context.SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider);
foreach (string currentFilepath in newPaths)
{
if (IsValidFileForUnblocking(currentFilepath))
{
pathsToProcess.Add(currentFilepath);
}
}
}
catch (ItemNotFoundException e)
{
if (!WildcardPattern.ContainsWildcardCharacters(path))
{
ErrorRecord errorRecord = new ErrorRecord(e,
"FileNotFound",
ErrorCategory.ObjectNotFound,
path);
WriteError(errorRecord);
}
}
}
}
#if !UNIX
// Unblock files
foreach (string path in pathsToProcess)
{
if (ShouldProcess(path))
{
try
{
AlternateDataStreamUtilities.DeleteFileStream(path, "Zone.Identifier");
}
catch (Exception e)
{
WriteError(new ErrorRecord(exception: e, errorId: "RemoveItemUnableToAccessFile", ErrorCategory.ResourceUnavailable, targetObject: path));
}
}
}
#else
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
string errorMessage = UnblockFileStrings.LinuxNotSupported;
Exception e = new PlatformNotSupportedException(errorMessage);
ThrowTerminatingError(new ErrorRecord(exception: e, errorId: "LinuxNotSupported", ErrorCategory.NotImplemented, targetObject: null));
return;
}
foreach (string path in pathsToProcess)
{
if(IsBlocked(path))
{
UInt32 result = RemoveXattr(path, MacBlockAttribute, RemovexattrFollowSymLink);
if(result != 0)
{
string errorMessage = string.Format(CultureInfo.CurrentUICulture, UnblockFileStrings.UnblockError, path);
Exception e = new InvalidOperationException(errorMessage);
WriteError(new ErrorRecord(exception: e, errorId: "UnblockError", ErrorCategory.InvalidResult, targetObject: path));
}
}
}
#endif
}
/// <summary>
/// IsValidFileForUnblocking is a helper method used to validate if
/// the supplied file path has to be considered for unblocking.
/// </summary>
/// <param name="resolvedpath">File or directory path.</param>
/// <returns>True is the supplied path is a
/// valid file path or else false is returned.
/// If the supplied path is a directory path then false is returned.</returns>
private bool IsValidFileForUnblocking(string resolvedpath)
{
bool isValidUnblockableFile = false;
// Bug 501423 : silently ignore folders given that folders cannot have
// alternate data streams attached to them (i.e. they're already unblocked).
if (!System.IO.Directory.Exists(resolvedpath))
{
if (!System.IO.File.Exists(resolvedpath))
{
ErrorRecord errorRecord = new ErrorRecord(
new System.IO.FileNotFoundException(resolvedpath),
"FileNotFound",
ErrorCategory.ObjectNotFound,
resolvedpath);
WriteError(errorRecord);
}
else
{
isValidUnblockableFile = true; ;
}
}
return isValidUnblockableFile;
}
#if UNIX
private bool IsBlocked(string path)
{
uint valueSize = 1024;
IntPtr value = Marshal.AllocHGlobal((int)valueSize);
try
{
var resultSize = GetXattr(path, MacBlockAttribute, value, valueSize, 0, RemovexattrFollowSymLink);
return resultSize != -1;
}
finally
{
Marshal.FreeHGlobal(value);
}
}
// Ansi means UTF8 on Unix
// https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/RemoveXattr.2.html
[DllImport("libc", SetLastError = true, EntryPoint = "removexattr", CharSet = CharSet.Ansi)]
private static extern UInt32 RemoveXattr(string path, string name, int options);
[DllImport("libc", EntryPoint = "getxattr", CharSet = CharSet.Ansi)]
private static extern long GetXattr(
[MarshalAs(UnmanagedType.LPStr)] string path,
[MarshalAs(UnmanagedType.LPStr)] string name,
IntPtr value,
ulong size,
uint position,
int options);
#endif
}
}