Debian Codegraph @

lib/ansible/module_utils/powershell/Ansible.ModuleUtils.LinkUtil.psm1

raw
1 # Copyright (c) 2017 Ansible Project
2 # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
3
4 #Requires -Module Ansible.ModuleUtils.PrivilegeUtil
5
6 Function Load-LinkUtils {
7 [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification = "Cannot change the name now")]
8 param ()
9
10 $link_util = @'
11 using Microsoft.Win32.SafeHandles;
12 using System;
13 using System.Collections.Generic;
14 using System.IO;
15 using System.Runtime.InteropServices;
16 using System.Text;
17
18 namespace Ansible
19 {
20 public enum LinkType
21 {
22 SymbolicLink,
23 JunctionPoint,
24 HardLink
25 }
26
27 public class LinkUtilWin32Exception : System.ComponentModel.Win32Exception
28 {
29 private string _msg;
30
31 public LinkUtilWin32Exception(string message) : this(Marshal.GetLastWin32Error(), message) { }
32
33 public LinkUtilWin32Exception(int errorCode, string message) : base(errorCode)
34 {
35 _msg = String.Format("{0} ({1}, Win32ErrorCode {2})", message, base.Message, errorCode);
36 }
37
38 public override string Message { get { return _msg; } }
39 public static explicit operator LinkUtilWin32Exception(string message) { return new LinkUtilWin32Exception(message); }
40 }
41
42 public class LinkInfo
43 {
44 public LinkType Type { get; internal set; }
45 public string PrintName { get; internal set; }
46 public string SubstituteName { get; internal set; }
47 public string AbsolutePath { get; internal set; }
48 public string TargetPath { get; internal set; }
49 public string[] HardTargets { get; internal set; }
50 }
51
52 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
53 public struct REPARSE_DATA_BUFFER
54 {
55 public UInt32 ReparseTag;
56 public UInt16 ReparseDataLength;
57 public UInt16 Reserved;
58 public UInt16 SubstituteNameOffset;
59 public UInt16 SubstituteNameLength;
60 public UInt16 PrintNameOffset;
61 public UInt16 PrintNameLength;
62
63 [MarshalAs(UnmanagedType.ByValArray, SizeConst = LinkUtil.MAXIMUM_REPARSE_DATA_BUFFER_SIZE)]
64 public char[] PathBuffer;
65 }
66
67 public class LinkUtil
68 {
69 public const int MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 1024 * 16;
70
71 private const UInt32 FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
72 private const UInt32 FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000;
73
74 private const UInt32 FSCTL_GET_REPARSE_POINT = 0x000900A8;
75 private const UInt32 FSCTL_SET_REPARSE_POINT = 0x000900A4;
76 private const UInt32 FILE_DEVICE_FILE_SYSTEM = 0x00090000;
77
78 private const UInt32 IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003;
79 private const UInt32 IO_REPARSE_TAG_SYMLINK = 0xA000000C;
80
81 private const UInt32 SYMLINK_FLAG_RELATIVE = 0x00000001;
82
83 private const Int64 INVALID_HANDLE_VALUE = -1;
84
85 private const UInt32 SIZE_OF_WCHAR = 2;
86
87 private const UInt32 SYMBOLIC_LINK_FLAG_FILE = 0x00000000;
88 private const UInt32 SYMBOLIC_LINK_FLAG_DIRECTORY = 0x00000001;
89
90 [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
91 private static extern SafeFileHandle CreateFile(
92 string lpFileName,
93 [MarshalAs(UnmanagedType.U4)] FileAccess dwDesiredAccess,
94 [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode,
95 IntPtr lpSecurityAttributes,
96 [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition,
97 UInt32 dwFlagsAndAttributes,
98 IntPtr hTemplateFile);
99
100 // Used by GetReparsePointInfo()
101 [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
102 private static extern bool DeviceIoControl(
103 SafeFileHandle hDevice,
104 UInt32 dwIoControlCode,
105 IntPtr lpInBuffer,
106 UInt32 nInBufferSize,
107 out REPARSE_DATA_BUFFER lpOutBuffer,
108 UInt32 nOutBufferSize,
109 out UInt32 lpBytesReturned,
110 IntPtr lpOverlapped);
111
112 // Used by CreateJunctionPoint()
113 [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
114 private static extern bool DeviceIoControl(
115 SafeFileHandle hDevice,
116 UInt32 dwIoControlCode,
117 REPARSE_DATA_BUFFER lpInBuffer,
118 UInt32 nInBufferSize,
119 IntPtr lpOutBuffer,
120 UInt32 nOutBufferSize,
121 out UInt32 lpBytesReturned,
122 IntPtr lpOverlapped);
123
124 [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
125 private static extern bool GetVolumePathName(
126 string lpszFileName,
127 StringBuilder lpszVolumePathName,
128 ref UInt32 cchBufferLength);
129
130 [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
131 private static extern IntPtr FindFirstFileNameW(
132 string lpFileName,
133 UInt32 dwFlags,
134 ref UInt32 StringLength,
135 StringBuilder LinkName);
136
137 [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
138 private static extern bool FindNextFileNameW(
139 IntPtr hFindStream,
140 ref UInt32 StringLength,
141 StringBuilder LinkName);
142
143 [DllImport("kernel32.dll", SetLastError = true)]
144 private static extern bool FindClose(
145 IntPtr hFindFile);
146
147 [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
148 private static extern bool RemoveDirectory(
149 string lpPathName);
150
151 [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
152 private static extern bool DeleteFile(
153 string lpFileName);
154
155 [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
156 private static extern bool CreateSymbolicLink(
157 string lpSymlinkFileName,
158 string lpTargetFileName,
159 UInt32 dwFlags);
160
161 [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
162 private static extern bool CreateHardLink(
163 string lpFileName,
164 string lpExistingFileName,
165 IntPtr lpSecurityAttributes);
166
167 public static LinkInfo GetLinkInfo(string linkPath)
168 {
169 FileAttributes attr = File.GetAttributes(linkPath);
170 if (attr.HasFlag(FileAttributes.ReparsePoint))
171 return GetReparsePointInfo(linkPath);
172
173 if (!attr.HasFlag(FileAttributes.Directory))
174 return GetHardLinkInfo(linkPath);
175
176 return null;
177 }
178
179 public static void DeleteLink(string linkPath)
180 {
181 bool success;
182 FileAttributes attr = File.GetAttributes(linkPath);
183 if (attr.HasFlag(FileAttributes.Directory))
184 {
185 success = RemoveDirectory(linkPath);
186 }
187 else
188 {
189 success = DeleteFile(linkPath);
190 }
191
192 if (!success)
193 throw new LinkUtilWin32Exception(String.Format("Failed to delete link at {0}", linkPath));
194 }
195
196 public static void CreateLink(string linkPath, String linkTarget, LinkType linkType)
197 {
198 switch (linkType)
199 {
200 case LinkType.SymbolicLink:
201 UInt32 linkFlags;
202 FileAttributes attr = File.GetAttributes(linkTarget);
203 if (attr.HasFlag(FileAttributes.Directory))
204 linkFlags = SYMBOLIC_LINK_FLAG_DIRECTORY;
205 else
206 linkFlags = SYMBOLIC_LINK_FLAG_FILE;
207
208 if (!CreateSymbolicLink(linkPath, linkTarget, linkFlags))
209 throw new LinkUtilWin32Exception(String.Format("CreateSymbolicLink({0}, {1}, {2}) failed", linkPath, linkTarget, linkFlags));
210 break;
211 case LinkType.JunctionPoint:
212 CreateJunctionPoint(linkPath, linkTarget);
213 break;
214 case LinkType.HardLink:
215 if (!CreateHardLink(linkPath, linkTarget, IntPtr.Zero))
216 throw new LinkUtilWin32Exception(String.Format("CreateHardLink({0}, {1}) failed", linkPath, linkTarget));
217 break;
218 }
219 }
220
221 private static LinkInfo GetHardLinkInfo(string linkPath)
222 {
223 UInt32 maxPath = 260;
224 List<string> result = new List<string>();
225
226 StringBuilder sb = new StringBuilder((int)maxPath);
227 UInt32 stringLength = maxPath;
228 if (!GetVolumePathName(linkPath, sb, ref stringLength))
229 throw new LinkUtilWin32Exception("GetVolumePathName() failed");
230 string volume = sb.ToString();
231
232 stringLength = maxPath;
233 IntPtr findHandle = FindFirstFileNameW(linkPath, 0, ref stringLength, sb);
234 if (findHandle.ToInt64() != INVALID_HANDLE_VALUE)
235 {
236 try
237 {
238 do
239 {
240 string hardLinkPath = sb.ToString();
241 if (hardLinkPath.StartsWith("\\"))
242 hardLinkPath = hardLinkPath.Substring(1, hardLinkPath.Length - 1);
243
244 result.Add(Path.Combine(volume, hardLinkPath));
245 stringLength = maxPath;
246
247 } while (FindNextFileNameW(findHandle, ref stringLength, sb));
248 }
249 finally
250 {
251 FindClose(findHandle);
252 }
253 }
254
255 if (result.Count > 1)
256 return new LinkInfo
257 {
258 Type = LinkType.HardLink,
259 HardTargets = result.ToArray()
260 };
261
262 return null;
263 }
264
265 private static LinkInfo GetReparsePointInfo(string linkPath)
266 {
267 SafeFileHandle fileHandle = CreateFile(
268 linkPath,
269 FileAccess.Read,
270 FileShare.None,
271 IntPtr.Zero,
272 FileMode.Open,
273 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
274 IntPtr.Zero);
275
276 if (fileHandle.IsInvalid)
277 throw new LinkUtilWin32Exception(String.Format("CreateFile({0}) failed", linkPath));
278
279 REPARSE_DATA_BUFFER buffer = new REPARSE_DATA_BUFFER();
280 UInt32 bytesReturned;
281 try
282 {
283 if (!DeviceIoControl(
284 fileHandle,
285 FSCTL_GET_REPARSE_POINT,
286 IntPtr.Zero,
287 0,
288 out buffer,
289 MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
290 out bytesReturned,
291 IntPtr.Zero))
292 throw new LinkUtilWin32Exception(String.Format("DeviceIoControl() failed for file at {0}", linkPath));
293 }
294 finally
295 {
296 fileHandle.Dispose();
297 }
298
299 bool isRelative = false;
300 int pathOffset = 0;
301 LinkType linkType;
302 if (buffer.ReparseTag == IO_REPARSE_TAG_SYMLINK)
303 {
304 UInt32 bufferFlags = Convert.ToUInt32(buffer.PathBuffer[0]) + Convert.ToUInt32(buffer.PathBuffer[1]);
305 if (bufferFlags == SYMLINK_FLAG_RELATIVE)
306 isRelative = true;
307 pathOffset = 2;
308 linkType = LinkType.SymbolicLink;
309 }
310 else if (buffer.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
311 {
312 linkType = LinkType.JunctionPoint;
313 }
314 else
315 {
316 string errorMessage = String.Format("Invalid Reparse Tag: {0}", buffer.ReparseTag.ToString());
317 throw new Exception(errorMessage);
318 }
319
320 string printName = new string(buffer.PathBuffer,
321 (int)(buffer.PrintNameOffset / SIZE_OF_WCHAR) + pathOffset,
322 (int)(buffer.PrintNameLength / SIZE_OF_WCHAR));
323 string substituteName = new string(buffer.PathBuffer,
324 (int)(buffer.SubstituteNameOffset / SIZE_OF_WCHAR) + pathOffset,
325 (int)(buffer.SubstituteNameLength / SIZE_OF_WCHAR));
326
327 // TODO: should we check for \?\UNC\server for convert it to the NT style \\server path
328 // Remove the leading Windows object directory \?\ from the path if present
329 string targetPath = substituteName;
330 if (targetPath.StartsWith("\\??\\"))
331 targetPath = targetPath.Substring(4, targetPath.Length - 4);
332
333 string absolutePath = targetPath;
334 if (isRelative)
335 absolutePath = Path.GetFullPath(Path.Combine(new FileInfo(linkPath).Directory.FullName, targetPath));
336
337 return new LinkInfo
338 {
339 Type = linkType,
340 PrintName = printName,
341 SubstituteName = substituteName,
342 AbsolutePath = absolutePath,
343 TargetPath = targetPath
344 };
345 }
346
347 private static void CreateJunctionPoint(string linkPath, string linkTarget)
348 {
349 // We need to create the link as a dir beforehand
350 Directory.CreateDirectory(linkPath);
351 SafeFileHandle fileHandle = CreateFile(
352 linkPath,
353 FileAccess.Write,
354 FileShare.Read | FileShare.Write | FileShare.None,
355 IntPtr.Zero,
356 FileMode.Open,
357 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
358 IntPtr.Zero);
359
360 if (fileHandle.IsInvalid)
361 throw new LinkUtilWin32Exception(String.Format("CreateFile({0}) failed", linkPath));
362
363 try
364 {
365 string substituteName = "\\??\\" + Path.GetFullPath(linkTarget);
366 string printName = linkTarget;
367
368 REPARSE_DATA_BUFFER buffer = new REPARSE_DATA_BUFFER();
369 buffer.SubstituteNameOffset = 0;
370 buffer.SubstituteNameLength = (UInt16)(substituteName.Length * SIZE_OF_WCHAR);
371 buffer.PrintNameOffset = (UInt16)(buffer.SubstituteNameLength + 2);
372 buffer.PrintNameLength = (UInt16)(printName.Length * SIZE_OF_WCHAR);
373
374 buffer.ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
375 buffer.ReparseDataLength = (UInt16)(buffer.SubstituteNameLength + buffer.PrintNameLength + 12);
376 buffer.PathBuffer = new char[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
377
378 byte[] unicodeBytes = Encoding.Unicode.GetBytes(substituteName + "\0" + printName);
379 char[] pathBuffer = Encoding.Unicode.GetChars(unicodeBytes);
380 Array.Copy(pathBuffer, buffer.PathBuffer, pathBuffer.Length);
381
382 UInt32 bytesReturned;
383 if (!DeviceIoControl(
384 fileHandle,
385 FSCTL_SET_REPARSE_POINT,
386 buffer,
387 (UInt32)(buffer.ReparseDataLength + 8),
388 IntPtr.Zero, 0,
389 out bytesReturned,
390 IntPtr.Zero))
391 throw new LinkUtilWin32Exception(String.Format("DeviceIoControl() failed to create junction point at {0} to {1}", linkPath, linkTarget));
392 }
393 finally
394 {
395 fileHandle.Dispose();
396 }
397 }
398 }
399 }
400 '@
401
402 # FUTURE: find a better way to get the _ansible_remote_tmp variable
403 $original_tmp = $env:TMP
404 $original_lib = $env:LIB
405
406 $remote_tmp = $original_tmp
407 $module_params = Get-Variable -Name complex_args -ErrorAction SilentlyContinue
408 if ($module_params) {
409 if ($module_params.Value.ContainsKey("_ansible_remote_tmp") ) {
410 $remote_tmp = $module_params.Value["_ansible_remote_tmp"]
411 $remote_tmp = [System.Environment]::ExpandEnvironmentVariables($remote_tmp)
412 }
413 }
414
415 $env:TMP = $remote_tmp
416 $env:LIB = $null
417 Add-Type -TypeDefinition $link_util
418 $env:TMP = $original_tmp
419 $env:LIB = $original_lib
420
421 # enable the SeBackupPrivilege if it is disabled
422 $state = Get-AnsiblePrivilege -Name SeBackupPrivilege
423 if ($state -eq $false) {
424 Set-AnsiblePrivilege -Name SeBackupPrivilege -Value $true
425 }
426 }
427
428 Function Get-Link($link_path) {
429 $link_info = [Ansible.LinkUtil]::GetLinkInfo($link_path)
430 return $link_info
431 }
432
433 Function Remove-Link($link_path) {
434 [Ansible.LinkUtil]::DeleteLink($link_path)
435 }
436
437 Function New-Link($link_path, $link_target, $link_type) {
438 if (-not (Test-Path -LiteralPath $link_target)) {
439 throw "link_target '$link_target' does not exist, cannot create link"
440 }
441
442 switch ($link_type) {
443 "link" {
444 $type = [Ansible.LinkType]::SymbolicLink
445 }
446 "junction" {
447 if (Test-Path -LiteralPath $link_target -PathType Leaf) {
448 throw "cannot set the target for a junction point to a file"
449 }
450 $type = [Ansible.LinkType]::JunctionPoint
451 }
452 "hard" {
453 if (Test-Path -LiteralPath $link_target -PathType Container) {
454 throw "cannot set the target for a hard link to a directory"
455 }
456 $type = [Ansible.LinkType]::HardLink
457 }
458 default { throw "invalid link_type option $($link_type): expecting link, junction, hard" }
459 }
460 [Ansible.LinkUtil]::CreateLink($link_path, $link_target, $type)
461 }
462
463 # this line must stay at the bottom to ensure all defined module parts are exported
464 Export-ModuleMember -Alias * -Function * -Cmdlet *