Debian Codegraph @

lib/ansible/module_utils/csharp/Ansible.Basic.cs

raw
1 using Microsoft.Win32.SafeHandles;
2 using System;
3 using System.Collections;
4 using System.Collections.Generic;
5 using System.ComponentModel;
6 using System.Diagnostics;
7 using System.IO;
8 using System.Linq;
9 using System.Management.Automation;
10 using System.Management.Automation.Runspaces;
11 using System.Reflection;
12 using System.Runtime.InteropServices;
13 using System.Security.AccessControl;
14 using System.Security.Principal;
15 #if CORECLR
16 using System.Text.Json;
17 #else
18 using System.Web.Script.Serialization;
19 #endif
20 using Ansible.Secrets;
21
22 // System.Diagnostics.EventLog.dll reference different versioned dlls that are
23 // loaded in PSCore, ignore CS1702 so the code will ignore this warning
24 //NoWarn -Name CS1702 -CLR Core
25
26 //AssemblyReference -Type System.Diagnostics.EventLog -CLR Core
27 //AssemblyReference -Type System.Security.AccessControl.NativeObjectSecurity -CLR Core
28 //AssemblyReference -Type System.Security.AccessControl.DirectorySecurity -CLR Core
29 //AssemblyReference -Type System.Security.Principal.IdentityReference -CLR Core
30
31 //AssemblyReference -Name System.Web.Extensions.dll -CLR Framework
32
33 namespace Ansible.Basic
34 {
35 public class AnsibleModule
36 {
37 public delegate void ExitHandler(int rc);
38 public static ExitHandler Exit = new ExitHandler(ExitModule);
39
40 public delegate void WriteLineHandler(string line);
41 public static WriteLineHandler WriteLine = new WriteLineHandler(WriteLineModule);
42
43 public static bool _DebugArgSpec = false;
44
45 // Used by the executor scripts to store warnings from the wrapper functions.
46 // This is public to avoid reflection but should not be used by modules.
47 public static List<string> _WrapperWarnings;
48
49 private static List<string> BOOLEANS_TRUE = new List<string>() { "y", "yes", "on", "1", "true", "t", "1.0" };
50 private static List<string> BOOLEANS_FALSE = new List<string>() { "n", "no", "off", "0", "false", "f", "0.0" };
51
52 private bool ignoreUnknownOpts = false;
53 private string remoteTmp = Path.GetTempPath();
54 private string tmpdir = null;
55 private List<string> optionsContext = new List<string>();
56 private List<string> warnings = new List<string>();
57 private List<Dictionary<string, string>> deprecations = new List<Dictionary<string, string>>();
58 private List<string> cleanupFiles = new List<string>();
59 private string[] _tracebacksFor = new string[0];
60 private bool injectInvocation = false;
61
62 private Dictionary<string, string> passVars = new Dictionary<string, string>()
63 {
64 // null values means no mapping, not used in Ansible.Basic.AnsibleModule
65 // keep in sync with python counterpart in lib/ansible/module_utils/common/parameters.py
66 { "check_mode", "CheckMode" },
67 { "debug", "DebugMode" },
68 { "diff", "DiffMode" },
69 { "keep_remote_files", "KeepRemoteFiles" },
70 { "ignore_unknown_opts", "ignoreUnknownOpts" },
71 { "inject_invocation", "injectInvocation" },
72 { "module_name", "ModuleName" },
73 { "no_log", "NoLog" },
74 { "remote_tmp", "remoteTmp" },
75 { "selinux_special_fs", null },
76 { "shell_executable", null },
77 { "socket", null },
78 { "syslog_facility", null },
79 { "target_log_info", "TargetLogInfo" },
80 { "tracebacks_for", "_tracebacksFor" },
81 { "tmpdir", "tmpdir" },
82 { "verbosity", "Verbosity" },
83 { "version", "AnsibleVersion" },
84 };
85 private List<string> passBools = new List<string>() { "check_mode", "debug", "diff", "keep_remote_files", "ignore_unknown_opts", "inject_invocation", "no_log" };
86 private List<string> passInts = new List<string>() { "verbosity" };
87 private string[] passStringArrays = new string[] { "tracebacks_for" };
88 private Dictionary<string, List<object>> specDefaults = new Dictionary<string, List<object>>()
89 {
90 // key - (default, type) - null is freeform
91 { "apply_defaults", new List<object>() { false, typeof(bool) } },
92 { "aliases", new List<object>() { typeof(List<string>), typeof(List<string>) } },
93 { "choices", new List<object>() { typeof(List<object>), typeof(List<object>) } },
94 { "default", new List<object>() { null, null } },
95 { "deprecated_aliases", new List<object>() { typeof(List<Hashtable>), typeof(List<Hashtable>) } },
96 { "elements", new List<object>() { null, null } },
97 { "mutually_exclusive", new List<object>() { typeof(List<List<string>>), typeof(List<object>) } },
98 { "no_log", new List<object>() { false, typeof(bool) } },
99 { "options", new List<object>() { typeof(Hashtable), typeof(Hashtable) } },
100 { "removed_in_version", new List<object>() { null, typeof(string) } },
101 { "removed_at_date", new List<object>() { null, typeof(DateTime) } },
102 { "removed_from_collection", new List<object>() { null, typeof(string) } },
103 { "required", new List<object>() { false, typeof(bool) } },
104 { "required_by", new List<object>() { typeof(Hashtable), typeof(Hashtable) } },
105 { "required_if", new List<object>() { typeof(List<List<object>>), typeof(List<object>) } },
106 { "required_one_of", new List<object>() { typeof(List<List<string>>), typeof(List<object>) } },
107 { "required_together", new List<object>() { typeof(List<List<string>>), typeof(List<object>) } },
108 { "supports_check_mode", new List<object>() { false, typeof(bool) } },
109 { "type", new List<object>() { "str", null } },
110 };
111 private Dictionary<string, Delegate> optionTypes = new Dictionary<string, Delegate>()
112 {
113 { "bool", new Func<object, bool>(ParseBool) },
114 { "dict", new Func<object, Dictionary<string, object>>(ParseDict) },
115 { "float", new Func<object, float>(ParseFloat) },
116 { "int", new Func<object, int>(ParseInt) },
117 { "json", new Func<object, string>(ParseJson) },
118 { "list", new Func<object, List<object>>(ParseList) },
119 { "path", new Func<object, string>(ParsePath) },
120 { "raw", new Func<object, object>(ParseRaw) },
121 { "sid", new Func<object, SecurityIdentifier>(ParseSid) },
122 { "str", new Func<object, string>(ParseStr) },
123 };
124
125 public Dictionary<string, object> Diff = new Dictionary<string, object>();
126 public IDictionary Params = null;
127 public Dictionary<string, object> Result = new Dictionary<string, object>() { { "changed", false } };
128
129 public bool CheckMode { get; private set; }
130 public bool DebugMode { get; private set; }
131 public bool DiffMode { get; private set; }
132 public bool KeepRemoteFiles { get; private set; }
133 public string ModuleName { get; private set; }
134 public bool NoLog { get; private set; }
135 public string TargetLogInfo { get; private set; }
136 public int Verbosity { get; private set; }
137 public string AnsibleVersion { get; private set; }
138 public string[] TracebacksFor { get { return _tracebacksFor; } }
139
140 public string Tmpdir
141 {
142 get
143 {
144 if (tmpdir == null)
145 {
146 #if WINDOWS
147 SecurityIdentifier user = WindowsIdentity.GetCurrent().User;
148 DirectorySecurity dirSecurity = new DirectorySecurity();
149 dirSecurity.SetOwner(user);
150 dirSecurity.SetAccessRuleProtection(true, false); // disable inheritance rules
151 FileSystemAccessRule ace = new FileSystemAccessRule(user, FileSystemRights.FullControl,
152 InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
153 PropagationFlags.None, AccessControlType.Allow);
154 dirSecurity.AddAccessRule(ace);
155 #else
156 UnixFileMode userMode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute;
157 #endif
158
159 string baseDir = Path.GetFullPath(Environment.ExpandEnvironmentVariables(remoteTmp));
160 if (!Directory.Exists(baseDir))
161 {
162 string failedMsg = null;
163 try
164 {
165 #if WINDOWS
166 #if CORECLR
167 FileSystemAclExtensions.CreateDirectory(dirSecurity, baseDir);
168 #else
169 Directory.CreateDirectory(baseDir, dirSecurity);
170 #endif
171 #else
172 Directory.CreateDirectory(baseDir, userMode);
173 #endif
174 }
175 catch (Exception e)
176 {
177 failedMsg = String.Format("Failed to create base tmpdir '{0}': {1}", baseDir, e.Message);
178 }
179
180 if (failedMsg != null)
181 {
182 string envTmp = Path.GetTempPath();
183 Warn(String.Format("Unable to use '{0}' as temporary directory, falling back to system tmp '{1}': {2}", baseDir, envTmp, failedMsg));
184 baseDir = envTmp;
185 }
186 else
187 {
188 string currentUser = Environment.UserName;
189 string warnMsg = String.Format("Module remote_tmp {0} did not exist and was created with FullControl to {1}, ", baseDir, currentUser);
190 warnMsg += "this may cause issues when running as another user. To avoid this, create the remote_tmp dir with the correct permissions manually";
191 Warn(warnMsg);
192 }
193 }
194
195 string dateTime = DateTime.Now.ToFileTime().ToString();
196 string dirName = String.Format("ansible-moduletmp-{0}-{1}-{2}", dateTime, System.Diagnostics.Process.GetCurrentProcess().Id,
197 new Random().Next(0, int.MaxValue));
198 string newTmpdir = Path.Combine(baseDir, dirName);
199 #if WINDOWS
200 #if CORECLR
201 FileSystemAclExtensions.CreateDirectory(dirSecurity, newTmpdir);
202 #else
203 Directory.CreateDirectory(newTmpdir, dirSecurity);
204 #endif
205 #else
206 Directory.CreateDirectory(newTmpdir, userMode);
207 #endif
208 tmpdir = newTmpdir;
209
210 if (!KeepRemoteFiles)
211 cleanupFiles.Add(tmpdir);
212 }
213 return tmpdir;
214 }
215 }
216
217 public AnsibleModule(string[] args, IDictionary argumentSpec, IDictionary[] fragments = null)
218 {
219 // NoLog is not set yet, we cannot rely on FailJson to sanitize the output
220 // Do the minimum amount to get this running before we actually parse the params
221 Dictionary<string, string> aliases = new Dictionary<string, string>();
222 try
223 {
224 ValidateArgumentSpec(argumentSpec);
225
226 // Merge the fragments if present into the main arg spec.
227 if (fragments != null)
228 {
229 foreach (IDictionary fragment in fragments)
230 {
231 ValidateArgumentSpec(fragment);
232 MergeFragmentSpec(argumentSpec, fragment);
233 }
234 }
235
236 // Used by ansible-test to retrieve the module argument spec, not designed for public use.
237 if (_DebugArgSpec)
238 {
239 // Cannot call exit here because it will be caught with the catch (Exception e) below. Instead
240 // just throw a new exception with a specific message and the exception block will handle it.
241 ScriptBlock.Create("Set-Variable -Name ansibleTestArgSpec -Value $args[0] -Scope Global"
242 ).Invoke(argumentSpec);
243 throw new Exception("ansible-test validate-modules check");
244 }
245
246 // Now make sure all the metadata keys are set to their defaults, this must be done after we've
247 // potentially output the arg spec for ansible-test.
248 SetArgumentSpecDefaults(argumentSpec);
249
250 Params = GetParams(args);
251 aliases = GetAliases(argumentSpec, Params);
252 SetNoLogValues(argumentSpec, Params);
253 }
254 catch (Exception e)
255 {
256 if (e.Message == "ansible-test validate-modules check")
257 Exit(0);
258
259 Result["exception"] = e.ToString();
260 FailJson(string.Format("internal error: {0}", e.Message));
261 }
262
263 // Initialise public properties to the defaults before we parse the actual inputs
264 CheckMode = false;
265 DebugMode = false;
266 DiffMode = false;
267 KeepRemoteFiles = false;
268 ModuleName = "undefined win module";
269 TargetLogInfo = "";
270 NoLog = (bool)argumentSpec["no_log"];
271 Verbosity = 0;
272 AppDomain.CurrentDomain.ProcessExit += CleanupFiles;
273
274 List<string> legalInputs = passVars.Keys.Select(v => "_ansible_" + v).ToList();
275 legalInputs.AddRange(((IDictionary)argumentSpec["options"]).Keys.Cast<string>().ToList());
276 legalInputs.AddRange(aliases.Keys.Cast<string>().ToList());
277 CheckArguments(argumentSpec, Params, legalInputs);
278
279 // Set a Ansible friendly invocation value in the result object
280 if (injectInvocation) {
281 Dictionary<string, object> invocation = new Dictionary<string, object>() { { "module_args", Params } };
282 Result["invocation"] = invocation;
283 }
284
285 if (!NoLog)
286 LogEvent(String.Format("Invoked with:\r\n {0}", FormatLogData(GetLogInvocationData(argumentSpec, Params), 2)));
287 }
288
289 public static AnsibleModule Create(string[] args, IDictionary argumentSpec, IDictionary[] fragments = null)
290 {
291 return new AnsibleModule(args, argumentSpec, fragments);
292 }
293
294 public void Debug(string message)
295 {
296 if (DebugMode)
297 LogEvent(String.Format("[DEBUG] {0}", message));
298 }
299
300 public void Deprecate(string message, string version)
301 {
302 Deprecate(message, version, null);
303 }
304
305 public void Deprecate(string message, string version, string collectionName)
306 {
307 deprecations.Add(new Dictionary<string, string>() {
308 { "msg", message }, { "version", version }, { "collection_name", collectionName } });
309 LogEvent(String.Format("[DEPRECATION WARNING] {0} {1}", message, version));
310 }
311
312 public void Deprecate(string message, DateTime date)
313 {
314 Deprecate(message, date, null);
315 }
316
317 public void Deprecate(string message, DateTime date, string collectionName)
318 {
319 string isoDate = date.ToString("yyyy-MM-dd");
320 deprecations.Add(new Dictionary<string, string>() {
321 { "msg", message }, { "date", isoDate }, { "collection_name", collectionName } });
322 LogEvent(String.Format("[DEPRECATION WARNING] {0} {1}", message, isoDate));
323 }
324
325 public void ExitJson()
326 {
327 CleanupFiles(null, null);
328 WriteLine(GetFormattedResults(Result));
329 Exit(0);
330 }
331
332 public void FailJson(string message) { FailJson(message, null, null); }
333 public void FailJson(string message, ErrorRecord psErrorRecord) { FailJson(message, psErrorRecord, null); }
334 public void FailJson(string message, Exception exception) { FailJson(message, null, exception); }
335 private void FailJson(string message, ErrorRecord psErrorRecord, Exception exception)
336 {
337 Result["failed"] = true;
338 Result["msg"] = message;
339
340 if (!Result.ContainsKey("exception") && (Verbosity > 2 || DebugMode))
341 {
342 if (psErrorRecord != null)
343 {
344 string traceback = String.Format("{0}\r\n{1}", psErrorRecord.ToString(), psErrorRecord.InvocationInfo.PositionMessage);
345 traceback += String.Format("\r\n + CategoryInfo : {0}", psErrorRecord.CategoryInfo.ToString());
346 traceback += String.Format("\r\n + FullyQualifiedErrorId : {0}", psErrorRecord.FullyQualifiedErrorId.ToString());
347 traceback += String.Format("\r\n\r\nScriptStackTrace:\r\n{0}", psErrorRecord.ScriptStackTrace);
348 Result["exception"] = traceback;
349 }
350 else if (exception != null)
351 Result["exception"] = exception.ToString();
352 }
353
354 CleanupFiles(null, null);
355 WriteLine(GetFormattedResults(Result));
356 Exit(1);
357 }
358
359 public void LogEvent(string message, EventLogEntryType logEntryType = EventLogEntryType.Information, bool sanitise = true)
360 {
361 if (NoLog)
362 return;
363
364 #if WINDOWS
365 string logSource = "Ansible";
366 bool logSourceExists = false;
367 try
368 {
369 logSourceExists = EventLog.SourceExists(logSource);
370 }
371 catch (System.Security.SecurityException) { } // non admin users may not have permission
372
373 if (!logSourceExists)
374 {
375 try
376 {
377 EventLog.CreateEventSource(logSource, "Application");
378 }
379 catch (System.Security.SecurityException)
380 {
381 // Cannot call Warn as that calls LogEvent and we get stuck in a loop
382 warnings.Add(String.Format("Access error when creating EventLog source {0}, logging to the Application source instead", logSource));
383 logSource = "Application";
384 }
385 }
386
387 if (String.IsNullOrWhiteSpace(TargetLogInfo))
388 {
389 message = String.Format("{0} - {1}", ModuleName, message);
390 }
391 else
392 {
393 message = String.Format("{0} {1} - {2}", ModuleName, TargetLogInfo, message);
394 }
395
396 if (sanitise)
397 {
398 message = SecretMasker.MaskString(message);
399 }
400
401 using (EventLog eventLog = new EventLog("Application"))
402 {
403 eventLog.Source = logSource;
404 try
405 {
406 eventLog.WriteEntry(message, logEntryType, 0);
407 }
408 catch (System.InvalidOperationException) { } // Ignore permission errors on the Application event log
409 catch (System.Exception e)
410 {
411 // Cannot call Warn as that calls LogEvent and we get stuck in a loop
412 warnings.Add(String.Format("Unknown error when creating event log entry: {0}", e.Message));
413 }
414 }
415 #else
416 // Windows Event Log is only available on Windows
417 return;
418 #endif
419 }
420
421 public void Warn(string message)
422 {
423 warnings.Add(message);
424 LogEvent(String.Format("[WARNING] {0}", message), EventLogEntryType.Warning);
425 }
426
427 public static object FromJson(string json) { return FromJson<object>(json); }
428 public static T FromJson<T>(string json)
429 {
430 #if CORECLR
431 try
432 {
433 if (typeof(T) == typeof(object) || typeof(T) == typeof(Dictionary<string, object>))
434 {
435 using (JsonDocument doc = JsonDocument.Parse(json))
436 {
437 return (T)(object)ConvertJsonElement(doc.RootElement);
438 }
439 }
440 return JsonSerializer.Deserialize<T>(json);
441 }
442 catch (JsonException e)
443 {
444 // For backwards compatibility with JavaScriptSerializer, we
445 // use ArgumentException instead.
446 throw new ArgumentException(String.Format("Failed to parse JSON: {0}", e.Message), e);
447 }
448 #else
449 JavaScriptSerializer jss = new JavaScriptSerializer();
450 jss.MaxJsonLength = int.MaxValue;
451 jss.RecursionLimit = int.MaxValue;
452 return jss.Deserialize<T>(json);
453 #endif
454 }
455
456 #if CORECLR
457 private static object ConvertJsonElement(JsonElement element)
458 {
459 switch (element.ValueKind)
460 {
461 case JsonValueKind.Object:
462 var dict = new Dictionary<string, object>();
463 foreach (JsonProperty prop in element.EnumerateObject())
464 {
465 dict[prop.Name] = ConvertJsonElement(prop.Value);
466 }
467 return dict;
468 case JsonValueKind.Array:
469 // We use ArrayList to copy JavaScriptSerializer behavior
470 var list = new ArrayList();
471 foreach (JsonElement item in element.EnumerateArray())
472 {
473 list.Add(ConvertJsonElement(item));
474 }
475 return list;
476 case JsonValueKind.String:
477 return element.GetString();
478 case JsonValueKind.Number:
479 if (element.TryGetInt32(out int i))
480 return i;
481 else if (element.TryGetInt64(out long l))
482 return l;
483 return element.GetDecimal();
484 case JsonValueKind.True:
485 return true;
486 case JsonValueKind.False:
487 return false;
488 case JsonValueKind.Null:
489 return null;
490 default:
491 throw new ArgumentException($"Unsupported JsonElement type: {element.ValueKind}");
492 }
493 }
494 #endif
495
496 public static string ToJson(object obj)
497 {
498 // Using PowerShell to serialize the JSON is preferable over the native .NET libraries as it handles
499 // PS Objects a lot better than the alternatives. In case we are debugging in Visual Studio we have a
500 // fallback to the other libraries as we won't be dealing with PowerShell objects there.
501 if (Runspace.DefaultRunspace != null)
502 {
503 PSObject rawOut = ScriptBlock.Create("ConvertTo-Json -InputObject $args[0] -Depth 99 -Compress").Invoke(obj)[0];
504 return rawOut.BaseObject as string;
505 }
506 else
507 {
508 #if CORECLR
509 return JsonSerializer.Serialize(obj);
510 #else
511 JavaScriptSerializer jss = new JavaScriptSerializer();
512 jss.MaxJsonLength = int.MaxValue;
513 jss.RecursionLimit = int.MaxValue;
514 return jss.Serialize(obj);
515 #endif
516 }
517 }
518
519 public static IDictionary GetParams(string[] args)
520 {
521 if (args.Length > 0)
522 {
523 string inputJson = File.ReadAllText(args[0]);
524 Dictionary<string, object> rawParams = FromJson<Dictionary<string, object>>(inputJson);
525 if (!rawParams.ContainsKey("ANSIBLE_MODULE_ARGS"))
526 throw new ArgumentException("Module was unable to get ANSIBLE_MODULE_ARGS value from the argument path json");
527 return (IDictionary)rawParams["ANSIBLE_MODULE_ARGS"];
528 }
529 else
530 {
531 // $complex_args is already a Hashtable, no need to waste time converting to a dictionary
532 PSObject rawArgs = ScriptBlock.Create("$complex_args").Invoke()[0];
533 return rawArgs.BaseObject as Hashtable;
534 }
535 }
536
537 public static bool ParseBool(object value)
538 {
539 if (value.GetType() == typeof(bool))
540 return (bool)value;
541
542 List<string> booleans = new List<string>();
543 booleans.AddRange(BOOLEANS_TRUE);
544 booleans.AddRange(BOOLEANS_FALSE);
545
546 string stringValue = ParseStr(value).ToLowerInvariant().Trim();
547 if (BOOLEANS_TRUE.Contains(stringValue))
548 return true;
549 else if (BOOLEANS_FALSE.Contains(stringValue))
550 return false;
551
552 string msg = String.Format("The value '{0}' is not a valid boolean. Valid booleans include: {1}",
553 stringValue, String.Join(", ", booleans));
554 throw new ArgumentException(msg);
555 }
556
557 public static Dictionary<string, object> ParseDict(object value)
558 {
559 Type valueType = value.GetType();
560 if (valueType == typeof(Dictionary<string, object>))
561 return (Dictionary<string, object>)value;
562 else if (value is IDictionary)
563 return ((IDictionary)value).Cast<DictionaryEntry>().ToDictionary(kvp => (string)kvp.Key, kvp => kvp.Value);
564 else if (valueType == typeof(string))
565 {
566 string stringValue = (string)value;
567 if (stringValue.StartsWith("{") && stringValue.EndsWith("}"))
568 return FromJson<Dictionary<string, object>>((string)value);
569 else if (stringValue.IndexOfAny(new char[1] { '=' }) != -1)
570 {
571 List<string> fields = new List<string>();
572 List<char> fieldBuffer = new List<char>();
573 char? inQuote = null;
574 bool inEscape = false;
575 string field;
576
577 foreach (char c in stringValue.ToCharArray())
578 {
579 if (inEscape)
580 {
581 fieldBuffer.Add(c);
582 inEscape = false;
583 }
584 else if (c == '\\')
585 inEscape = true;
586 else if (inQuote == null && (c == '\'' || c == '"'))
587 inQuote = c;
588 else if (inQuote != null && c == inQuote)
589 inQuote = null;
590 else if (inQuote == null && (c == ',' || c == ' '))
591 {
592 field = String.Join("", fieldBuffer);
593 if (field != "")
594 fields.Add(field);
595 fieldBuffer = new List<char>();
596 }
597 else
598 fieldBuffer.Add(c);
599 }
600
601 field = String.Join("", fieldBuffer);
602 if (field != "")
603 fields.Add(field);
604
605 return fields.Distinct().Select(i => i.Split(new[] { '=' }, 2)).ToDictionary(i => i[0], i => i.Length > 1 ? (object)i[1] : null);
606 }
607 else
608 throw new ArgumentException("string cannot be converted to a dict, must either be a JSON string or in the key=value form");
609 }
610
611 throw new ArgumentException(String.Format("{0} cannot be converted to a dict", valueType.FullName));
612 }
613
614 public static float ParseFloat(object value)
615 {
616 if (value.GetType() == typeof(float))
617 return (float)value;
618
619 string valueStr = ParseStr(value);
620 return float.Parse(valueStr);
621 }
622
623 public static int ParseInt(object value)
624 {
625 Type valueType = value.GetType();
626 if (valueType == typeof(int))
627 return (int)value;
628 else
629 return Int32.Parse(ParseStr(value));
630 }
631
632 public static string ParseJson(object value)
633 {
634 // mostly used to ensure a dict is a json string as it may
635 // have been converted on the controller side
636 Type valueType = value.GetType();
637 if (value is IDictionary)
638 return ToJson(value);
639 else if (valueType == typeof(string))
640 return (string)value;
641 else
642 throw new ArgumentException(String.Format("{0} cannot be converted to json", valueType.FullName));
643 }
644
645 public static List<object> ParseList(object value)
646 {
647 if (value == null)
648 return null;
649
650 Type valueType = value.GetType();
651 if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(List<>))
652 return (List<object>)value;
653 else if (valueType == typeof(ArrayList))
654 return ((ArrayList)value).Cast<object>().ToList();
655 else if (valueType.IsArray)
656 return ((object[])value).ToList();
657 else if (valueType == typeof(string))
658 return ((string)value).Split(',').Select(s => s.Trim()).ToList<object>();
659 else if (valueType == typeof(int) || valueType == typeof(long))
660 return new List<object>() { value };
661 else
662 throw new ArgumentException(String.Format("{0} cannot be converted to a list", valueType.FullName));
663 }
664
665 public static string ParsePath(object value)
666 {
667 string stringValue = ParseStr(value);
668
669 // do not validate, expand the env vars if it starts with \\?\ as
670 // it is a special path designed for the NT kernel to interpret
671 if (stringValue.StartsWith(@"\\?\"))
672 return stringValue;
673
674 stringValue = Environment.ExpandEnvironmentVariables(stringValue);
675 if (stringValue.IndexOfAny(Path.GetInvalidPathChars()) != -1)
676 throw new ArgumentException("string value contains invalid path characters, cannot convert to path");
677
678 // will fire an exception if it contains any invalid chars
679 Path.GetFullPath(stringValue);
680 return stringValue;
681 }
682
683 public static object ParseRaw(object value) { return value; }
684
685 public static SecurityIdentifier ParseSid(object value)
686 {
687 string stringValue = ParseStr(value);
688
689 try
690 {
691 return new SecurityIdentifier(stringValue);
692 }
693 catch (ArgumentException) { } // ignore failures string may not have been a SID
694
695 NTAccount account = new NTAccount(stringValue);
696 return (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
697 }
698
699 public static string ParseStr(object value) { return value.ToString(); }
700
701 private void ValidateArgumentSpec(IDictionary argumentSpec)
702 {
703 Dictionary<string, object> changedValues = new Dictionary<string, object>();
704 foreach (DictionaryEntry entry in argumentSpec)
705 {
706 string key = (string)entry.Key;
707
708 // validate the key is a valid argument spec key
709 if (!specDefaults.ContainsKey(key))
710 {
711 string msg = String.Format("argument spec entry contains an invalid key '{0}', valid keys: {1}",
712 key, String.Join(", ", specDefaults.Keys));
713 throw new ArgumentException(FormatOptionsContext(msg, " - "));
714 }
715
716 // ensure the value is casted to the type we expect
717 Type optionType = null;
718 if (entry.Value != null)
719 optionType = (Type)specDefaults[key][1];
720 if (optionType != null)
721 {
722 Type actualType = entry.Value.GetType();
723 bool invalid = false;
724 if (optionType.IsGenericType && optionType.GetGenericTypeDefinition() == typeof(List<>))
725 {
726 // verify the actual type is not just a single value of the list type
727 Type entryType = optionType.GetGenericArguments()[0];
728 object[] arrayElementTypes = new object[]
729 {
730 null, // ArrayList does not have an ElementType
731 entryType,
732 typeof(object), // Hope the object is actually entryType or it can at least be casted.
733 };
734
735 bool isArray = entry.Value is IList && arrayElementTypes.Contains(actualType.GetElementType());
736 if (actualType == entryType || isArray)
737 {
738 object rawArray;
739 if (isArray)
740 rawArray = entry.Value;
741 else
742 rawArray = new object[1] { entry.Value };
743
744 MethodInfo castMethod = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(entryType);
745 MethodInfo toListMethod = typeof(Enumerable).GetMethod("ToList").MakeGenericMethod(entryType);
746
747 var enumerable = castMethod.Invoke(null, new object[1] { rawArray });
748 var newList = toListMethod.Invoke(null, new object[1] { enumerable });
749 changedValues.Add(key, newList);
750 }
751 else if (actualType != optionType && !(actualType == typeof(List<object>)))
752 invalid = true;
753 }
754 else
755 invalid = actualType != optionType;
756
757 if (invalid)
758 {
759 string msg = String.Format("argument spec for '{0}' did not match expected type {1}: actual type {2}",
760 key, optionType.FullName, actualType.FullName);
761 throw new ArgumentException(FormatOptionsContext(msg, " - "));
762 }
763 }
764
765 // recursively validate the spec
766 if (key == "options" && entry.Value != null)
767 {
768 IDictionary optionsSpec = (IDictionary)entry.Value;
769 foreach (DictionaryEntry optionEntry in optionsSpec)
770 {
771 optionsContext.Add((string)optionEntry.Key);
772 IDictionary optionMeta = (IDictionary)optionEntry.Value;
773 ValidateArgumentSpec(optionMeta);
774 optionsContext.RemoveAt(optionsContext.Count - 1);
775 }
776 }
777
778 // validate the type and elements key type values are known types
779 if (key == "type" || key == "elements" && entry.Value != null)
780 {
781 Type valueType = entry.Value.GetType();
782 if (valueType == typeof(string))
783 {
784 string typeValue = (string)entry.Value;
785 if (!optionTypes.ContainsKey(typeValue))
786 {
787 string msg = String.Format("{0} '{1}' is unsupported", key, typeValue);
788 msg = String.Format("{0}. Valid types are: {1}", FormatOptionsContext(msg, " - "), String.Join(", ", optionTypes.Keys));
789 throw new ArgumentException(msg);
790 }
791 }
792 else if (!(entry.Value is Delegate))
793 {
794 string msg = String.Format("{0} must either be a string or delegate, was: {1}", key, valueType.FullName);
795 throw new ArgumentException(FormatOptionsContext(msg, " - "));
796 }
797 }
798 }
799
800 // Outside of the spec iterator, change the values that were casted above
801 foreach (KeyValuePair<string, object> changedValue in changedValues)
802 argumentSpec[changedValue.Key] = changedValue.Value;
803 }
804
805 private void MergeFragmentSpec(IDictionary argumentSpec, IDictionary fragment)
806 {
807 foreach (DictionaryEntry fragmentEntry in fragment)
808 {
809 string fragmentKey = fragmentEntry.Key.ToString();
810
811 if (argumentSpec.Contains(fragmentKey))
812 {
813 // We only want to add new list entries and merge dictionary new keys and values. Leave the other
814 // values as is in the argument spec as that takes priority over the fragment.
815 if (fragmentEntry.Value is IDictionary)
816 {
817 MergeFragmentSpec((IDictionary)argumentSpec[fragmentKey], (IDictionary)fragmentEntry.Value);
818 }
819 else if (fragmentEntry.Value is IList)
820 {
821 IList specValue = (IList)argumentSpec[fragmentKey];
822 foreach (object fragmentValue in (IList)fragmentEntry.Value)
823 specValue.Add(fragmentValue);
824 }
825 }
826 else
827 argumentSpec[fragmentKey] = fragmentEntry.Value;
828 }
829 }
830
831 private void SetArgumentSpecDefaults(IDictionary argumentSpec)
832 {
833 foreach (KeyValuePair<string, List<object>> metadataEntry in specDefaults)
834 {
835 List<object> defaults = metadataEntry.Value;
836 object defaultValue = defaults[0];
837 if (defaultValue != null && defaultValue.GetType() == typeof(Type).GetType())
838 defaultValue = Activator.CreateInstance((Type)defaultValue);
839
840 if (!argumentSpec.Contains(metadataEntry.Key))
841 argumentSpec[metadataEntry.Key] = defaultValue;
842 }
843
844 // Recursively set the defaults for any inner options.
845 foreach (DictionaryEntry entry in argumentSpec)
846 {
847 if (entry.Value == null || entry.Key.ToString() != "options")
848 continue;
849
850 IDictionary optionsSpec = (IDictionary)entry.Value;
851 foreach (DictionaryEntry optionEntry in optionsSpec)
852 {
853 optionsContext.Add((string)optionEntry.Key);
854 IDictionary optionMeta = (IDictionary)optionEntry.Value;
855 SetArgumentSpecDefaults(optionMeta);
856 optionsContext.RemoveAt(optionsContext.Count - 1);
857 }
858 }
859 }
860
861 private Dictionary<string, string> GetAliases(IDictionary argumentSpec, IDictionary parameters)
862 {
863 Dictionary<string, string> aliasResults = new Dictionary<string, string>();
864
865 foreach (DictionaryEntry entry in (IDictionary)argumentSpec["options"])
866 {
867 string k = (string)entry.Key;
868 Hashtable v = (Hashtable)entry.Value;
869
870 List<string> aliases = (List<string>)v["aliases"];
871 object defaultValue = v["default"];
872 bool required = (bool)v["required"];
873
874 if (defaultValue != null && required)
875 throw new ArgumentException(String.Format("required and default are mutually exclusive for {0}", k));
876
877 foreach (string alias in aliases)
878 {
879 aliasResults.Add(alias, k);
880 if (parameters.Contains(alias))
881 parameters[k] = parameters[alias];
882 }
883
884 List<Hashtable> deprecatedAliases = (List<Hashtable>)v["deprecated_aliases"];
885 foreach (Hashtable depInfo in deprecatedAliases)
886 {
887 foreach (string keyName in new List<string> { "name" })
888 {
889 if (!depInfo.ContainsKey(keyName))
890 {
891 string msg = String.Format("{0} is required in a deprecated_aliases entry", keyName);
892 throw new ArgumentException(FormatOptionsContext(msg, " - "));
893 }
894 }
895 if (!depInfo.ContainsKey("version") && !depInfo.ContainsKey("date"))
896 {
897 string msg = "One of version or date is required in a deprecated_aliases entry";
898 throw new ArgumentException(FormatOptionsContext(msg, " - "));
899 }
900 if (depInfo.ContainsKey("version") && depInfo.ContainsKey("date"))
901 {
902 string msg = "Only one of version or date is allowed in a deprecated_aliases entry";
903 throw new ArgumentException(FormatOptionsContext(msg, " - "));
904 }
905 if (depInfo.ContainsKey("date") && depInfo["date"].GetType() != typeof(DateTime))
906 {
907 string msg = "A deprecated_aliases date must be a DateTime object";
908 throw new ArgumentException(FormatOptionsContext(msg, " - "));
909 }
910 string collectionName = null;
911 if (depInfo.ContainsKey("collection_name"))
912 {
913 collectionName = (string)depInfo["collection_name"];
914 }
915 string aliasName = (string)depInfo["name"];
916
917 if (parameters.Contains(aliasName))
918 {
919 string msg = String.Format("Alias '{0}' is deprecated. See the module docs for more information", aliasName);
920 if (depInfo.ContainsKey("version"))
921 {
922 string depVersion = (string)depInfo["version"];
923 Deprecate(FormatOptionsContext(msg, " - "), depVersion, collectionName);
924 }
925 if (depInfo.ContainsKey("date"))
926 {
927 DateTime depDate = (DateTime)depInfo["date"];
928 Deprecate(FormatOptionsContext(msg, " - "), depDate, collectionName);
929 }
930 }
931 }
932 }
933
934 return aliasResults;
935 }
936
937 private void SetNoLogValues(IDictionary argumentSpec, IDictionary parameters)
938 {
939 foreach (DictionaryEntry entry in (IDictionary)argumentSpec["options"])
940 {
941 string k = (string)entry.Key;
942 Hashtable v = (Hashtable)entry.Value;
943
944 if ((bool)v["no_log"])
945 {
946 object noLogObject = parameters.Contains(k) ? parameters[k] : null;
947 string noLogString = noLogObject == null ? "" : noLogObject.ToString();
948 SecretMasker.RegisterSecret(noLogString);
949 }
950
951 string collectionName = null;
952 if (v.ContainsKey("removed_from_collection"))
953 {
954 collectionName = (string)v["removed_from_collection"];
955 }
956
957 object removedInVersion = v["removed_in_version"];
958 if (removedInVersion != null && parameters.Contains(k))
959 Deprecate(String.Format("Param '{0}' is deprecated. See the module docs for more information", k),
960 removedInVersion.ToString(), collectionName);
961
962 object removedAtDate = v["removed_at_date"];
963 if (removedAtDate != null && parameters.Contains(k))
964 Deprecate(String.Format("Param '{0}' is deprecated. See the module docs for more information", k),
965 (DateTime)removedAtDate, collectionName);
966 }
967 }
968
969 private void CheckArguments(IDictionary spec, IDictionary param, List<string> legalInputs)
970 {
971 // initially parse the params and check for unsupported ones and set internal vars
972 CheckUnsupportedArguments(param, legalInputs);
973
974 // Only run this check if we are at the root argument (optionsContext.Count == 0)
975 if (CheckMode && !(bool)spec["supports_check_mode"] && optionsContext.Count == 0)
976 {
977 Result["skipped"] = true; // deprecated: description='remove this skipped return', core_version='2.25'
978 Result["msg"] = String.Format("remote module ({0}) does not support check mode", ModuleName);
979 ExitJson();
980 }
981 IDictionary optionSpec = (IDictionary)spec["options"];
982
983 CheckMutuallyExclusive(param, (IList)spec["mutually_exclusive"]);
984 CheckRequiredArguments(optionSpec, param);
985
986 // set the parameter types based on the type spec value
987 foreach (DictionaryEntry entry in optionSpec)
988 {
989 string k = (string)entry.Key;
990 Hashtable v = (Hashtable)entry.Value;
991
992 object value = param.Contains(k) ? param[k] : null;
993 if (value != null)
994 {
995 // convert the current value to the wanted type
996 Delegate typeConverter;
997 string type;
998 if (v["type"].GetType() == typeof(string))
999 {
1000 type = (string)v["type"];
1001 typeConverter = optionTypes[type];
1002 }
1003 else
1004 {
1005 type = "delegate";
1006 typeConverter = (Delegate)v["type"];
1007 }
1008
1009 try
1010 {
1011 value = typeConverter.DynamicInvoke(value);
1012 param[k] = value;
1013 }
1014 catch (Exception e)
1015 {
1016 string msg = String.Format("argument for {0} is of type {1} and we were unable to convert to {2}: {3}",
1017 k, value.GetType(), type, e.InnerException.Message);
1018 FailJson(FormatOptionsContext(msg));
1019 }
1020
1021 // ensure it matches the choices if there are choices set
1022 List<string> choices = ((List<object>)v["choices"]).Select(x => x.ToString()).Cast<string>().ToList();
1023 if (choices.Count > 0)
1024 {
1025 List<string> values;
1026 string choiceMsg;
1027 if (type == "list")
1028 {
1029 values = ((List<object>)value).Select(x => x.ToString()).Cast<string>().ToList();
1030 choiceMsg = "one or more of";
1031 }
1032 else
1033 {
1034 values = new List<string>() { value.ToString() };
1035 choiceMsg = "one of";
1036 }
1037
1038 List<string> diffList = values.Except(choices, StringComparer.OrdinalIgnoreCase).ToList();
1039 List<string> caseDiffList = values.Except(choices).ToList();
1040 if (diffList.Count > 0)
1041 {
1042 string msg = String.Format("value of {0} must be {1}: {2}. Got no match for: {3}",
1043 k, choiceMsg, String.Join(", ", choices), String.Join(", ", diffList));
1044 FailJson(FormatOptionsContext(msg));
1045 }
1046 /*
1047 For now we will just silently accept case insensitive choices, uncomment this if we want to add it back in
1048 else if (caseDiffList.Count > 0)
1049 {
1050 // For backwards compatibility with Legacy.psm1 we need to be matching choices that are not case sensitive.
1051 // We will warn the user it was case insensitive and tell them this will become case sensitive in the future.
1052 string msg = String.Format(
1053 "value of {0} was a case insensitive match of {1}: {2}. Checking of choices will be case sensitive in a future Ansible release. Case insensitive matches were: {3}",
1054 k, choiceMsg, String.Join(", ", choices), String.Join(", ", caseDiffList)
1055 );
1056 Warn(FormatOptionsContext(msg));
1057 }*/
1058 }
1059 }
1060 }
1061
1062 CheckRequiredTogether(param, (IList)spec["required_together"]);
1063 CheckRequiredOneOf(param, (IList)spec["required_one_of"]);
1064 CheckRequiredIf(param, (IList)spec["required_if"]);
1065 CheckRequiredBy(param, (IDictionary)spec["required_by"]);
1066
1067 // finally ensure all missing parameters are set to null and handle sub options
1068 foreach (DictionaryEntry entry in optionSpec)
1069 {
1070 string k = (string)entry.Key;
1071 IDictionary v = (IDictionary)entry.Value;
1072
1073 if (!param.Contains(k))
1074 param[k] = null;
1075
1076 CheckSubOption(param, k, v);
1077 }
1078 }
1079
1080 private void CheckUnsupportedArguments(IDictionary param, List<string> legalInputs)
1081 {
1082 HashSet<string> unsupportedParameters = new HashSet<string>();
1083 HashSet<string> caseUnsupportedParameters = new HashSet<string>();
1084 List<string> removedParameters = new List<string>();
1085
1086 foreach (DictionaryEntry entry in param)
1087 {
1088 string paramKey = (string)entry.Key;
1089 if (!legalInputs.Contains(paramKey, StringComparer.OrdinalIgnoreCase))
1090 unsupportedParameters.Add(paramKey);
1091 else if (!legalInputs.Contains(paramKey))
1092 // For backwards compatibility we do not care about the case but we need to warn the users as this will
1093 // change in a future Ansible release.
1094 caseUnsupportedParameters.Add(paramKey);
1095 else if (paramKey.StartsWith("_ansible_"))
1096 {
1097 removedParameters.Add(paramKey);
1098 string key = paramKey.Replace("_ansible_", "");
1099 // skip setting NoLog if NoLog is already set to true (set by the module)
1100 // or there's no mapping for this key
1101 if ((key == "no_log" && NoLog == true) || (passVars[key] == null))
1102 continue;
1103
1104 object value = entry.Value;
1105 if (passBools.Contains(key))
1106 value = ParseBool(value);
1107 else if (passInts.Contains(key))
1108 value = ParseInt(value);
1109 else if (passStringArrays.Contains(key))
1110 {
1111 value = Array.ConvertAll((object[])value, ParseStr);
1112 }
1113
1114 string propertyName = passVars[key];
1115 PropertyInfo property = typeof(AnsibleModule).GetProperty(propertyName);
1116 FieldInfo field = typeof(AnsibleModule).GetField(propertyName, BindingFlags.NonPublic | BindingFlags.Instance);
1117 if (property != null)
1118 property.SetValue(this, value, null);
1119 else if (field != null)
1120 field.SetValue(this, value);
1121 else
1122 FailJson(String.Format("implementation error: unknown AnsibleModule property {0}", propertyName));
1123 }
1124 }
1125 foreach (string parameter in removedParameters)
1126 param.Remove(parameter);
1127
1128 if (unsupportedParameters.Count > 0 && !ignoreUnknownOpts)
1129 {
1130 legalInputs.RemoveAll(x => passVars.Keys.Contains(x.Replace("_ansible_", "")));
1131 IEnumerable<string> unsupportedSorted = unsupportedParameters.OrderBy(s => s, StringComparer.Ordinal);
1132 IEnumerable<string> legalInputsSorted = legalInputs.OrderBy(s => s, StringComparer.Ordinal);
1133 string msg = String.Format("Unsupported parameters for ({0}) module: {1}", ModuleName, String.Join(", ", unsupportedSorted));
1134 msg = String.Format("{0}. Supported parameters include: {1}", FormatOptionsContext(msg), String.Join(", ", legalInputsSorted));
1135 FailJson(msg);
1136 }
1137
1138 /*
1139 // Uncomment when we want to start warning users around options that are not a case sensitive match to the spec
1140 if (caseUnsupportedParameters.Count > 0)
1141 {
1142 legalInputs.RemoveAll(x => passVars.Keys.Contains(x.Replace("_ansible_", "")));
1143 string msg = String.Format("Parameters for ({0}) was a case insensitive match: {1}", ModuleName, String.Join(", ", caseUnsupportedParameters));
1144 msg = String.Format("{0}. Module options will become case sensitive in a future Ansible release. Supported parameters include: {1}",
1145 FormatOptionsContext(msg), String.Join(", ", legalInputs));
1146 Warn(msg);
1147 }*/
1148
1149 // Make sure we convert all the incorrect case params to the ones set by the module spec
1150 foreach (string key in caseUnsupportedParameters)
1151 {
1152 string correctKey = legalInputs[legalInputs.FindIndex(s => s.Equals(key, StringComparison.OrdinalIgnoreCase))];
1153 object value = param[key];
1154 param.Remove(key);
1155 param.Add(correctKey, value);
1156 }
1157 }
1158
1159 private void CheckMutuallyExclusive(IDictionary param, IList mutuallyExclusive)
1160 {
1161 if (mutuallyExclusive == null)
1162 return;
1163
1164 foreach (object check in mutuallyExclusive)
1165 {
1166 List<string> mutualCheck = ((IList)check).Cast<string>().ToList();
1167 int count = 0;
1168 foreach (string entry in mutualCheck)
1169 if (param.Contains(entry))
1170 count++;
1171
1172 if (count > 1)
1173 {
1174 string msg = String.Format("parameters are mutually exclusive: {0}", String.Join(", ", mutualCheck));
1175 FailJson(FormatOptionsContext(msg));
1176 }
1177 }
1178 }
1179
1180 private void CheckRequiredArguments(IDictionary spec, IDictionary param)
1181 {
1182 List<string> missing = new List<string>();
1183 foreach (DictionaryEntry entry in spec)
1184 {
1185 string k = (string)entry.Key;
1186 Hashtable v = (Hashtable)entry.Value;
1187
1188 // set defaults for values not already set
1189 object defaultValue = v["default"];
1190 if (defaultValue != null && !param.Contains(k))
1191 param[k] = defaultValue;
1192
1193 // check required arguments
1194 bool required = (bool)v["required"];
1195 if (required && !param.Contains(k))
1196 missing.Add(k);
1197 }
1198 if (missing.Count > 0)
1199 {
1200 string msg = String.Format("missing required arguments: {0}", String.Join(", ", missing));
1201 FailJson(FormatOptionsContext(msg));
1202 }
1203 }
1204
1205 private void CheckRequiredTogether(IDictionary param, IList requiredTogether)
1206 {
1207 if (requiredTogether == null)
1208 return;
1209
1210 foreach (object check in requiredTogether)
1211 {
1212 List<string> requiredCheck = ((IList)check).Cast<string>().ToList();
1213 List<bool> found = new List<bool>();
1214 foreach (string field in requiredCheck)
1215 if (param.Contains(field))
1216 found.Add(true);
1217 else
1218 found.Add(false);
1219
1220 if (found.Contains(true) && found.Contains(false))
1221 {
1222 string msg = String.Format("parameters are required together: {0}", String.Join(", ", requiredCheck));
1223 FailJson(FormatOptionsContext(msg));
1224 }
1225 }
1226 }
1227
1228 private void CheckRequiredOneOf(IDictionary param, IList requiredOneOf)
1229 {
1230 if (requiredOneOf == null)
1231 return;
1232
1233 foreach (object check in requiredOneOf)
1234 {
1235 List<string> requiredCheck = ((IList)check).Cast<string>().ToList();
1236 int count = 0;
1237 foreach (string field in requiredCheck)
1238 if (param.Contains(field))
1239 count++;
1240
1241 if (count == 0)
1242 {
1243 string msg = String.Format("one of the following is required: {0}", String.Join(", ", requiredCheck));
1244 FailJson(FormatOptionsContext(msg));
1245 }
1246 }
1247 }
1248
1249 private void CheckRequiredIf(IDictionary param, IList requiredIf)
1250 {
1251 if (requiredIf == null)
1252 return;
1253
1254 foreach (object check in requiredIf)
1255 {
1256 IList requiredCheck = (IList)check;
1257 List<string> missing = new List<string>();
1258 List<string> missingFields = new List<string>();
1259 int maxMissingCount = 1;
1260 bool oneRequired = false;
1261
1262 if (requiredCheck.Count < 3 && requiredCheck.Count < 4)
1263 FailJson(String.Format("internal error: invalid required_if value count of {0}, expecting 3 or 4 entries", requiredCheck.Count));
1264 else if (requiredCheck.Count == 4)
1265 oneRequired = (bool)requiredCheck[3];
1266
1267 string key = (string)requiredCheck[0];
1268 object val = requiredCheck[1];
1269 IList requirements = (IList)requiredCheck[2];
1270
1271 if (param[key] == null || ParseStr(param[key]) != ParseStr(val))
1272 continue;
1273
1274 string term = "all";
1275 if (oneRequired)
1276 {
1277 maxMissingCount = requirements.Count;
1278 term = "any";
1279 }
1280
1281 foreach (string required in requirements.Cast<string>())
1282 if (!param.Contains(required))
1283 missing.Add(required);
1284
1285 if (missing.Count >= maxMissingCount)
1286 {
1287 string msg = String.Format("{0} is {1} but {2} of the following are missing: {3}",
1288 key, val.ToString(), term, String.Join(", ", missing));
1289 FailJson(FormatOptionsContext(msg));
1290 }
1291 }
1292 }
1293
1294 private void CheckRequiredBy(IDictionary param, IDictionary requiredBy)
1295 {
1296 foreach (DictionaryEntry entry in requiredBy)
1297 {
1298 string key = (string)entry.Key;
1299 if (!param.Contains(key))
1300 continue;
1301
1302 List<string> missing = new List<string>();
1303 List<string> requires = ParseList(entry.Value).Cast<string>().ToList();
1304 foreach (string required in requires)
1305 if (!param.Contains(required))
1306 missing.Add(required);
1307
1308 if (missing.Count > 0)
1309 {
1310 string msg = String.Format("missing parameter(s) required by '{0}': {1}", key, String.Join(", ", missing));
1311 FailJson(FormatOptionsContext(msg));
1312 }
1313 }
1314 }
1315
1316 private void CheckSubOption(IDictionary param, string key, IDictionary spec)
1317 {
1318 object value = param[key];
1319
1320 string type;
1321 if (spec["type"].GetType() == typeof(string))
1322 type = (string)spec["type"];
1323 else
1324 type = "delegate";
1325
1326 string elements = null;
1327 Delegate typeConverter = null;
1328 if (spec["elements"] != null && spec["elements"].GetType() == typeof(string))
1329 {
1330 elements = (string)spec["elements"];
1331 typeConverter = optionTypes[elements];
1332 }
1333 else if (spec["elements"] != null)
1334 {
1335 elements = "delegate";
1336 typeConverter = (Delegate)spec["elements"];
1337 }
1338
1339 if (!(type == "dict" || (type == "list" && elements != null)))
1340 // either not a dict, or list with the elements set, so continue
1341 return;
1342 else if (type == "list")
1343 {
1344 // cast each list element to the type specified
1345 if (value == null)
1346 return;
1347
1348 List<object> newValue = new List<object>();
1349 foreach (object element in (List<object>)value)
1350 {
1351 if (elements == "dict")
1352 newValue.Add(ParseSubSpec(spec, element, key));
1353 else
1354 {
1355 try
1356 {
1357 object newElement = typeConverter.DynamicInvoke(element);
1358 newValue.Add(newElement);
1359 }
1360 catch (Exception e)
1361 {
1362 string msg = String.Format("argument for list entry {0} is of type {1} and we were unable to convert to {2}: {3}",
1363 key, element.GetType(), elements, e.Message);
1364 FailJson(FormatOptionsContext(msg));
1365 }
1366 }
1367 }
1368
1369 param[key] = newValue;
1370 }
1371 else
1372 param[key] = ParseSubSpec(spec, value, key);
1373 }
1374
1375 private object ParseSubSpec(IDictionary spec, object value, string context)
1376 {
1377 bool applyDefaults = (bool)spec["apply_defaults"];
1378
1379 // set entry to an empty dict if apply_defaults is set
1380 IDictionary optionsSpec = (IDictionary)spec["options"];
1381 if (applyDefaults && optionsSpec.Keys.Count > 0 && value == null)
1382 value = new Dictionary<string, object>();
1383 else if (optionsSpec.Keys.Count == 0 || value == null)
1384 return value;
1385
1386 optionsContext.Add(context);
1387 Dictionary<string, object> newValue = (Dictionary<string, object>)ParseDict(value);
1388 Dictionary<string, string> aliases = GetAliases(spec, newValue);
1389 SetNoLogValues(spec, newValue);
1390
1391 List<string> subLegalInputs = optionsSpec.Keys.Cast<string>().ToList();
1392 subLegalInputs.AddRange(aliases.Keys.Cast<string>().ToList());
1393
1394 CheckArguments(spec, newValue, subLegalInputs);
1395 optionsContext.RemoveAt(optionsContext.Count - 1);
1396 return newValue;
1397 }
1398
1399 private string GetFormattedResults(Dictionary<string, object> result)
1400 {
1401 if (injectInvocation && !result.ContainsKey("invocation"))
1402 result["invocation"] = new Dictionary<string, object>() { { "module_args", Params } };
1403
1404 if (_WrapperWarnings != null)
1405 {
1406 foreach (string warning in _WrapperWarnings)
1407 {
1408 warnings.Add(warning);
1409 }
1410 }
1411
1412 if (warnings.Count > 0)
1413 result["warnings"] = warnings;
1414
1415 if (deprecations.Count > 0)
1416 result["deprecations"] = deprecations;
1417
1418 if (Diff.Count > 0 && DiffMode)
1419 result["diff"] = Diff;
1420
1421 string[] newSecrets = SecretMasker.DrainNewSecrets().ToArray();
1422 if (newSecrets.Length > 0)
1423 {
1424 result["_ansible_new_secrets"] = newSecrets;
1425 }
1426
1427 return ToJson(result);
1428 }
1429
1430 private IDictionary GetLogInvocationData(IDictionary argumentSpec, IDictionary parameters)
1431 {
1432 // While we mask the final string we need to redact any value that
1433 // was marked as no_log in the spec in case the length was shorter
1434 // than our masking minimum. The final string is still passed
1435 // through the secret masker to ensure anything else is masked
1436 // based on our new rules.
1437 IDictionary options = (IDictionary)argumentSpec["options"];
1438 Dictionary<string, object> logData = new Dictionary<string, object>();
1439
1440 foreach (DictionaryEntry entry in parameters)
1441 {
1442 string key = (string)entry.Key;
1443 Hashtable optionSpec = options.Contains(key) ? (Hashtable)options[key] : null;
1444
1445 if (optionSpec == null)
1446 logData[key] = entry.Value;
1447 else if ((bool)optionSpec["no_log"])
1448 logData[key] = "$REDACTED$";
1449 else
1450 logData[key] = RedactLogSubOptions(optionSpec, entry.Value);
1451 }
1452
1453 return logData;
1454 }
1455
1456 private object RedactLogSubOptions(IDictionary optionSpec, object value)
1457 {
1458 // Recurse into dict and list-of-dict sub-options so their own no_log
1459 // sub-options are redacted too. Any other value is returned as-is;
1460 // the SecretMasker string pass in LogEvent is the backstop for it.
1461 if (value == null)
1462 return value;
1463
1464 string type = optionSpec["type"] as string;
1465 string elements = optionSpec["elements"] as string;
1466
1467 if (type == "dict" && value is IDictionary)
1468 return GetLogInvocationData(optionSpec, (IDictionary)value);
1469
1470 if (type == "list" && elements == "dict" && value is IList)
1471 {
1472 List<object> newValue = new List<object>();
1473 foreach (object element in (IList)value)
1474 {
1475 if (element is IDictionary)
1476 newValue.Add(GetLogInvocationData(optionSpec, (IDictionary)element));
1477 else
1478 newValue.Add(element);
1479 }
1480 return newValue;
1481 }
1482
1483 return value;
1484 }
1485
1486 private string FormatLogData(object data, int indentLevel)
1487 {
1488 if (data == null)
1489 return "$null";
1490
1491 string msg = "";
1492 if (data is IList)
1493 {
1494 string newMsg = "";
1495 foreach (object value in (IList)data)
1496 {
1497 string entryValue = FormatLogData(value, indentLevel + 2);
1498 newMsg += String.Format("\r\n{0}- {1}", new String(' ', indentLevel), entryValue);
1499 }
1500 msg += newMsg;
1501 }
1502 else if (data is IDictionary)
1503 {
1504 bool start = true;
1505 foreach (DictionaryEntry entry in (IDictionary)data)
1506 {
1507 string newMsg = FormatLogData(entry.Value, indentLevel + 2);
1508 if (!start)
1509 msg += String.Format("\r\n{0}", new String(' ', indentLevel));
1510 msg += String.Format("{0}: {1}", (string)entry.Key, newMsg);
1511 start = false;
1512 }
1513 }
1514 else
1515 msg = ParseStr(data);
1516
1517 return msg;
1518 }
1519
1520 private void CleanupFiles(object s, EventArgs ev)
1521 {
1522 foreach (string path in cleanupFiles)
1523 {
1524 try
1525 {
1526 #if WINDOWS
1527 FileCleaner.Delete(path);
1528 #else
1529 if (File.Exists(path))
1530 File.Delete(path);
1531 else if (Directory.Exists(path))
1532 Directory.Delete(path, true);
1533 #endif
1534 }
1535 catch (Exception e)
1536 {
1537 Warn(string.Format("Failure cleaning temp path '{0}': {1} {2}",
1538 path, e.GetType().Name, e.Message));
1539 }
1540 }
1541 cleanupFiles = new List<string>();
1542 }
1543
1544 private string FormatOptionsContext(string msg, string prefix = " ")
1545 {
1546 if (optionsContext.Count > 0)
1547 msg += String.Format("{0}found in {1}", prefix, String.Join(" -> ", optionsContext));
1548 return msg;
1549 }
1550
1551 [DllImport("kernel32.dll")]
1552 private static extern IntPtr GetConsoleWindow();
1553
1554 private static void ExitModule(int rc)
1555 {
1556 // When running in a Runspace Environment.Exit will kill the entire
1557 // process which is not what we want, detect if we are in a
1558 // Runspace and call a ScriptBlock with exit instead.
1559 if (Runspace.DefaultRunspace != null)
1560 ScriptBlock.Create("Set-Variable -Name LASTEXITCODE -Value $args[0] -Scope Global; exit $args[0]").Invoke(rc);
1561 else
1562 {
1563 // Used for local debugging in Visual Studio
1564 if (System.Diagnostics.Debugger.IsAttached)
1565 {
1566 Console.WriteLine("Press enter to continue...");
1567 Console.ReadLine();
1568 }
1569 Environment.Exit(rc);
1570 }
1571 }
1572
1573 private static void WriteLineModule(string line)
1574 {
1575 Console.WriteLine(line);
1576 }
1577 }
1578
1579 #if WINDOWS
1580 // Windows is tricky as AVs and other software might still
1581 // have an open handle to files causing a failure. Use a
1582 // custom deletion mechanism to remove the files/dirs.
1583 // https://github.com/ansible/ansible/pull/80247
1584 internal static class FileCleaner
1585 {
1586 private const int FileDispositionInformation = 13;
1587 private const int FileDispositionInformationEx = 64;
1588
1589 private const int ERROR_INVALID_PARAMETER = 0x00000057;
1590 private const int ERROR_DIR_NOT_EMPTY = 0x00000091;
1591
1592 private static bool? _supportsPosixDelete = null;
1593
1594 [StructLayout(LayoutKind.Sequential)]
1595 public struct IO_STATUS_BLOCK
1596 {
1597 public int Status;
1598 public IntPtr Information;
1599 }
1600
1601 [Flags()]
1602 public enum DispositionFlags : uint
1603 {
1604 FILE_DISPOSITION_DO_NOT_DELETE = 0x00000000,
1605 FILE_DISPOSITION_DELETE = 0x00000001,
1606 FILE_DISPOSITION_POSIX_SEMANTICS = 0x00000002,
1607 FILE_DISPOSITION_FORCE_IMAGE_SECTION_CHECK = 0x00000004,
1608 FILE_DISPOSITION_ON_CLOSE = 0x00000008,
1609 FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE = 0x00000010,
1610 }
1611
1612 [Flags()]
1613 public enum FileFlags : uint
1614 {
1615 FILE_FLAG_OPEN_NO_RECALL = 0x00100000,
1616 FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000,
1617 FILE_FLAG_SESSION_AWARE = 0x00800000,
1618 FILE_FLAG_POSIX_SEMANTICS = 0x01000000,
1619 FILE_FLAG_BACKUP_SEMANTICS = 0x02000000,
1620 FILE_FLAG_DELETE_ON_CLOSE = 0x04000000,
1621 FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000,
1622 FILE_FLAG_RANDOM_ACCESS = 0x10000000,
1623 FILE_FLAG_NO_BUFFERING = 0x20000000,
1624 FILE_FLAG_OVERLAPPED = 0x40000000,
1625 FILE_FLAG_WRITE_THROUGH = 0x80000000,
1626 }
1627
1628 [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
1629 private static extern SafeFileHandle CreateFileW(
1630 [MarshalAs(UnmanagedType.LPWStr)] string lpFileName,
1631 FileSystemRights dwDesiredAccess,
1632 FileShare dwShareMode,
1633 IntPtr lpSecurityAttributes,
1634 FileMode dwCreationDisposition,
1635 uint dwFlagsAndAttributes,
1636 IntPtr hTemplateFile);
1637
1638 private static SafeFileHandle CreateFile(string path, FileSystemRights access, FileShare share, FileMode mode,
1639 FileAttributes attributes, FileFlags flags)
1640 {
1641 uint flagsAndAttributes = (uint)attributes | (uint)flags;
1642 SafeFileHandle handle = CreateFileW(path, access, share, IntPtr.Zero, mode, flagsAndAttributes,
1643 IntPtr.Zero);
1644 if (handle.IsInvalid)
1645 {
1646 int errCode = Marshal.GetLastWin32Error();
1647 string msg = string.Format("CreateFileW({0}) failed 0x{1:X8}: {2}",
1648 path, errCode, new Win32Exception(errCode).Message);
1649 throw new Win32Exception(errCode, msg);
1650 }
1651
1652 return handle;
1653 }
1654
1655 [DllImport("Ntdll.dll")]
1656 private static extern int NtSetInformationFile(
1657 SafeFileHandle FileHandle,
1658 ref IO_STATUS_BLOCK IoStatusBlock,
1659 ref int FileInformation,
1660 int Length,
1661 int FileInformationClass);
1662
1663 [DllImport("Ntdll.dll")]
1664 private static extern int RtlNtStatusToDosError(
1665 int Status);
1666
1667 public static void Delete(string path)
1668 {
1669 if (File.Exists(path))
1670 {
1671 DeleteEntry(path, FileAttributes.ReadOnly);
1672 }
1673 else if (Directory.Exists(path))
1674 {
1675 Queue<DirectoryInfo> dirQueue = new Queue<DirectoryInfo>();
1676 dirQueue.Enqueue(new DirectoryInfo(path));
1677 bool nonEmptyDirs = false;
1678 HashSet<string> processedDirs = new HashSet<string>();
1679
1680 while (dirQueue.Count > 0)
1681 {
1682 DirectoryInfo currentDir = dirQueue.Dequeue();
1683
1684 bool deleteDir = true;
1685 if (processedDirs.Add(currentDir.FullName))
1686 {
1687 foreach (FileSystemInfo entry in currentDir.EnumerateFileSystemInfos())
1688 {
1689 // Tries to delete each entry. Failures are ignored
1690 // as they will be picked up when the dir is
1691 // deleted and not empty.
1692 if (entry is DirectoryInfo)
1693 {
1694 if ((entry.Attributes & FileAttributes.ReparsePoint) != 0)
1695 {
1696 // If it's a reparse point, just delete it directly.
1697 DeleteEntry(entry.FullName, entry.Attributes, ignoreFailure: true);
1698 }
1699 else
1700 {
1701 // Add the dir to the queue to delete and it will be processed next round.
1702 dirQueue.Enqueue((DirectoryInfo)entry);
1703 deleteDir = false;
1704 }
1705 }
1706 else
1707 {
1708 DeleteEntry(entry.FullName, entry.Attributes, ignoreFailure: true);
1709 }
1710 }
1711 }
1712
1713 if (deleteDir)
1714 {
1715 try
1716 {
1717 DeleteEntry(currentDir.FullName, FileAttributes.Directory);
1718 }
1719 catch (Win32Exception e)
1720 {
1721 if (e.NativeErrorCode == ERROR_DIR_NOT_EMPTY)
1722 {
1723 nonEmptyDirs = true;
1724 }
1725 else
1726 {
1727 throw;
1728 }
1729 }
1730 }
1731 else
1732 {
1733 dirQueue.Enqueue(currentDir);
1734 }
1735 }
1736
1737 if (nonEmptyDirs)
1738 {
1739 throw new IOException("Directory contains files still open by other processes");
1740 }
1741 }
1742 }
1743
1744 private static void DeleteEntry(string path, FileAttributes attr, bool ignoreFailure = false)
1745 {
1746 try
1747 {
1748 if ((attr & FileAttributes.ReadOnly) != 0)
1749 {
1750 // Windows does not allow files set with ReadOnly to be
1751 // deleted. Preemptively unset the attribute.
1752 // FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE is quite new,
1753 // look at using that flag with POSIX delete once Server 2019
1754 // is the baseline.
1755 File.SetAttributes(path, FileAttributes.Normal);
1756 }
1757
1758 // REPARSE - Only touch the symlink itself and not the target
1759 // BACKUP - Needed for dir handles, bypasses access checks for admins
1760 // DELETE_ON_CLOSE is not used as it interferes with the POSIX delete
1761 FileFlags flags = FileFlags.FILE_FLAG_OPEN_REPARSE_POINT |
1762 FileFlags.FILE_FLAG_BACKUP_SEMANTICS;
1763
1764 using (SafeFileHandle fileHandle = CreateFile(path, FileSystemRights.Delete,
1765 FileShare.ReadWrite | FileShare.Delete, FileMode.Open, FileAttributes.Normal, flags))
1766 {
1767 if (_supportsPosixDelete == null || _supportsPosixDelete == true)
1768 {
1769 // A POSIX delete will delete the filesystem entry even if
1770 // it's still opened by another process so favour that if
1771 // available.
1772 DispositionFlags deleteFlags = DispositionFlags.FILE_DISPOSITION_DELETE |
1773 DispositionFlags.FILE_DISPOSITION_POSIX_SEMANTICS;
1774
1775 SetInformationFile(fileHandle, FileDispositionInformationEx, (int)deleteFlags);
1776 if (_supportsPosixDelete == true)
1777 {
1778 return;
1779 }
1780 }
1781
1782 // FileDispositionInformation takes in a struct with only a BOOLEAN value.
1783 // Using an int will also do the same thing to set that flag to true.
1784 SetInformationFile(fileHandle, FileDispositionInformation, Int32.MaxValue);
1785 }
1786 }
1787 catch
1788 {
1789 if (!ignoreFailure)
1790 {
1791 throw;
1792 }
1793 }
1794 }
1795
1796 private static void SetInformationFile(SafeFileHandle handle, int infoClass, int value)
1797 {
1798 IO_STATUS_BLOCK ioStatusBlock = new IO_STATUS_BLOCK();
1799
1800 int ntStatus = NtSetInformationFile(handle, ref ioStatusBlock, ref value,
1801 Marshal.SizeOf(typeof(int)), infoClass);
1802
1803 if (ntStatus != 0)
1804 {
1805 int errCode = RtlNtStatusToDosError(ntStatus);
1806
1807 // The POSIX delete was added in Server 2016 (Win 10 14393/Redstone 1)
1808 // Mark this flag so we don't try again.
1809 if (infoClass == FileDispositionInformationEx && _supportsPosixDelete == null &&
1810 errCode == ERROR_INVALID_PARAMETER)
1811 {
1812 _supportsPosixDelete = false;
1813 return;
1814 }
1815
1816 string msg = string.Format("NtSetInformationFile() failed 0x{0:X8}: {1}",
1817 errCode, new Win32Exception(errCode).Message);
1818 throw new Win32Exception(errCode, msg);
1819 }
1820
1821 if (infoClass == FileDispositionInformationEx)
1822 {
1823 _supportsPosixDelete = true;
1824 }
1825 }
1826 }
1827 #endif
1828 }