// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Language;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Generic;
using Microsoft.Management.Infrastructure.Serialization;
using Microsoft.PowerShell.Commands;
using static Microsoft.PowerShell.SecureStringHelper;
namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
{
///
///
[SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes",
Justification = "Needed Internal use only")]
public static class DscRemoteOperationsClass
{
///
/// Convert Cim Instance representing Resource desired state to Powershell Class Object.
///
public static object ConvertCimInstanceToObject(Type targetType, CimInstance instance, string moduleName)
{
var className = instance.CimClass.CimSystemProperties.ClassName;
object targetObject = null;
string errorMessage;
using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
{
powerShell.AddScript("param($targetType,$moduleName) & (Microsoft.PowerShell.Core\\Get-Module $moduleName) { New-Object $targetType } ");
powerShell.AddArgument(targetType);
powerShell.AddArgument(moduleName);
Collection psExecutionResult = powerShell.Invoke();
if (psExecutionResult.Count == 1)
{
targetObject = psExecutionResult[0].BaseObject;
}
else
{
Exception innerException = null;
if (powerShell.Streams.Error != null && powerShell.Streams.Error.Count > 0)
{
innerException = powerShell.Streams.Error[0].Exception;
}
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InstantiatePSClassObjectFailed, className);
var invalidOperationException = new InvalidOperationException(errorMessage, innerException);
throw invalidOperationException;
}
}
foreach (var property in instance.CimInstanceProperties)
{
if (property.Value != null)
{
MemberInfo[] memberInfo = targetType.GetMember(property.Name, BindingFlags.Public | BindingFlags.Instance);
// verify property exists in corresponding class type
if (memberInfo == null
|| memberInfo.Length > 1
|| (memberInfo[0] is not PropertyInfo && memberInfo[0] is not FieldInfo))
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.PropertyNotDeclaredInPSClass, new object[] { property.Name, className });
var invalidOperationException = new InvalidOperationException(errorMessage);
throw invalidOperationException;
}
var member = memberInfo[0];
var memberType = (member is FieldInfo)
? ((FieldInfo)member).FieldType
: ((PropertyInfo)member).PropertyType;
object targetValue = null;
switch (property.CimType)
{
case CimType.Instance:
{
var cimPropertyInstance = property.Value as CimInstance;
if (cimPropertyInstance != null &&
cimPropertyInstance.CimClass != null &&
cimPropertyInstance.CimClass.CimSystemProperties != null &&
string.Equals(
cimPropertyInstance.CimClass.CimSystemProperties.ClassName,
"MSFT_Credential", StringComparison.OrdinalIgnoreCase))
{
targetValue = ConvertCimInstancePsCredential(moduleName, cimPropertyInstance);
}
else
{
targetValue = ConvertCimInstanceToObject(memberType, cimPropertyInstance, moduleName);
}
if (targetValue == null)
{
return null;
}
}
break;
case CimType.InstanceArray:
{
if (memberType == typeof(Hashtable))
{
targetValue = ConvertCimInstanceHashtable(moduleName, (CimInstance[])property.Value);
}
else
{
var instanceArray = (CimInstance[])property.Value;
if (!memberType.IsArray)
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.ExpectArrayTypeOfPropertyInPSClass, new object[] { property.Name, className });
var invalidOperationException = new InvalidOperationException(errorMessage);
throw invalidOperationException;
}
var elementType = memberType.GetElementType();
var targetArray = Array.CreateInstance(elementType, instanceArray.Length);
for (int i = 0; i < instanceArray.Length; i++)
{
var obj = ConvertCimInstanceToObject(elementType, instanceArray[i], moduleName);
if (obj == null)
{
return null;
}
targetArray.SetValue(obj, i);
}
targetValue = targetArray;
}
}
break;
default:
targetValue = LanguagePrimitives.ConvertTo(property.Value, memberType, CultureInfo.InvariantCulture);
break;
}
if (targetValue == null)
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.ConvertCimPropertyToObjectPropertyFailed, new object[] { property.Name, className });
var invalidOperationException = new InvalidOperationException(errorMessage);
throw invalidOperationException;
}
if (member is FieldInfo)
{
((FieldInfo)member).SetValue(targetObject, targetValue);
}
if (member is PropertyInfo)
{
((PropertyInfo)member).SetValue(targetObject, targetValue);
}
}
}
return targetObject;
}
///
/// Convert hashtable from Ciminstance to hashtable primitive type.
///
///
///
///
private static object ConvertCimInstanceHashtable(string providerName, CimInstance[] arrayInstance)
{
var result = new Hashtable();
string errorMessage;
try
{
foreach (var keyValuePair in arrayInstance)
{
var key = keyValuePair.CimInstanceProperties["Key"];
var value = keyValuePair.CimInstanceProperties["Value"];
if (key == null || value == null)
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidHashtable, providerName);
var invalidOperationException = new InvalidOperationException(errorMessage);
throw invalidOperationException;
}
result.Add(LanguagePrimitives.ConvertTo(key.Value), LanguagePrimitives.ConvertTo(value.Value));
}
}
catch (Exception exception)
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidHashtable, providerName);
var invalidOperationException = new InvalidOperationException(errorMessage, exception);
throw invalidOperationException;
}
return result;
}
///
/// Convert CIM instance to PS Credential.
///
///
///
///
private static object ConvertCimInstancePsCredential(string providerName, CimInstance propertyInstance)
{
string errorMessage;
string userName;
string plainPassWord;
try
{
userName = propertyInstance.CimInstanceProperties["UserName"].Value as string;
if (string.IsNullOrEmpty(userName))
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidUserName, providerName);
var invalidOperationException = new InvalidOperationException(errorMessage);
throw invalidOperationException;
}
}
catch (CimException exception)
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidUserName, providerName);
var invalidOperationException = new InvalidOperationException(errorMessage, exception);
throw invalidOperationException;
}
try
{
plainPassWord = propertyInstance.CimInstanceProperties["PassWord"].Value as string;
// In future we might receive password in an encrypted format. Make sure we add
// the decryption login in this method.
if (string.IsNullOrEmpty(plainPassWord))
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidPassword, providerName);
var invalidOperationException = new InvalidOperationException(errorMessage);
throw invalidOperationException;
}
}
catch (CimException exception)
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidPassword, providerName);
var invalidOperationException = new InvalidOperationException(errorMessage, exception);
throw invalidOperationException;
}
SecureString password = SecureStringHelper.FromPlainTextString(plainPassWord);
password.MakeReadOnly();
return new PSCredential(userName, password);
}
}
}
namespace Microsoft.PowerShell.DesiredStateConfiguration
{
///
/// To make it easier to specify -ConfigurationData parameter, we add an ArgumentTransformationAttribute here.
/// When the input data is of type string and is valid path to a file that can be converted to hashtable, we do
/// the conversion and return the converted value. Otherwise, we just return the input data.
///
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class ArgumentToConfigurationDataTransformationAttribute : ArgumentTransformationAttribute
{
///
/// Convert a file of ConfigurationData into a hashtable.
///
///
///
///
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData)
{
var configDataPath = inputData as string;
if (string.IsNullOrEmpty(configDataPath))
{
return inputData;
}
if (engineIntrinsics == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(engineIntrinsics));
}
return PsUtils.EvaluatePowerShellDataFileAsModuleManifest(
"ConfigurationData",
configDataPath,
engineIntrinsics.SessionState.Internal.ExecutionContext,
skipPathValidation: false);
}
}
///
///
/// Represents a communication channel to a CIM server.
///
///
/// This is the main entry point of the Microsoft.Management.Infrastructure API.
/// All CIM operations are represented as methods of this class.
///
///
internal class CimDSCParser
{
private readonly CimMofDeserializer _deserializer;
private readonly CimMofDeserializer.OnClassNeeded _onClassNeeded;
///
///
internal CimDSCParser(CimMofDeserializer.OnClassNeeded onClassNeeded)
{
_deserializer = CimMofDeserializer.Create();
_onClassNeeded = onClassNeeded;
}
///
///
internal CimDSCParser(CimMofDeserializer.OnClassNeeded onClassNeeded, Microsoft.Management.Infrastructure.Serialization.MofDeserializerSchemaValidationOption validationOptions)
{
_deserializer = CimMofDeserializer.Create();
_deserializer.SchemaValidationOption = validationOptions;
_onClassNeeded = onClassNeeded;
}
///
///
///
///
[SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "3#", Justification = "Have to return 2 things. Wrapping those 2 things in a class will result in a more, not less complexity")]
internal List ParseInstanceMof(string filePath)
{
uint offset = 0;
var buffer = GetFileContent(filePath);
try
{
var result = new List(_deserializer.DeserializeInstances(buffer, ref offset, _onClassNeeded, null));
return result;
}
catch (CimException exception)
{
PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
exception, ParserStrings.CimDeserializationError, filePath);
e.SetErrorId("CimDeserializationError");
throw e;
}
}
///
/// Read file content to byte array.
///
///
///
internal static byte[] GetFileContent(string fullFilePath)
{
if (string.IsNullOrEmpty(fullFilePath))
{
throw PSTraceSource.NewArgumentNullException(nameof(fullFilePath));
}
if (!File.Exists(fullFilePath))
{
var errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.FileNotFound, fullFilePath);
throw PSTraceSource.NewArgumentException(nameof(fullFilePath), errorMessage);
}
using (FileStream fs = File.OpenRead(fullFilePath))
{
var bytes = new byte[fs.Length];
fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
return bytes;
}
}
internal List ParseSchemaMofFileBuffer(string mof)
{
uint offset = 0;
#if UNIX
// OMI only supports UTF-8 without BOM
var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
#else
// This is what we traditionally use with Windows
// DSC asked to keep it UTF-32 for Windows
var encoding = new UnicodeEncoding();
#endif
var buffer = encoding.GetBytes(mof);
var result = new List(_deserializer.DeserializeClasses(buffer, ref offset, null, null, null, _onClassNeeded, null));
return result;
}
///
///
///
///
[SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "3#", Justification = "Have to return 2 things. Wrapping those 2 things in a class will result in a more, not less complexity")]
internal List ParseSchemaMof(string filePath)
{
uint offset = 0;
var buffer = GetFileContent(filePath);
try
{
string fileNameDefiningClass = Path.GetFileNameWithoutExtension(filePath);
int dotIndex = fileNameDefiningClass.IndexOf('.');
if (dotIndex != -1)
{
fileNameDefiningClass = fileNameDefiningClass.Substring(0, dotIndex);
}
var result = new List(_deserializer.DeserializeClasses(buffer, ref offset, null, null, null, _onClassNeeded, null));
foreach (CimClass c in result)
{
string superClassName = c.CimSuperClassName;
string className = c.CimSystemProperties.ClassName;
if ((superClassName != null) && (superClassName.Equals("OMI_BaseResource", StringComparison.OrdinalIgnoreCase)))
{
// Get the name of the file without schema.mof extension
if (!(className.Equals(fileNameDefiningClass, StringComparison.OrdinalIgnoreCase)))
{
PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
ParserStrings.ClassNameNotSameAsDefiningFile, className, fileNameDefiningClass);
throw e;
}
}
}
return result;
}
catch (CimException exception)
{
PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
exception, ParserStrings.CimDeserializationError, filePath);
e.SetErrorId("CimDeserializationError");
throw e;
}
}
///
/// Make sure that the instance conforms to the schema.
///
///
internal void ValidateInstanceText(string classText)
{
uint offset = 0;
byte[] bytes = null;
if (Platform.IsLinux || Platform.IsMacOS)
{
bytes = System.Text.Encoding.UTF8.GetBytes(classText);
}
else
{
bytes = System.Text.Encoding.Unicode.GetBytes(classText);
}
_deserializer.DeserializeInstances(bytes, ref offset, _onClassNeeded, null);
}
}
}
namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
{
///
///
[SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes",
Justification = "Needed Internal use only")]
internal class DscClassCacheEntry
{
///
/// Store the RunAs Credentials that this DSC resource will use.
///
public DSCResourceRunAsCredential DscResRunAsCred;
///
/// If we have implicitly imported this resource, we will set this field to true. This will
/// only happen to InBox resources.
///
public bool IsImportedImplicitly;
///
/// A CimClass instance for this resource.
///
public Microsoft.Management.Infrastructure.CimClass CimClassInstance;
///
/// Initializes variables with default values.
///
public DscClassCacheEntry() : this(DSCResourceRunAsCredential.Default, false, null) { }
///
/// Initializes all values.
///
///
///
///
public DscClassCacheEntry(DSCResourceRunAsCredential aDSCResourceRunAsCredential, bool aIsImportedImplicitly, Microsoft.Management.Infrastructure.CimClass aCimClassInstance)
{
DscResRunAsCred = aDSCResourceRunAsCredential;
IsImportedImplicitly = aIsImportedImplicitly;
CimClassInstance = aCimClassInstance;
}
}
///
///
[SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes",
Justification = "Needed Internal use only")]
public static class DscClassCache
{
private const string InboxDscResourceModulePath = "WindowsPowershell\\v1.0\\Modules\\PsDesiredStateConfiguration";
private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("DSC", "DSC Class Cache");
// Constants for items in the module qualified name (Module\Version\ClassName)
private const int IndexModuleName = 0;
private const int IndexModuleVersion = 1;
private const int IndexClassName = 2;
private const int IndexFriendlyName = 3;
// Create a list of classes which are not actual DSC resources similar to what we do inside PSDesiredStateConfiguration.psm1
private static readonly string[] s_hiddenResourceList =
{
"MSFT_BaseConfigurationProviderRegistration",
"MSFT_CimConfigurationProviderRegistration",
"MSFT_PSConfigurationProviderRegistration",
};
// Create a HashSet for fast lookup. According to MSDN, the time complexity of search for an element in a HashSet is O(1)
private static readonly HashSet s_hiddenResourceCache =
new(s_hiddenResourceList, StringComparer.OrdinalIgnoreCase);
// a collection to hold current importing script based resource file
// this prevent circular importing case when the script resource existing in the same module with resources it import-dscresource
private static readonly HashSet s_currentImportingScriptFiles = new(StringComparer.OrdinalIgnoreCase);
///
/// DSC class cache for this runspace.
/// Cache stores the DSCRunAsBehavior, cim class and boolean to indicate if an Inbox resource has been implicitly imported.
///
private static Dictionary ClassCache
{
get
{
t_classCache ??= new Dictionary(StringComparer.OrdinalIgnoreCase);
return t_classCache;
}
}
[ThreadStatic]
private static Dictionary t_classCache;
///
/// DSC classname to source module mapper.
///
private static Dictionary> ByClassModuleCache
{
get
{
t_byClassModuleCache ??= new Dictionary>(StringComparer.OrdinalIgnoreCase);
return t_byClassModuleCache;
}
}
[ThreadStatic]
private static Dictionary> t_byClassModuleCache;
///
/// DSC filename to defined class mapper.
///
private static Dictionary> ByFileClassCache
{
get
{
t_byFileClassCache ??= new Dictionary>(StringComparer.OrdinalIgnoreCase);
return t_byFileClassCache;
}
}
[ThreadStatic]
private static Dictionary> t_byFileClassCache;
///
/// Filenames from which we have imported script dynamic keywords.
///
private static HashSet ScriptKeywordFileCache
{
get
{
t_scriptKeywordFileCache ??= new HashSet(StringComparer.OrdinalIgnoreCase);
return t_scriptKeywordFileCache;
}
}
[ThreadStatic]
private static HashSet t_scriptKeywordFileCache;
///
/// Default ModuleName and ModuleVersion to use.
///
private static readonly Tuple s_defaultModuleInfoForResource =
new("PSDesiredStateConfiguration", new Version("1.1"));
///
/// Default ModuleName and ModuleVersion to use for meta configuration resources.
///
internal static readonly Tuple DefaultModuleInfoForMetaConfigResource =
new("PSDesiredStateConfigurationEngine", new Version("2.0"));
///
/// A set of dynamic keywords that can be used in both configuration and meta configuration.
///
internal static readonly HashSet SystemResourceNames =
new(StringComparer.OrdinalIgnoreCase) { "Node", "OMI_ConfigurationDocument" };
///
/// When this property is set to true, DSC Cache will cache multiple versions of a resource.
/// That means it will cache duplicate resource classes (class names for a resource in two different module versions are same).
/// NOTE: This property should be set to false for DSC compiler related methods/functionality, such as Import-DscResource,
/// because the Mof serializer does not support deserialization of classes with different versions.
///
[ThreadStatic]
private static bool t_cacheResourcesFromMultipleModuleVersions;
private static bool CacheResourcesFromMultipleModuleVersions
{
get
{
return t_cacheResourcesFromMultipleModuleVersions;
}
set
{
t_cacheResourcesFromMultipleModuleVersions = value;
}
}
///
/// Initialize the class cache with the default classes in $ENV:SystemDirectory\Configuration.
///
public static void Initialize()
{
Initialize(null, null);
}
///
/// Initialize the class cache with the default classes in $ENV:SystemDirectory\Configuration.
///
/// Collection of any errors encountered during initialization.
/// List of module path from where DSC PS modules will be loaded.
public static void Initialize(Collection errors, List modulePathList)
{
s_tracer.WriteLine("Initializing DSC class cache force={0}");
if (Platform.IsLinux || Platform.IsMacOS)
{
//
// Load the base schema files.
//
ClearCache();
var dscConfigurationDirectory = Environment.GetEnvironmentVariable("DSC_HOME") ??
"/etc/opt/omi/conf/dsc/configuration";
if (!Directory.Exists(dscConfigurationDirectory))
{
throw new DirectoryNotFoundException("Unable to find DSC schema store at " + dscConfigurationDirectory + ". Please ensure PS DSC for Linux is installed.");
}
var resourceBaseFile = Path.Combine(dscConfigurationDirectory, "BaseRegistration/BaseResource.schema.mof");
ImportClasses(resourceBaseFile, s_defaultModuleInfoForResource, errors);
var metaConfigFile = Path.Combine(dscConfigurationDirectory, "BaseRegistration/MSFT_DSCMetaConfiguration.mof");
ImportClasses(metaConfigFile, s_defaultModuleInfoForResource, errors);
var allResourceRoots = new string[] { dscConfigurationDirectory };
//
// Load all of the system resource schema files, searching
//
string resources;
foreach (var resourceRoot in allResourceRoots)
{
resources = Path.Combine(resourceRoot, "schema");
if (!Directory.Exists(resources))
{
continue;
}
foreach (var schemaFile in Directory.EnumerateDirectories(resources).SelectMany(static d => Directory.EnumerateFiles(d, "*.schema.mof")))
{
ImportClasses(schemaFile, s_defaultModuleInfoForResource, errors);
}
}
// Linux DSC Modules are installed to the dscConfigurationDirectory, so no need to load them.
}
else
{
// DSC SxS scenario
var configSystemPath = Utils.DefaultPowerShellAppBase;
var systemResourceRoot = Path.Combine(configSystemPath, "Configuration");
var inboxModulePath = "Modules\\PSDesiredStateConfiguration";
if (!Directory.Exists(systemResourceRoot))
{
configSystemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
systemResourceRoot = Path.Combine(configSystemPath, "Configuration");
inboxModulePath = InboxDscResourceModulePath;
}
var programFilesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
Debug.Assert(programFilesDirectory != null, "Program Files environment variable does not exist!");
var customResourceRoot = Path.Combine(programFilesDirectory, "WindowsPowerShell\\Configuration");
Debug.Assert(Directory.Exists(customResourceRoot), "%ProgramFiles%\\WindowsPowerShell\\Configuration Directory does not exist");
var allResourceRoots = new string[] { systemResourceRoot, customResourceRoot };
//
// Load the base schema files.
//
ClearCache();
var resourceBaseFile = Path.Combine(systemResourceRoot, "BaseRegistration\\BaseResource.schema.mof");
ImportClasses(resourceBaseFile, s_defaultModuleInfoForResource, errors);
var metaConfigFile = Path.Combine(systemResourceRoot, "BaseRegistration\\MSFT_DSCMetaConfiguration.mof");
ImportClasses(metaConfigFile, s_defaultModuleInfoForResource, errors);
var metaConfigExtensionFile = Path.Combine(systemResourceRoot, "BaseRegistration\\MSFT_MetaConfigurationExtensionClasses.schema.mof");
ImportClasses(metaConfigExtensionFile, DefaultModuleInfoForMetaConfigResource, errors);
//
// Load all of the system resource schema files, searching
//
string resources;
foreach (var resourceRoot in allResourceRoots)
{
resources = Path.Combine(resourceRoot, "Schema");
if (!Directory.Exists(resources))
{
continue;
}
foreach (var schemaFile in Directory.EnumerateDirectories(resources).SelectMany(static d => Directory.EnumerateFiles(d, "*.schema.mof")))
{
ImportClasses(schemaFile, s_defaultModuleInfoForResource, errors);
}
}
// Load Regular and DSC PS modules
bool importInBoxResourcesImplicitly = false;
List modulePaths = new();
if (modulePathList == null || modulePathList.Count == 0)
{
modulePaths.Add(Path.Combine(configSystemPath, inboxModulePath));
importInBoxResourcesImplicitly = true;
}
else
{
foreach (string moduleFolderPath in modulePathList)
{
if (!Directory.Exists(moduleFolderPath))
{
continue;
}
foreach (string moduleDir in Directory.EnumerateDirectories(moduleFolderPath))
{
modulePaths.Add(moduleDir);
}
}
}
LoadDSCResourceIntoCache(errors, modulePaths, importInBoxResourcesImplicitly);
}
}
///
/// Load DSC resources into Cache from moduleFolderPath.
///
/// Collection of any errors encountered during initialization.
/// Module path from where DSC PS modules will be loaded.
///
/// if module is inbox.
///
private static void LoadDSCResourceIntoCache(Collection errors, List modulePathList, bool importInBoxResourcesImplicitly)
{
foreach (string moduleDir in modulePathList)
{
if (!Directory.Exists(moduleDir))
{
continue;
}
var dscResourcesPath = Path.Combine(moduleDir, "DscResources");
if (Directory.Exists(dscResourcesPath))
{
foreach (string resourceDir in Directory.EnumerateDirectories(dscResourcesPath))
{
IEnumerable schemaFiles = Directory.EnumerateFiles(resourceDir, "*.schema.mof");
if (!schemaFiles.Any())
{
continue;
}
Tuple moduleInfo = GetModuleInfoHelper(moduleDir, importInBoxResourcesImplicitly, isPsProviderModule: false);
if (moduleInfo == null)
{
continue;
}
foreach (string schemaFile in schemaFiles)
{
ImportClasses(schemaFile, moduleInfo, errors, importInBoxResourcesImplicitly);
}
}
}
}
}
///
/// Get the module name and module version.
///
///
/// Path to the module folder
///
///
/// if module is inbox and we are importing resources implicitly
///
///
/// Indicate a internal DSC module
///
///
private static Tuple GetModuleInfoHelper(string moduleFolderPath, bool importInBoxResourcesImplicitly, bool isPsProviderModule)
{
string moduleName = "PsDesiredStateConfiguration";
if (!importInBoxResourcesImplicitly)
{
moduleName = Path.GetFileName(moduleFolderPath);
}
string manifestPath = Path.Combine(moduleFolderPath, moduleName + ".psd1");
s_tracer.WriteLine("DSC GetModuleVersion: Try retrieving module version information from file: {0}.", manifestPath);
if (!File.Exists(manifestPath))
{
if (isPsProviderModule)
{
// Some internal PSProviders do not come with a .psd1 file, such
// as MSFT_LogResource. We don't report error in this case.
return new Tuple(moduleName, new Version("1.0"));
}
else
{
s_tracer.WriteLine("DSC GetModuleVersion: Manifest file '{0}' not exist.", manifestPath);
return null;
}
}
try
{
Hashtable dataFileSetting =
PsUtils.GetModuleManifestProperties(
manifestPath,
PsUtils.ManifestModuleVersionPropertyName);
object versionValue = dataFileSetting["ModuleVersion"];
if (versionValue != null)
{
Version moduleVersion;
if (LanguagePrimitives.TryConvertTo(versionValue, out moduleVersion))
{
return new Tuple(moduleName, moduleVersion);
}
else
{
s_tracer.WriteLine(
"DSC GetModuleVersion: ModuleVersion value '{0}' cannot be converted to System.Version. Skip the module '{1}'.",
versionValue, moduleName);
}
}
else
{
s_tracer.WriteLine(
"DSC GetModuleVersion: Manifest file '{0}' does not contain ModuleVersion. Skip the module '{1}'.",
manifestPath, moduleName);
}
}
catch (PSInvalidOperationException ex)
{
s_tracer.WriteLine(
"DSC GetModuleVersion: Error evaluating module manifest file '{0}', with error '{1}'. Skip the module '{2}'.",
manifestPath, ex, moduleName);
}
return null;
}
// Callback implementation...
private static CimClass MyClassCallback(string serverName, string namespaceName, string className)
{
foreach (KeyValuePair cimClass in ClassCache)
{
string cachedClassName = cimClass.Key.Split('\\')[IndexClassName];
if (string.Equals(cachedClassName, className, StringComparison.OrdinalIgnoreCase))
{
return cimClass.Value.CimClassInstance;
}
}
return null;
}
///
/// Reads CIM MOF schema file and returns classes defined in it.
/// This is used MOF->PSClass conversion tool.
///
///
/// Path to CIM MOF schema file for reading.
///
/// List of classes from MOF schema file.
public static List ReadCimSchemaMof(string mofPath)
{
var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback);
return parser.ParseSchemaMof(mofPath);
}
///
/// Import CIM classes from the given file.
///
///
///
///
///
///
public static List ImportClasses(string path, Tuple moduleInfo, Collection errors, bool importInBoxResourcesImplicitly = false)
{
if (string.IsNullOrEmpty(path))
{
throw PSTraceSource.NewArgumentNullException(nameof(path));
}
s_tracer.WriteLine("DSC ClassCache: importing file: {0}", path);
var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback);
List classes = null;
try
{
classes = parser.ParseSchemaMof(path);
}
catch (PSInvalidOperationException e)
{
// Ignore modules with invalid schemas.
s_tracer.WriteLine("DSC ClassCache: Error importing file '{0}', with error '{1}'. Skipping file.", path, e);
errors?.Add(e);
}
if (classes != null)
{
foreach (var c in classes)
{
// Only add the class once...
var className = c.CimSystemProperties.ClassName;
string alias = GetFriendlyName(c);
var friendlyName = string.IsNullOrEmpty(alias) ? className : alias;
string moduleQualifiedResourceName = GetModuleQualifiedResourceName(moduleInfo.Item1, moduleInfo.Item2.ToString(), className, friendlyName);
DscClassCacheEntry cimClassInfo;
if (ClassCache.TryGetValue(moduleQualifiedResourceName, out cimClassInfo))
{
CimClass cimClass = cimClassInfo.CimClassInstance;
// If this is a nested object and we already have exactly same nested object, we will
// allow sharing of nested objects.
if (!IsSameNestedObject(cimClass, c))
{
var files = string.Join(',', GetFileDefiningClass(className));
PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
ParserStrings.DuplicateCimClassDefinition, className, path, files);
e.SetErrorId("DuplicateCimClassDefinition");
errors?.Add(e);
}
}
if (s_hiddenResourceCache.Contains(className))
{
continue;
}
if (!CacheResourcesFromMultipleModuleVersions)
{
// Find & remove the previous version of the resource.
List> resourceList = FindResourceInCache(moduleInfo.Item1, className, friendlyName);
if (resourceList.Count > 0 && !string.IsNullOrEmpty(resourceList[0].Key))
{
ClassCache.Remove(resourceList[0].Key);
// keyword is already defined and it is a Inbox resource, remove it
if (DynamicKeyword.ContainsKeyword(friendlyName) && resourceList[0].Value.IsImportedImplicitly)
{
DynamicKeyword.RemoveKeyword(friendlyName);
}
}
}
ClassCache[moduleQualifiedResourceName] = new DscClassCacheEntry(DSCResourceRunAsCredential.Default, importInBoxResourcesImplicitly, c);
ByClassModuleCache[className] = moduleInfo;
}
var sb = new System.Text.StringBuilder();
foreach (var c in classes)
{
sb.Append(c.CimSystemProperties.ClassName);
sb.Append(',');
}
s_tracer.WriteLine("DSC ClassCache: loading file '{0}' added the following classes to the cache: {1}", path, sb.ToString());
}
else
{
s_tracer.WriteLine("DSC ClassCache: loading file '{0}' added no classes to the cache.");
}
ByFileClassCache[path] = classes;
return classes;
}
///
/// Get text from SecureString.
///
/// Value of SecureString.
/// Decoded string.
public static string GetStringFromSecureString(SecureString value)
{
string passwordValueToAdd = string.Empty;
if (value != null)
{
IntPtr ptr = Marshal.SecureStringToCoTaskMemUnicode(value);
passwordValueToAdd = Marshal.PtrToStringUni(ptr);
Marshal.ZeroFreeCoTaskMemUnicode(ptr);
}
return passwordValueToAdd;
}
///
/// Clear out the existing collection of CIM classes and associated keywords.
///
public static void ClearCache()
{
s_tracer.WriteLine("DSC class: clearing the cache and associated keywords.");
ClassCache.Clear();
ByClassModuleCache.Clear();
ByFileClassCache.Clear();
ScriptKeywordFileCache.Clear();
CacheResourcesFromMultipleModuleVersions = false;
}
///
/// Returns module qualified resource name in "Module\Version\Class" format.
///
///
///
///
///
///
private static string GetModuleQualifiedResourceName(string moduleName, string moduleVersion, string className, string resourceName)
{
return string.Create(CultureInfo.InvariantCulture, $"{moduleName}\\{moduleVersion}\\{className}\\{resourceName}");
}
///
/// Finds resources in the that which matches the specified class and module name.
///
/// Module name.
/// Resource type name.
/// Resource friendly name.
/// List of found resources in the form of Dictionary{moduleQualifiedName, cimClass}, otherwise empty list.
private static List> FindResourceInCache(string moduleName, string className, string resourceName)
{
return (from cacheEntry in ClassCache
let splittedName = cacheEntry.Key.Split('\\')
let cachedClassName = splittedName[IndexClassName]
let cachedModuleName = splittedName[IndexModuleName]
let cachedResourceName = splittedName[IndexFriendlyName]
where (string.Equals(cachedResourceName, resourceName, StringComparison.OrdinalIgnoreCase)
|| (string.Equals(cachedClassName, className, StringComparison.OrdinalIgnoreCase)
&& string.Equals(cachedModuleName, moduleName, StringComparison.OrdinalIgnoreCase)))
select cacheEntry).ToList();
}
///
///
///
private static List GetCachedClasses()
{
return ClassCache.Values.ToList();
}
///
/// Find cached cim classes defined under specified module.
///
///
/// List of cached cim classes.
public static List GetCachedClassesForModule(PSModuleInfo module)
{
List cachedClasses = new();
var moduleQualifiedName = string.Create(CultureInfo.InvariantCulture, $"{module.Name}\\{module.Version}");
foreach (var dscClassCacheEntry in ClassCache)
{
if (dscClassCacheEntry.Key.StartsWith(moduleQualifiedName, StringComparison.OrdinalIgnoreCase))
{
cachedClasses.Add(dscClassCacheEntry.Value.CimClassInstance);
}
}
return cachedClasses;
}
///
/// Get the file that defined this class.
///
///
///
public static List GetFileDefiningClass(string className)
{
List files = new();
foreach (var pair in ByFileClassCache)
{
var file = pair.Key;
var classList = pair.Value;
if (classList != null && classList.Find((CimClass c) => string.Equals(c.CimSystemProperties.ClassName, className, StringComparison.OrdinalIgnoreCase)) != null)
{
files.Add(file);
}
}
return files;
}
///
/// Get a list of files from which classes have been loaded.
///
///
public static string[] GetLoadedFiles()
{
return ByFileClassCache.Keys.ToArray();
}
///
/// Returns the classes that we loaded from the specified file name.
///
///
///
public static List GetCachedClassByFileName(string fileName)
{
if (string.IsNullOrWhiteSpace(fileName))
{
throw PSTraceSource.NewArgumentNullException(nameof(fileName));
}
List listCimClass;
ByFileClassCache.TryGetValue(fileName, out listCimClass);
return listCimClass;
}
///
/// Returns the classes associated with the specified module name.
/// Per PowerShell the module name is the base name of the schema file.
///
///
///
public static List GetCachedClassByModuleName(string moduleName)
{
if (string.IsNullOrWhiteSpace(moduleName))
{
throw PSTraceSource.NewArgumentNullException(nameof(moduleName));
}
var moduleFileName = moduleName + ".schema.mof";
return (from filename in ByFileClassCache.Keys where string.Equals(Path.GetFileName(filename), moduleFileName, StringComparison.OrdinalIgnoreCase) select GetCachedClassByFileName(filename)).FirstOrDefault();
}
///
/// Routine used to load a set of CIM instances from a .mof file using the
/// current set of cached classes for schema validation.
///
/// The file to load the classes from.
///
public static List ImportInstances(string path)
{
if (string.IsNullOrEmpty(path))
{
throw PSTraceSource.NewArgumentNullException(nameof(path));
}
var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback);
return parser.ParseInstanceMof(path);
}
///
/// Routine used to load a set of CIM instances from a .mof file using the
/// current set of cached classes for schema validation.
///
///
///
///
public static List ImportInstances(string path, int schemaValidationOption)
{
if (string.IsNullOrEmpty(path))
{
throw PSTraceSource.NewArgumentNullException(nameof(path));
}
if (schemaValidationOption < (int)Microsoft.Management.Infrastructure.Serialization.MofDeserializerSchemaValidationOption.Default ||
schemaValidationOption > (int)Microsoft.Management.Infrastructure.Serialization.MofDeserializerSchemaValidationOption.Ignore)
{
throw new IndexOutOfRangeException("schemaValidationOption");
}
var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback, (Microsoft.Management.Infrastructure.Serialization.MofDeserializerSchemaValidationOption)schemaValidationOption);
return parser.ParseInstanceMof(path);
}
///
/// A routine that validates a string containing MOF instances against the
/// current set of cached classes.
///
///
public static void ValidateInstanceText(string instanceText)
{
if (string.IsNullOrEmpty(instanceText))
{
throw PSTraceSource.NewArgumentNullException(nameof(instanceText));
}
var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback);
parser.ValidateInstanceText(instanceText);
}
private static string GetFriendlyName(CimClass cimClass)
{
try
{
var aliasQualifier = cimClass.CimClassQualifiers["FriendlyName"];
if (aliasQualifier != null)
{
return aliasQualifier.Value as string;
}
}
catch (Microsoft.Management.Infrastructure.CimException)
{
// exception means no DSCAlias
}
return null;
}
///
/// Method to get the cached classes in the form of DynamicKeyword.
///
public static Collection GetCachedKeywords()
{
Collection keywords = new();
foreach (KeyValuePair cachedClass in ClassCache)
{
string[] splittedName = cachedClass.Key.Split('\\');
string moduleName = splittedName[IndexModuleName];
string moduleVersion = splittedName[IndexModuleVersion];
var keyword = CreateKeywordFromCimClass(moduleName, Version.Parse(moduleVersion), cachedClass.Value.CimClassInstance, null, cachedClass.Value.DscResRunAsCred);
if (keyword != null)
{
keywords.Add(keyword);
}
}
return keywords;
}
///
/// A method to generate a keyword from a CIM class object and register it to DynamicKeyword table.
///
///
///
///
/// If true, don't define the keywords, just create the functions.
/// To Specify RunAsBehavior of the class.
private static void CreateAndRegisterKeywordFromCimClass(string moduleName, Version moduleVersion, Microsoft.Management.Infrastructure.CimClass cimClass, Dictionary functionsToDefine, DSCResourceRunAsCredential runAsBehavior)
{
var keyword = CreateKeywordFromCimClass(moduleName, moduleVersion, cimClass, functionsToDefine, runAsBehavior);
if (keyword == null)
{
return;
}
// keyword is already defined and we don't allow redefine it
if (!CacheResourcesFromMultipleModuleVersions && DynamicKeyword.ContainsKeyword(keyword.Keyword))
{
var oldKeyword = DynamicKeyword.GetKeyword(keyword.Keyword);
if (oldKeyword.ImplementingModule == null ||
!oldKeyword.ImplementingModule.Equals(moduleName, StringComparison.OrdinalIgnoreCase) || oldKeyword.ImplementingModuleVersion != moduleVersion)
{
var e = PSTraceSource.NewInvalidOperationException(ParserStrings.DuplicateKeywordDefinition, keyword.Keyword);
e.SetErrorId("DuplicateKeywordDefinition");
throw e;
}
}
// Add the dynamic keyword to the table
DynamicKeyword.AddKeyword(keyword);
// And now define the driver functions in the current scope...
if (functionsToDefine != null)
{
functionsToDefine[moduleName + "\\" + keyword.Keyword] = CimKeywordImplementationFunction;
}
}
///
/// A method to generate a keyword from a CIM class object. This is used for DSC.
///
///
///
///
/// If true, don't define the keywords, just create the functions.
/// To specify RunAs behavior of the class.
private static DynamicKeyword CreateKeywordFromCimClass(string moduleName, Version moduleVersion, Microsoft.Management.Infrastructure.CimClass cimClass, Dictionary functionsToDefine, DSCResourceRunAsCredential runAsBehavior)
{
var resourceName = cimClass.CimSystemProperties.ClassName;
string alias = GetFriendlyName(cimClass);
var keywordString = string.IsNullOrEmpty(alias) ? resourceName : alias;
//
// Skip all of the base, meta, registration and other classes that are not intended to be used directly by a script author
//
if (keywordString.StartsWith("OMI_Base", StringComparison.OrdinalIgnoreCase) ||
(keywordString.StartsWith("OMI_", StringComparison.OrdinalIgnoreCase) && keywordString.IndexOf("Registration", 4, StringComparison.OrdinalIgnoreCase) >= 0))
{
return null;
}
var keyword = new DynamicKeyword()
{
BodyMode = DynamicKeywordBodyMode.Hashtable,
Keyword = keywordString,
ResourceName = resourceName,
ImplementingModule = moduleName,
ImplementingModuleVersion = moduleVersion,
SemanticCheck = CheckMandatoryPropertiesPresent
};
// If it's one of reserved dynamic keyword, mark it
if (IsReservedDynamicKeyword(keywordString))
{
keyword.IsReservedKeyword = true;
}
// see if it's a resource type i.e. it inherits from OMI_BaseResource
bool isResourceType = false;
for (var classToCheck = cimClass; !string.IsNullOrEmpty(classToCheck.CimSuperClassName); classToCheck = classToCheck.CimSuperClass)
{
if (string.Equals("OMI_BaseResource", classToCheck.CimSuperClassName, StringComparison.OrdinalIgnoreCase) || string.Equals("OMI_MetaConfigurationResource", classToCheck.CimSuperClassName, StringComparison.OrdinalIgnoreCase))
{
isResourceType = true;
break;
}
}
// If it's a resource type, then a resource name is required.
keyword.NameMode = isResourceType ? DynamicKeywordNameMode.NameRequired : DynamicKeywordNameMode.NoName;
//
// Add the settable properties to the keyword object
//
foreach (var prop in cimClass.CimClassProperties)
{
// If the property is marked as readonly, skip it...
if ((prop.Flags & Microsoft.Management.Infrastructure.CimFlags.ReadOnly) == Microsoft.Management.Infrastructure.CimFlags.ReadOnly)
{
continue;
}
try
{
// If the property has the Read qualifier, also skip it.
if (prop.Qualifiers["Read"] != null)
{
continue;
}
}
catch (Microsoft.Management.Infrastructure.CimException)
{
// Cim exception means Read wasn't found so continue...
}
// If it's one of our magic properties, skip it
if (IsMagicProperty(prop.Name))
{
continue;
}
if (runAsBehavior == DSCResourceRunAsCredential.NotSupported)
{
if (string.Equals(prop.Name, "PsDscRunAsCredential", StringComparison.OrdinalIgnoreCase))
{
// skip adding PsDscRunAsCredential to the dynamic word for the dsc resource.
continue;
}
}
// If it's one of our reserved properties, save it for error reporting
if (IsReservedProperty(prop.Name))
{
keyword.HasReservedProperties = true;
continue;
}
// Otherwise, add it to the Keyword List.
var keyProp = new System.Management.Automation.Language.DynamicKeywordProperty();
keyProp.Name = prop.Name;
// Set the mandatory flag if appropriate
if ((prop.Flags & Microsoft.Management.Infrastructure.CimFlags.Key) == Microsoft.Management.Infrastructure.CimFlags.Key)
{
keyProp.Mandatory = true;
keyProp.IsKey = true;
}
// Copy the type name string. If it's an embedded instance, need to grab it from the ReferenceClassName
bool referenceClassNameIsNullOrEmpty = string.IsNullOrEmpty(prop.ReferenceClassName);
if (prop.CimType == CimType.Instance && !referenceClassNameIsNullOrEmpty)
{
keyProp.TypeConstraint = prop.ReferenceClassName;
}
else if (prop.CimType == CimType.InstanceArray && !referenceClassNameIsNullOrEmpty)
{
keyProp.TypeConstraint = prop.ReferenceClassName + "[]";
}
else
{
keyProp.TypeConstraint = prop.CimType.ToString();
}
string[] valueMap = null;
foreach (var qualifier in prop.Qualifiers)
{
// Check to see if there is a Values attribute and save the list of allowed values if so.
if (string.Equals(qualifier.Name, "Values", StringComparison.OrdinalIgnoreCase) && qualifier.CimType == Microsoft.Management.Infrastructure.CimType.StringArray)
{
keyProp.Values.AddRange((string[])qualifier.Value);
}
// Check to see if there is a ValueMap attribute and save the list of allowed values if so.
if (string.Equals(qualifier.Name, "ValueMap", StringComparison.OrdinalIgnoreCase) && qualifier.CimType == Microsoft.Management.Infrastructure.CimType.StringArray)
{
valueMap = (string[])qualifier.Value;
}
// Check to see if this property has the Required qualifier associated with it.
if (string.Equals(qualifier.Name, "Required", StringComparison.OrdinalIgnoreCase) &&
qualifier.CimType == Microsoft.Management.Infrastructure.CimType.Boolean &&
(bool)qualifier.Value)
{
keyProp.Mandatory = true;
}
// set the property to mandatory is specified for the resource.
if (runAsBehavior == DSCResourceRunAsCredential.Mandatory)
{
if (string.Equals(prop.Name, "PsDscRunAsCredential", StringComparison.OrdinalIgnoreCase))
{
keyProp.Mandatory = true;
}
}
}
if (valueMap != null && keyProp.Values.Count > 0)
{
if (valueMap.Length != keyProp.Values.Count)
{
s_tracer.WriteLine(
"DSC CreateDynamicKeywordFromClass: the count of values for qualifier 'Values' and 'ValueMap' doesn't match. count of 'Values': {0}, count of 'ValueMap': {1}. Skip the keyword '{2}'.",
keyProp.Values.Count, valueMap.Length, keyword.Keyword);
return null;
}
for (int index = 0; index < valueMap.Length; index++)
{
string key = keyProp.Values[index];
string value = valueMap[index];
if (keyProp.ValueMap.ContainsKey(key))
{
s_tracer.WriteLine(
"DSC CreateDynamicKeywordFromClass: same string value '{0}' appears more than once in qualifier 'Values'. Skip the keyword '{1}'.",
key, keyword.Keyword);
return null;
}
keyProp.ValueMap.Add(key, value);
}
}
keyword.Properties.Add(prop.Name, keyProp);
}
// update specific keyword with range constraints
UpdateKnownRestriction(keyword);
return keyword;
static bool IsMagicProperty(string propertyName) =>
string.Equals(propertyName, "ResourceId", StringComparison.OrdinalIgnoreCase) ||
string.Equals(propertyName, "SourceInfo", StringComparison.OrdinalIgnoreCase) ||
string.Equals(propertyName, "ModuleName", StringComparison.OrdinalIgnoreCase) ||
string.Equals(propertyName, "ModuleVersion", StringComparison.OrdinalIgnoreCase) ||
string.Equals(propertyName, "ConfigurationName", StringComparison.OrdinalIgnoreCase);
static bool IsReservedDynamicKeyword(string keyword) =>
string.Equals(keyword, "Synchronization", StringComparison.OrdinalIgnoreCase) ||
string.Equals(keyword, "Certificate", StringComparison.OrdinalIgnoreCase) ||
string.Equals(keyword, "IIS", StringComparison.OrdinalIgnoreCase) ||
string.Equals(keyword, "SQL", StringComparison.OrdinalIgnoreCase);
static bool IsReservedProperty(string name) =>
string.Equals(name, "Require", StringComparison.OrdinalIgnoreCase) ||
string.Equals(name, "Trigger", StringComparison.OrdinalIgnoreCase) ||
string.Equals(name, "Notify", StringComparison.OrdinalIgnoreCase) ||
string.Equals(name, "Before", StringComparison.OrdinalIgnoreCase) ||
string.Equals(name, "After", StringComparison.OrdinalIgnoreCase) ||
string.Equals(name, "Subscribe", StringComparison.OrdinalIgnoreCase);
}
///
/// Update range restriction for meta configuration keywords
/// the restrictions are for
/// ConfigurationModeFrequency: 15-44640
/// RefreshFrequency: 30-44640.
///
///
private static void UpdateKnownRestriction(DynamicKeyword keyword)
{
if (
string.Equals(keyword.ResourceName, "MSFT_DSCMetaConfigurationV2",
StringComparison.OrdinalIgnoreCase)
||
string.Equals(keyword.ResourceName, "MSFT_DSCMetaConfiguration",
StringComparison.OrdinalIgnoreCase))
{
if (keyword.Properties["RefreshFrequencyMins"] != null)
{
keyword.Properties["RefreshFrequencyMins"].Range = new Tuple(30, 44640);
}
if (keyword.Properties["ConfigurationModeFrequencyMins"] != null)
{
keyword.Properties["ConfigurationModeFrequencyMins"].Range = new Tuple(15, 44640);
}
if (keyword.Properties["DebugMode"] != null)
{
keyword.Properties["DebugMode"].Values.Remove("ResourceScriptBreakAll");
keyword.Properties["DebugMode"].ValueMap.Remove("ResourceScriptBreakAll");
}
}
}
///
/// Load the default system CIM classes and create the corresponding keywords.
///
public static void LoadDefaultCimKeywords()
{
LoadDefaultCimKeywords(null, null, null, false);
}
///
/// Load the default system CIM classes and create the corresponding keywords.
///
/// List of module path from where DSC PS modules will be loaded.
public static void LoadDefaultCimKeywords(List modulePathList)
{
LoadDefaultCimKeywords(null, null, modulePathList, false);
}
///
/// Load the default system CIM classes and create the corresponding keywords.
///
/// Collection of any errors encountered while loading keywords.
public static void LoadDefaultCimKeywords(Collection errors)
{
LoadDefaultCimKeywords(null, errors, null, false);
}
///
/// Load the default system CIM classes and create the corresponding keywords.
///
/// A dictionary to add the defined functions to, may be null.
public static void LoadDefaultCimKeywords(Dictionary functionsToDefine)
{
LoadDefaultCimKeywords(functionsToDefine, null, null, false);
}
///
/// Load the default system CIM classes and create the corresponding keywords.
///
/// Collection of any errors encountered while loading keywords.
/// Allow caching the resources from multiple versions of modules.
public static void LoadDefaultCimKeywords(Collection errors, bool cacheResourcesFromMultipleModuleVersions)
{
LoadDefaultCimKeywords(null, errors, null, cacheResourcesFromMultipleModuleVersions);
}
///
/// Load the default system CIM classes and create the corresponding keywords.
///
/// A dictionary to add the defined functions to, may be null.
/// Collection of any errors encountered while loading keywords.
/// List of module path from where DSC PS modules will be loaded.
/// Allow caching the resources from multiple versions of modules.
private static void LoadDefaultCimKeywords(Dictionary functionsToDefine, Collection errors,
List modulePathList, bool cacheResourcesFromMultipleModuleVersions)
{
DynamicKeyword.Reset();
Initialize(errors, modulePathList);
// Initialize->ClearCache resets CacheResourcesFromMultipleModuleVersions to false,
// workaround is to set it after Initialize method call.
// Initialize method imports all the Inbox resources and internal classes which belongs to only one version
// of the module, so it is ok if this property is not set during cache initialization.
CacheResourcesFromMultipleModuleVersions = cacheResourcesFromMultipleModuleVersions;
foreach (var cimClass in GetCachedClasses())
{
var className = cimClass.CimClassInstance.CimSystemProperties.ClassName;
var moduleInfo = ByClassModuleCache[className];
CreateAndRegisterKeywordFromCimClass(moduleInfo.Item1, moduleInfo.Item2, cimClass.CimClassInstance, functionsToDefine, cimClass.DscResRunAsCred);
}
// And add the Node keyword definitions
if (!DynamicKeyword.ContainsKeyword("Node"))
{
// Implement dispatch to the Node keyword.
var nodeKeyword = new DynamicKeyword()
{
BodyMode = DynamicKeywordBodyMode.ScriptBlock,
ImplementingModule = s_defaultModuleInfoForResource.Item1,
ImplementingModuleVersion = s_defaultModuleInfoForResource.Item2,
NameMode = DynamicKeywordNameMode.NameRequired,
Keyword = "Node",
};
DynamicKeyword.AddKeyword(nodeKeyword);
}
// And add the Import-DscResource keyword definitions
if (!DynamicKeyword.ContainsKeyword("Import-DscResource"))
{
// Implement dispatch to the Node keyword.
var nodeKeyword = new DynamicKeyword()
{
BodyMode = DynamicKeywordBodyMode.Command,
ImplementingModule = s_defaultModuleInfoForResource.Item1,
ImplementingModuleVersion = s_defaultModuleInfoForResource.Item2,
NameMode = DynamicKeywordNameMode.NoName,
Keyword = "Import-DscResource",
MetaStatement = true,
PostParse = ImportResourcePostParse,
SemanticCheck = ImportResourceCheckSemantics
};
DynamicKeyword.AddKeyword(nodeKeyword);
}
}
// This function is called after parsing the Import-DscResource keyword and it's arguments, but before parsing
// anything else.
//
//
private static ParseError[] ImportResourcePostParse(DynamicKeywordStatementAst kwAst)
{
var elements = Ast.CopyElements(kwAst.CommandElements);
Diagnostics.Assert(elements[0] is StringConstantExpressionAst &&
((StringConstantExpressionAst)elements[0]).Value.Equals("Import-DscResource", StringComparison.OrdinalIgnoreCase),
"Incorrect ast for expected keyword");
var commandAst = new CommandAst(kwAst.Extent, elements, TokenKind.Unknown, null);
const string nameParam = "Name";
const string moduleNameParam = "ModuleName";
const string moduleVersionParam = "ModuleVersion";
StaticBindingResult bindingResult = StaticParameterBinder.BindCommand(commandAst, false);
var errorList = new List();
foreach (var bindingException in bindingResult.BindingExceptions.Values)
{
errorList.Add(new ParseError(bindingException.CommandElement.Extent,
"ParameterBindingException",
bindingException.BindingException.Message));
}
ParameterBindingResult moduleNameBindingResult = null;
ParameterBindingResult resourceNameBindingResult = null;
ParameterBindingResult moduleVersionBindingResult = null;
foreach (var binding in bindingResult.BoundParameters)
{
// Error case when positional parameter values are specified
var boundParameterName = binding.Key;
var parameterBindingResult = binding.Value;
if (boundParameterName.All(char.IsDigit))
{
errorList.Add(new ParseError(parameterBindingResult.Value.Extent,
"ImportDscResourcePositionalParamsNotSupported",
string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourcePositionalParamsNotSupported)));
continue;
}
if (nameParam.StartsWith(boundParameterName, StringComparison.OrdinalIgnoreCase))
{
resourceNameBindingResult = parameterBindingResult;
}
else if (moduleNameParam.StartsWith(boundParameterName, StringComparison.OrdinalIgnoreCase))
{
moduleNameBindingResult = parameterBindingResult;
}
else if (moduleVersionParam.StartsWith(boundParameterName, StringComparison.OrdinalIgnoreCase))
{
moduleVersionBindingResult = parameterBindingResult;
}
else
{
errorList.Add(new ParseError(parameterBindingResult.Value.Extent,
"ImportDscResourceNeedParams",
string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceNeedParams)));
}
}
if (errorList.Count == 0 && moduleNameBindingResult == null && resourceNameBindingResult == null)
{
errorList.Add(new ParseError(kwAst.Extent,
"ImportDscResourceNeedParams",
string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceNeedParams)));
}
// Check here if Version is specified but modulename is not specified
if (moduleVersionBindingResult != null && moduleNameBindingResult == null)
{
// only add this error again to the error list if resources is not null
// if resources and modules are both null we have already added this error in collection
// we do not want to do this twice. since we are giving same error ImportDscResourceNeedParams in both cases
// once we have different error messages for 2 scenarios we can remove this check
if (resourceNameBindingResult != null)
{
errorList.Add(new ParseError(kwAst.Extent,
"ImportDscResourceNeedModuleNameWithModuleVersion",
string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceNeedParams)));
}
}
string[] resourceNames = null;
if (resourceNameBindingResult != null)
{
object resourceName = null;
if (!IsConstantValueVisitor.IsConstant(resourceNameBindingResult.Value, out resourceName, true, true) ||
!LanguagePrimitives.TryConvertTo(resourceName, out resourceNames))
{
errorList.Add(new ParseError(resourceNameBindingResult.Value.Extent,
"RequiresInvalidStringArgument",
string.Format(CultureInfo.CurrentCulture, ParserStrings.RequiresInvalidStringArgument, nameParam)));
}
}
System.Version moduleVersion = null;
if (moduleVersionBindingResult != null)
{
object moduleVer = null;
if (!IsConstantValueVisitor.IsConstant(moduleVersionBindingResult.Value, out moduleVer, true, true))
{
errorList.Add(new ParseError(moduleVersionBindingResult.Value.Extent,
"RequiresArgumentMustBeConstant",
ParserStrings.RequiresArgumentMustBeConstant));
}
if (moduleVer is double)
{
// this happens in case -ModuleVersion 1.0, then use extent text for that.
// The better way to do it would be define static binding API against CommandInfo, that holds information about parameter types.
// This way, we can avoid this ugly special-casing and say that -ModuleVersion has type [System.Version].
moduleVer = moduleVersionBindingResult.Value.Extent.Text;
}
if (!LanguagePrimitives.TryConvertTo(moduleVer, out moduleVersion))
{
errorList.Add(new ParseError(moduleVersionBindingResult.Value.Extent,
"RequiresVersionInvalid",
ParserStrings.RequiresVersionInvalid));
}
}
ModuleSpecification[] moduleSpecifications = null;
if (moduleNameBindingResult != null)
{
object moduleName = null;
if (!IsConstantValueVisitor.IsConstant(moduleNameBindingResult.Value, out moduleName, true, true))
{
errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent,
"RequiresArgumentMustBeConstant",
ParserStrings.RequiresArgumentMustBeConstant));
}
if (LanguagePrimitives.TryConvertTo(moduleName, out moduleSpecifications))
{
// if resourceNames are specified then we can not specify multiple modules name
if (moduleSpecifications != null && moduleSpecifications.Length > 1 && resourceNames != null)
{
errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent,
"ImportDscResourceMultipleModulesNotSupportedWithName",
string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceMultipleModulesNotSupportedWithName)));
}
// if moduleversion is specified then we can not specify multiple modules name
if (moduleSpecifications != null && moduleSpecifications.Length > 1 && moduleVersion != null)
{
errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent,
"ImportDscResourceMultipleModulesNotSupportedWithVersion",
string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceNeedParams)));
}
// if moduleversion is specified then we can not specify another version in modulespecification object of ModuleName
if (moduleSpecifications != null && (moduleSpecifications[0].Version != null || moduleSpecifications[0].MaximumVersion != null) && moduleVersion != null)
{
errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent,
"ImportDscResourceMultipleModuleVersionsNotSupported",
string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceNeedParams)));
}
// If moduleVersion is specified we have only one module Name in valid scenario
// So update it's version property in module specification object that will be used to load modules
if (moduleSpecifications != null && moduleSpecifications[0].Version == null && moduleSpecifications[0].MaximumVersion == null && moduleVersion != null)
{
moduleSpecifications[0].Version = moduleVersion;
}
}
else
{
errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent,
"RequiresInvalidStringArgument",
string.Format(CultureInfo.CurrentCulture, ParserStrings.RequiresInvalidStringArgument, moduleNameParam)));
}
}
if (errorList.Count == 0)
{
// No errors, try to load the resources
LoadResourcesFromModule(kwAst.Extent, moduleSpecifications, resourceNames, errorList);
}
return errorList.ToArray();
}
// This function performs semantic checks for Import-DscResource
private static ParseError[] ImportResourceCheckSemantics(DynamicKeywordStatementAst kwAst)
{
List errorList = null;
var keywordAst = Ast.GetAncestorAst(kwAst.Parent);
while (keywordAst != null)
{
if (keywordAst.Keyword.Keyword.Equals("Node"))
{
errorList ??= new List();
errorList.Add(new ParseError(kwAst.Extent,
"ImportDscResourceInsideNode",
string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceInsideNode)));
break;
}
keywordAst = Ast.GetAncestorAst(keywordAst.Parent);
}
if (errorList != null)
{
return errorList.ToArray();
}
else
{
return null;
}
}
// This function performs semantic checks for all DSC Resources keywords.
private static ParseError[] CheckMandatoryPropertiesPresent(DynamicKeywordStatementAst kwAst)
{
HashSet mandatoryPropertiesNames = new(StringComparer.OrdinalIgnoreCase);
foreach (var pair in kwAst.Keyword.Properties)
{
if (pair.Value.Mandatory)
{
mandatoryPropertiesNames.Add(pair.Key);
}
}
// by design mandatoryPropertiesNames are not empty at this point:
// every resource must have at least one Key property.
HashtableAst hashtableAst = null;
foreach (var ast in kwAst.CommandElements)
{
hashtableAst = ast as HashtableAst;
if (hashtableAst != null)
{
break;
}
}
if (hashtableAst == null)
{
// nothing to validate
return null;
}
foreach (var pair in hashtableAst.KeyValuePairs)
{
object evalResultObject;
if (IsConstantValueVisitor.IsConstant(pair.Item1, out evalResultObject, forAttribute: false, forRequires: false))
{
if (evalResultObject is string presentName)
{
if (mandatoryPropertiesNames.Remove(presentName) && mandatoryPropertiesNames.Count == 0)
{
// optimization, once all mandatory properties are specified, we can safely exit.
return null;
}
}
}
}
if (mandatoryPropertiesNames.Count > 0)
{
ParseError[] errors = new ParseError[mandatoryPropertiesNames.Count];
var extent = kwAst.CommandElements[0].Extent;
int i = 0;
foreach (string name in mandatoryPropertiesNames)
{
errors[i] = new ParseError(extent, "MissingValueForMandatoryProperty",
string.Format(CultureInfo.CurrentCulture, ParserStrings.MissingValueForMandatoryProperty,
kwAst.Keyword.Keyword, kwAst.Keyword.Properties.First(
p => StringComparer.OrdinalIgnoreCase.Equals(p.Value.Name, name)).Value.TypeConstraint, name));
i++;
}
return errors;
}
return null;
}
///
/// Load DSC resources from specified module.
///
/// Script statement loading the module, can be null.
/// Module information, can be null.
/// Name of the resource to be loaded from module.
/// List of errors reported by the method.
public static void LoadResourcesFromModule(IScriptExtent scriptExtent,
ModuleSpecification[] moduleSpecifications,
string[] resourceNames,
List errorList)
{
// get all required modules
var modules = new Collection();
if (moduleSpecifications != null)
{
foreach (var moduleToImport in moduleSpecifications)
{
bool foundModule = false;
var moduleInfos = ModuleCmdletBase.GetModuleIfAvailable(moduleToImport);
if (moduleInfos.Count >= 1 && (moduleToImport.Version != null || moduleToImport.Guid != null))
{
foreach (var psModuleInfo in moduleInfos)
{
if ((moduleToImport.Guid.HasValue && moduleToImport.Guid.Equals(psModuleInfo.Guid)) ||
(moduleToImport.Version != null &&
moduleToImport.Version.Equals(psModuleInfo.Version)))
{
modules.Add(psModuleInfo);
foundModule = true;
break;
}
}
}
else if (moduleInfos.Count == 1)
{
modules.Add(moduleInfos[0]);
foundModule = true;
}
if (!foundModule)
{
if (moduleInfos.Count > 1)
{
errorList.Add(new ParseError(scriptExtent,
"MultipleModuleEntriesFoundDuringParse",
string.Format(CultureInfo.CurrentCulture,
ParserStrings.MultipleModuleEntriesFoundDuringParse,
moduleToImport.Name)));
}
else
{
string moduleString = moduleToImport.Version == null
? moduleToImport.Name
: string.Create(CultureInfo.CurrentCulture, $"<{moduleToImport.Name}, {moduleToImport.Version}>");
errorList.Add(new ParseError(scriptExtent, "ModuleNotFoundDuringParse",
string.Format(CultureInfo.CurrentCulture, ParserStrings.ModuleNotFoundDuringParse, moduleString)));
}
return;
}
}
}
else if (resourceNames != null)
{
// Lookup the required resources under available PowerShell modules when modulename is not specified
using (var powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
{
powerShell.AddCommand("Get-Module");
powerShell.AddParameter("ListAvailable");
modules = powerShell.Invoke();
}
}
// When ModuleName only specified, we need to import all resources from that module
var resourcesToImport = new List();
if (resourceNames == null || resourceNames.Length == 0)
{
resourcesToImport.Add("*");
}
else
{
resourcesToImport.AddRange(resourceNames);
}
foreach (var moduleInfo in modules)
{
var dscResourcesPath = Path.Combine(moduleInfo.ModuleBase, "DscResources");
var resourcesFound = new List();
LoadPowerShellClassResourcesFromModule(moduleInfo, moduleInfo, resourcesToImport, resourcesFound, errorList, null, true, scriptExtent);
if (Directory.Exists(dscResourcesPath))
{
foreach (var resourceToImport in resourcesToImport)
{
bool foundResources = false;
foreach (var resourceDir in Directory.EnumerateDirectories(dscResourcesPath, resourceToImport))
{
var resourceName = Path.GetFileName(resourceDir);
bool foundCimSchema = false;
bool foundScriptSchema = false;
string schemaMofFilePath = string.Empty;
try
{
foundCimSchema = ImportCimKeywordsFromModule(moduleInfo, resourceName, out schemaMofFilePath);
}
catch (FileNotFoundException)
{
errorList.Add(new ParseError(scriptExtent,
"SchemaFileNotFound",
string.Format(CultureInfo.CurrentCulture, ParserStrings.SchemaFileNotFound, schemaMofFilePath)));
}
catch (PSInvalidOperationException e)
{
errorList.Add(new ParseError(scriptExtent,
e.ErrorRecord.FullyQualifiedErrorId,
e.Message));
}
catch (Exception e)
{
errorList.Add(new ParseError(scriptExtent,
"ExceptionParsingMOFFile",
string.Format(CultureInfo.CurrentCulture, ParserStrings.ExceptionParsingMOFFile, schemaMofFilePath, e.Message)));
}
var schemaScriptFilePath = string.Empty;
try
{
foundScriptSchema = ImportScriptKeywordsFromModule(moduleInfo, resourceName, out schemaScriptFilePath);
}
catch (FileNotFoundException)
{
errorList.Add(new ParseError(scriptExtent,
"SchemaFileNotFound",
string.Format(CultureInfo.CurrentCulture, ParserStrings.SchemaFileNotFound, schemaScriptFilePath)));
}
catch (Exception e)
{
// This shouldn't happen so just report the error as is
errorList.Add(new ParseError(scriptExtent,
"UnexpectedParseError",
string.Format(CultureInfo.CurrentCulture, e.ToString())));
}
if (foundCimSchema || foundScriptSchema)
{
foundResources = true;
}
}
//
// resourceToImport may be the friendly name of the DSC resource
//
if (!foundResources)
{
try
{
foundResources = ImportCimKeywordsFromModule(moduleInfo, resourceToImport, out _);
}
catch (Exception)
{
}
}
// resource name without wildcard (*) should be imported only once
if (!resourceToImport.Contains('*') && foundResources)
{
resourcesFound.Add(resourceToImport);
}
}
}
foreach (var resource in resourcesFound)
{
resourcesToImport.Remove(resource);
}
if (resourcesToImport.Count == 0)
{
break;
}
}
if (resourcesToImport.Count > 0)
{
foreach (var resourceNameToImport in resourcesToImport)
{
if (!resourceNameToImport.Contains('*'))
{
errorList.Add(new ParseError(scriptExtent,
"DscResourcesNotFoundDuringParsing",
string.Format(CultureInfo.CurrentCulture, ParserStrings.DscResourcesNotFoundDuringParsing, resourceNameToImport)));
}
}
}
}
private static void LoadPowerShellClassResourcesFromModule(PSModuleInfo primaryModuleInfo, PSModuleInfo moduleInfo, ICollection resourcesToImport, ICollection resourcesFound,
List errorList,
Dictionary functionsToDefine = null,
bool recurse = true,
IScriptExtent extent = null)
{
if (primaryModuleInfo._declaredDscResourceExports == null || primaryModuleInfo._declaredDscResourceExports.Count == 0)
{
return;
}
if (moduleInfo.ModuleType == ModuleType.Binary)
{
#if CORECLR
throw PSTraceSource.NewArgumentException("isConfiguration", ParserStrings.ConfigurationNotSupportedInPowerShellCore);
#else
ResolveEventHandler reh = (sender, args) => CurrentDomain_ReflectionOnlyAssemblyResolve(sender, args, moduleInfo);
try
{
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += reh;
var assembly = moduleInfo.ImplementingAssembly;
if (assembly == null && moduleInfo.Path != null)
{
try
{
var path = moduleInfo.Path;
if (moduleInfo.RootModule != null && !Path.GetExtension(moduleInfo.Path).Equals(".dll", StringComparison.OrdinalIgnoreCase))
{
path = moduleInfo.ModuleBase + "\\" + moduleInfo.RootModule;
}
assembly = Assembly.ReflectionOnlyLoadFrom(path);
}
catch { }
}
// Ignore the module if we can't find the assembly.
if (assembly != null)
{
ImportKeywordsFromAssembly(moduleInfo, resourcesToImport, resourcesFound, functionsToDefine, assembly);
}
}
finally
{
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= reh;
}
#endif
}
else
{
string scriptPath = null;
// handle RootModule and nestedModule together
if (moduleInfo.RootModule != null)
{
scriptPath = Path.Combine(moduleInfo.ModuleBase, moduleInfo.RootModule);
}
else if (moduleInfo.Path != null)
{
scriptPath = moduleInfo.Path;
}
ImportKeywordsFromScriptFile(scriptPath, primaryModuleInfo, resourcesToImport, resourcesFound, functionsToDefine, errorList, extent);
}
if (moduleInfo.NestedModules != null && recurse)
{
foreach (var nestedModule in moduleInfo.NestedModules)
{
LoadPowerShellClassResourcesFromModule(primaryModuleInfo, nestedModule, resourcesToImport, resourcesFound, errorList, functionsToDefine, recurse: false, extent: extent);
}
}
}
#if !CORECLR
private static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args, PSModuleInfo moduleInfo)
{
AssemblyName name = new AssemblyName(args.Name);
if (moduleInfo != null && !string.IsNullOrEmpty(moduleInfo.Path))
{
string asmToCheck = Path.GetDirectoryName(moduleInfo.Path) + "\\" + name.Name + ".dll";
if (File.Exists(asmToCheck))
{
return Assembly.ReflectionOnlyLoadFrom(asmToCheck);
}
asmToCheck = Path.GetDirectoryName(moduleInfo.Path) + "\\" + name.Name + ".exe";
if (File.Exists(asmToCheck))
{
return Assembly.ReflectionOnlyLoadFrom(asmToCheck);
}
}
return Assembly.ReflectionOnlyLoad(args.Name);
}
#endif
///
///
///
///
///
/// The list of resources imported from this module.
public static List ImportClassResourcesFromModule(PSModuleInfo moduleInfo, ICollection resourcesToImport, Dictionary functionsToDefine)
{
var resourcesImported = new List();
LoadPowerShellClassResourcesFromModule(moduleInfo, moduleInfo, resourcesToImport, resourcesImported, null, functionsToDefine);
return resourcesImported;
}
internal static string GenerateMofForAst(TypeDefinitionAst typeAst)
{
var embeddedInstanceTypes = new List