source
Unblocker.cs
from FolderKit
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 | using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Windows.Forms; namespace FolderKit { internal sealed class UnblockResult { public int FilesScanned; public int Unblocked; public readonly List<string> Failures = new List<string>(); } /// <summary> /// "Unblock" = remove the Mark-of-the-Web. When a browser, Outlook or Teams saves a download, Windows /// attaches a hidden stream named Zone.Identifier to the file. That stream is what triggers /// "This file came from another computer and might be blocked", Office Protected View, blocked /// macros, SmartScreen prompts and "blocked" CHM help files. Deleting the stream is exactly what the /// Unblock checkbox in File Properties and PowerShell's Unblock-File do. /// </summary> internal static class Unblocker { private const string MarkStream = ":Zone.Identifier"; private const int ERROR_FILE_NOT_FOUND = 2; private const int ERROR_PATH_NOT_FOUND = 3; private const int ERROR_ACCESS_DENIED = 5; /// <summary>Unblocks one file, or a folder and everything under it.</summary> public static void Unblock(string path, UnblockResult result) { string full; try { full = Path.GetFullPath(path); } catch (Exception ex) { result.Failures.Add(path + ": " + ex.Message); return; } if (File.Exists(full)) { result.FilesScanned++; TryRemoveMark(full, result); } else if (Directory.Exists(full)) { UnblockFolder(full, result); } else { result.Failures.Add(full + ": not found"); } } private static void UnblockFolder(string root, UnblockResult result) { // Folders can carry the mark too (some unzip tools copy it onto extracted folders). if (!PathUtil.IsDriveRoot(root)) TryRemoveMark(root, result); var pending = new Stack<string>(); pending.Push(root); while (pending.Count > 0) { string dir = pending.Pop(); List<string> entries; try { entries = Directory.EnumerateFileSystemEntries(dir).ToList(); } catch (Exception ex) when (ex is UnauthorizedAccessException || ex is IOException) { // One unreadable sub-folder doesn't abort the whole run. result.Failures.Add(dir + ": " + ex.Message); continue; } foreach (var entry in entries) { FileAttributes attrs; try { attrs = File.GetAttributes(entry); } catch (Exception ex) { result.Failures.Add(entry + ": " + ex.Message); continue; } if ((attrs & FileAttributes.Directory) != 0) { TryRemoveMark(entry, result); // Don't follow junctions/symlinks: avoids loops and wandering outside the folder. if ((attrs & FileAttributes.ReparsePoint) == 0) pending.Push(entry); } else { result.FilesScanned++; TryRemoveMark(entry, result); } } } } private static void TryRemoveMark(string fullPath, UnblockResult result) { string stream = PathUtil.ToExtendedPath(fullPath) + MarkStream; if (NativeMethods.DeleteFileW(stream)) { result.Unblocked++; return; } int err = Marshal.GetLastWin32Error(); if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) return; // wasn't blocked // Read-only files refuse stream deletion: clear the flag, retry, put it back. if (err == ERROR_ACCESS_DENIED) { try { var attrs = File.GetAttributes(fullPath); if ((attrs & FileAttributes.ReadOnly) != 0 && (attrs & FileAttributes.Directory) == 0) { File.SetAttributes(fullPath, attrs & ~FileAttributes.ReadOnly); try { if (NativeMethods.DeleteFileW(stream)) { result.Unblocked++; return; } err = Marshal.GetLastWin32Error(); } finally { File.SetAttributes(fullPath, attrs); } } } catch (Exception ex) { result.Failures.Add(fullPath + ": " + ex.Message); return; } } result.Failures.Add(fullPath + ": " + new Win32Exception(err).Message); } } /// <summary> /// Handles "FolderKit.exe --unblock path". When several files are selected, Explorer starts one /// process per file. The first process becomes the collector: the others hand it their path over a /// named pipe and exit, so the user gets one summary instead of a pile of message boxes. /// </summary> internal static class UnblockCommand { private const int IdleMilliseconds = 700; private static string MutexName { get { return @"Local\" + AppInfo.Name + ".Unblock"; } } private static string PipeName { get { return AppInfo.Name + ".Unblock." + Process.GetCurrentProcess().SessionId; } } public static void Run(string path) { bool isFirst; using (var mutex = new Mutex(true, MutexName, out isFirst)) { if (!isFirst) { if (TrySendToCollector(path)) return; ProcessPaths(new List<string> { path }); // collector already finished: do it ourselves return; } var paths = new List<string> { path }; try { CollectFromOtherInstances(paths); } finally { mutex.ReleaseMutex(); } ProcessPaths(paths); } } private static void CollectFromOtherInstances(List<string> paths) { while (true) { using (var server = new NamedPipeServerStream(PipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) { var wait = server.BeginWaitForConnection(null, null); if (!wait.AsyncWaitHandle.WaitOne(IdleMilliseconds)) return; // nobody else is coming server.EndWaitForConnection(wait); try { var reader = new StreamReader(server, Encoding.UTF8); var line = reader.ReadLine(); if (!string.IsNullOrWhiteSpace(line)) paths.Add(line); server.WriteByte(1); // acknowledge, so the sender knows it can exit server.Flush(); } catch (IOException) { /* sender went away; it will handle its own file */ } } } } private static bool TrySendToCollector(string path) { try { using (var client = new NamedPipeClientStream(".", PipeName, PipeDirection.InOut)) { client.Connect(3000); var bytes = Encoding.UTF8.GetBytes(path + "\n"); client.Write(bytes, 0, bytes.Length); client.Flush(); return client.ReadByte() == 1; } } catch (Exception) { return false; } } private static void ProcessPaths(List<string> paths) { var result = new UnblockResult(); Cursor.Current = Cursors.WaitCursor; foreach (var p in paths.Distinct(StringComparer.OrdinalIgnoreCase)) Unblocker.Unblock(p, result); Cursor.Current = Cursors.Default; var msg = new StringBuilder(); if (result.Unblocked > 0) msg.AppendFormat("Unblocked {0} item(s). Checked {1} file(s).", result.Unblocked, result.FilesScanned); else msg.AppendFormat("Nothing to unblock. None of the {0} file(s) checked had the \"downloaded from the internet\" mark.", result.FilesScanned); if (result.Failures.Count > 0) { msg.AppendLine().AppendLine().AppendFormat("{0} item(s) could not be processed:", result.Failures.Count).AppendLine(); foreach (var f in result.Failures.Take(15)) msg.AppendLine(" • " + f); if (result.Failures.Count > 15) msg.AppendLine(" …"); Ui.Warn(msg.ToString()); } else { Ui.Info(msg.ToString()); } } } } |