Example #1
0
        private bool FilterOnVersion(Package pkg, string requiredVersion, string minimumVersion, string maximumVersion) {

            if(pkg == null) {
                return false;
            }

            if (string.IsNullOrWhiteSpace(requiredVersion) || (SoftwareIdentityVersionComparer.CompareVersions(pkg.VersionScheme, pkg.Version, requiredVersion) == 0))
            {
                if (string.IsNullOrWhiteSpace(minimumVersion) || (SoftwareIdentityVersionComparer.CompareVersions(pkg.VersionScheme, pkg.Version, minimumVersion) >= 0))
                {
                    if (string.IsNullOrWhiteSpace(maximumVersion) || (SoftwareIdentityVersionComparer.CompareVersions(pkg.VersionScheme, pkg.Version, maximumVersion) <= 0))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
Example #2
0
        internal bool YieldFromSwidtag(Package pkg, string searchKey) {
            if (pkg == null) {
                return !IsCanceled;
            }

            var provider = pkg._swidtag;
            var fastPackageReference = LocalSource.Any() ? pkg.Location.LocalPath : pkg.Location.AbsoluteUri;
            var source = pkg.Source ?? fastPackageReference;

            var summary = pkg.Name;
            var targetFileName = pkg.Name;

            if (!LocalSource.Any()) {
                summary = new MetadataIndexer(provider)[Iso19770_2.Attributes.Summary.LocalName].FirstOrDefault();
                targetFileName = provider.Links.Select(each => each.Attributes[Iso19770_2.Discovery.TargetFilename]).WhereNotNull().FirstOrDefault();
            }

            if (YieldSoftwareIdentity(fastPackageReference, provider.Name, provider.Version, provider.VersionScheme, summary, source, searchKey, null, targetFileName) != null) {
                // yield all the meta/attributes
                if (provider.Meta.Any(
                    m => {
                        var element = AddMeta(fastPackageReference);
                        var attributes = m.Attributes;
                        return attributes.Keys.Any(key => {
                            var nspace = key.Namespace.ToString();
                            if (String.IsNullOrWhiteSpace(nspace)) {
                                return AddMetadata(element, key.LocalName, attributes[key]) == null;
                            }

                            return AddMetadata(element, new Uri(nspace), key.LocalName, attributes[key]) == null;
                        });
                    })) {
                    return !IsCanceled;
                }

                if (provider.Links.Any(link => AddLink(link.HRef, link.Relationship, link.MediaType, link.Ownership, link.Use, link.Media, link.Artifact) == null)) {
                    return !IsCanceled;
                }

                if (provider.Entities.Any(entity => AddEntity(entity.Name, entity.RegId, entity.Role, entity.Thumbprint) == null)) {
                    return !IsCanceled;
                }

                //installing a package from bootstrap site needs to prompt a user. Only auto-bootstrap is not prompted.
                var pm = PackageManagementService as PackageManagementService;
                string isTrustedSource = pm.InternalPackageManagementInstallOnly ? "false" : "true";
                if (AddMetadata(fastPackageReference, "FromTrustedSource", isTrustedSource) == null) {
                    return !IsCanceled;
                }
            }
            return !IsCanceled;
        }
Example #3
0
        private bool FilterOnName(Package pkg, string name)
        {
            if (pkg == null)
            {
                return false;
            }

            if(string.IsNullOrWhiteSpace(name))
            {
                return true;
            }

            if (WildcardPattern.ContainsWildcardCharacters(name))            
            {
                // Applying the wildcard pattern matching
                const WildcardOptions wildcardOptions = WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase;
                var wildcardPattern = new WildcardPattern(name, wildcardOptions);

                return wildcardPattern.IsMatch(pkg.Name);

            }
            else
            {
                return pkg.Name.EqualsIgnoreCase(name);
            }
        }
Example #4
0
        private bool InstallProviderFromInstaller(Package provider, Link link, string fastPath, BootstrapRequest request)
        {
            switch (link.MediaType) {
                case Iso19770_2.MediaType.MsiPackage:
                case Iso19770_2.MediaType.MsuPackage:
                    return InstallPackageFile(provider, fastPath, request);

                case Iso19770_2.MediaType.PackageReference:
                    // let the core figure out how to install this package
                    var packages = PackageManagementService.FindPackageByCanonicalId(link.HRef.AbsoluteUri, request).ToArray();
                    switch (packages.Length) {
                        case 0:
                            request.Warning("Unable to resolve package reference '{0}'", link.HRef);
                            return false;

                        case 1:
                            return InstallPackageReference(provider, fastPath, request, packages);

                        default:
                            request.Warning("Package Reference '{0}' resolves to {1} packages.", packages.Length);
                            return false;
                    }

                case Iso19770_2.MediaType.NuGetPackage:
                    return InstallNugetPackage(provider, link, fastPath, request);

                default:
                    request.Warning("Provider '{0}' with link '{1}' has unknown media type '{2}'.", provider.Name, link.HRef, link.MediaType);
                    return false;
            }
        }
Example #5
0
        internal bool YieldFromSwidtag(Package provider, string requiredVersion, string minimumVersion, string maximumVersion, string searchKey) {
            if (provider == null) {
                // if the provider isn't there, just return.
                return !IsCanceled;
            }

            if (AnyNullOrEmpty(provider.Name, provider.Version, provider.VersionScheme)) {
                Debug("Skipping yield on swid due to missing field \r\n", provider.ToString());
                return !IsCanceled;
            }

            if (!String.IsNullOrWhiteSpace(requiredVersion)) {
                if (provider.Version != requiredVersion) {
                    return !IsCanceled;
                }
            } else {
                if (!String.IsNullOrWhiteSpace(minimumVersion) && SoftwareIdentityVersionComparer.CompareVersions(provider.VersionScheme, provider.Version, minimumVersion) < 0) {
                    return !IsCanceled;
                }

                if (!String.IsNullOrWhiteSpace(maximumVersion) && SoftwareIdentityVersionComparer.CompareVersions(provider.VersionScheme, provider.Version, maximumVersion) > 0) {
                    return !IsCanceled;
                }
            }
            return YieldFromSwidtag(provider, searchKey);
        }
Example #6
0
        private bool InstallPackageReference(Package provider, string fastPath, BootstrapRequest request, SoftwareIdentity[] packages)
        {
            IHostApi installRequest = request;
            if (packages[0].Provider.Name.EqualsIgnoreCase("PowerShellGet") && !request.ProviderServices.IsElevated) {
                // if we're not elevated, we want powershellget to install to the user scope

                installRequest = new object[] {
                    new {
                        GetOptionKeys = new Func<IEnumerable<string>>(() => request.OptionKeys.ConcatSingleItem("Scope")),
                        GetOptionValues = new Func<string, IEnumerable<string>>((key) => {
                            if (key != null && key.EqualsIgnoreCase("Scope")) {
                                return "CurrentUser".SingleItemAsEnumerable();
                            }
                            return request.GetOptionValues(key);
                        })
                    }
                    , installRequest
                }.As<IHostApi>();
            }

            var installing = packages[0].Provider.InstallPackage(packages[0], installRequest);

            SoftwareIdentity lastPackage = null;

            foreach (var i in installing) {
                lastPackage = i;
                // should we echo each package back as it comes back?
                request.YieldSoftwareIdentity(i.FastPackageReference, i.Name, i.Version, i.VersionScheme, i.Summary, i.Source, i.SearchKey, i.FullPath, i.PackageFilename);

                if (request.IsCanceled) {
                    installing.Cancel();
                }
            }

            if (!request.IsCanceled && lastPackage != null) {
                if (provider.Name.EqualsIgnoreCase("PowerShellGet")) {
                    // special case. PSModules we can just ask the PowerShell provider to pick it up
                    // rather than try to scan for it.
                    PackageManagementService.TryLoadProviderViaMetaProvider("PowerShell", lastPackage.FullPath, request);
                    request.YieldFromSwidtag(provider, fastPath);
                    return true;
                }

                // looks like it installed ok.
                request.YieldFromSwidtag(provider, fastPath);

                // rescan providers
                PackageManagementService.LoadProviders(request.As<IRequest>());
                return true;
            }
            return false;
        }
Example #7
0
 private bool InstallPackageFile(Package provider, string fastPath, BootstrapRequest request)
 {
     // we can download and verify this package and get the core to install it.
     var file = request.DownloadAndValidateFile(provider.Name, provider._swidtag);
     if (file != null) {
         // we have a valid file.
         // run the installer
         if (request.ProviderServices.Install(file, "", request)) {
             // it installed ok!
             request.YieldFromSwidtag(provider, fastPath);
             PackageManagementService.LoadProviders(request.As<IRequest>());
             return true;
         }
         request.Warning(Constants.Messages.FailedProviderBootstrap, fastPath);
     }
     return false;
 }
Example #8
0
        private bool InstallNugetPackage(Package provider, Link link, string fastPath, BootstrapRequest request)
        {
            // download the nuget package
            string downloadedNupkg = request.DownloadAndValidateFile(provider.Name, provider._swidtag);

            if (downloadedNupkg != null)
            {
                // extracted folder
                string extractedFolder = String.Concat(downloadedNupkg.GenerateTemporaryFilename());

                try
                {
                    //unzip the file
                    ZipFile.ExtractToDirectory(downloadedNupkg, extractedFolder);

                    if (Directory.Exists(extractedFolder))
                    {
                        string versionFolder = Path.Combine(request.DestinationPath(request), provider.Name, provider.Version);
                        // tool folder is where we find things like nuget.exe
                        string toolFolder = Path.Combine(extractedFolder, "tools");
                        string libFolder = Path.Combine(extractedFolder, "lib");

                        // create the directory version folder if not exist
                        if (!Directory.Exists(versionFolder))
                        {
                            Directory.CreateDirectory(versionFolder);
                        }

                        // copy the tools directory
                        if (Directory.Exists(toolFolder))
                        {
                            string destinationToolFolder = Path.Combine(versionFolder, "tools");

                            if (!Directory.Exists(destinationToolFolder))
                            {
                                Directory.CreateDirectory(destinationToolFolder);
                            }

                            foreach (string child in Directory.EnumerateFiles(toolFolder))
                            {
                                try
                                {
                                    // try copy and overwrite
                                    File.Copy(child, Path.Combine(destinationToolFolder, Path.GetFileName(child)), true);
                                }
                                catch (Exception e)
                                {
                                    request.Debug(e.StackTrace);
                                    if (!(e is UnauthorizedAccessException || e is IOException))
                                    {
                                        // something wrong, delete the version folder
                                        versionFolder.TryHardToDelete();
                                        return false;
                                    }

                                    // otherwise this means the file is just being used. so just moves on to copy other files
                                }
                            }
                        }

                        // copy files from lib
                        if (Directory.Exists(libFolder))
                        {
                            // check that the lib folder has at most 1 dll
                            if (Directory.EnumerateFiles(libFolder).Count(file => String.Equals(Path.GetExtension(file), ".dll", StringComparison.OrdinalIgnoreCase)) > 1)
                            {
                                request.Warning(String.Format(CultureInfo.CurrentCulture, Resources.Messages.MoreThanOneDllExists, provider.Name));
                                return false;
                            }

                            foreach (string child in Directory.EnumerateFiles(libFolder))
                            {
                                try
                                {
                                    File.Copy(child, Path.Combine(versionFolder, Path.GetFileName(child)), true);
                                }
                                catch (Exception e)
                                {
                                    request.Debug(e.StackTrace);
                                    if (!(e is UnauthorizedAccessException || e is IOException))
                                    {
                                        // something wrong, delete the version folder
                                        versionFolder.TryHardToDelete();
                                        return false;
                                    }

                                    // otherwise this means the file is just being used. so just moves on to copy other files
                                }
                            }
                        }

                        // target file name is the assembly provider
                        string targetFile = Path.Combine(versionFolder, Path.GetFileName(link.Attributes[Iso19770_2.Discovery.TargetFilename]));

                        if (File.Exists(targetFile))
                        {
                            request.Verbose(Resources.Messages.InstalledPackage, provider.Name, targetFile);
                            request.YieldFromSwidtag(provider, fastPath);
                            return true;
                        }
                    }
                }
                finally
                {
                    downloadedNupkg.TryHardToDelete();
                    extractedFolder.TryHardToDelete();
                }
            }

            return false;
        }
Example #9
0
        private bool InstallAssemblyProvider(Package provider, Link link, string fastPath, BootstrapRequest request)
        {
            request.Verbose(Resources.Messages.InstallingPackage, fastPath);

            if (!Directory.Exists(request.DestinationPath(request))) {
                request.Error(ErrorCategory.InvalidOperation, fastPath, Constants.Messages.DestinationPathNotSet);
                return false;
            }

            var targetFilename = link.Attributes[Iso19770_2.Discovery.TargetFilename];

            if (string.IsNullOrWhiteSpace(targetFilename)) {
                request.Error(ErrorCategory.InvalidOperation, fastPath, Constants.Messages.InvalidFilename);
                return false;
            }

            targetFilename = Path.GetFileName(targetFilename);

            if (string.IsNullOrWhiteSpace(provider.Version)) {
                request.Error(ErrorCategory.InvalidOperation, fastPath, Resources.Messages.MissingVersion);
                return false;
            }

            //the provider is installing to like this folder: \WindowsPowerShell\Modules\PackageManagement\ProviderAssemblies\nuget\2.8.5.127
            //... providername\version\.dll
            var versionFolder = Path.Combine(request.DestinationPath(request), provider.Name, provider.Version);

            if (!Directory.Exists(versionFolder)) {
                //we create it
                Directory.CreateDirectory(versionFolder);
            }

            var targetFile = Path.Combine(versionFolder, targetFilename);

            // download the file
            var file = request.DownloadAndValidateFile(provider.Name, provider._swidtag);

            if (file != null) {
                try
                {
                    // looks good! let's keep it
                    if (File.Exists(targetFile)) {
                        request.Debug("Removing old file '{0}'", targetFile);
                        targetFile.TryHardToDelete();
                    }

                    // is that file still there?
                    if (File.Exists(targetFile)) {
                        request.Error(ErrorCategory.InvalidOperation, fastPath, Constants.Messages.UnableToRemoveFile, targetFile);
                        return false;
                    }

                    request.Debug("Copying file '{0}' to '{1}'", file, targetFile);
                    try {
                        File.Copy(file, targetFile);
                    }
                    catch (Exception ex) {
                        request.Debug(ex.StackTrace);
                        return false;
                    }

                    //do not need to load the assembly here.The caller in the PackageManangemnt.RequirePackageProvider() is loading assembly
                    //after the install
                    if (File.Exists(targetFile)) {
                        request.Verbose(Resources.Messages.InstalledPackage, provider.Name, targetFile);
                        request.YieldFromSwidtag(provider, fastPath);
                        return true;
                    }

                }
                finally
                {
                    file.TryHardToDelete();
                }
            }

            return false;
        }
Example #10
0
        private bool InstallAssemblyProvider(Package provider, Link link, string fastPath, BootstrapRequest request, bool deleteFile=true) {
            request.Verbose(Resources.Messages.InstallingPackage, fastPath);
            
            if (!Directory.Exists(request.DestinationPath(request))) {
                request.Error(ErrorCategory.InvalidOperation, fastPath, Constants.Messages.DestinationPathNotSet);
                return false;
            }

            string targetFilename = fastPath;
            string file = fastPath;

            //source can be from install-packageprovider or can be from the pipeline
            if (!request.LocalSource.Any() && !fastPath.IsFile() && link != null) {

                targetFilename = link.Attributes[Iso19770_2.Discovery.TargetFilename];

                // download the file
                file = request.DownloadAndValidateFile(provider._swidtag);

            }

            if (string.IsNullOrWhiteSpace(targetFilename)) {
                request.Error(ErrorCategory.InvalidOperation, fastPath, Constants.Messages.InvalidFilename);
                return false;
            }

            targetFilename = Path.GetFileName(targetFilename);
            if (string.IsNullOrWhiteSpace(provider.Version)) {
                request.Error(ErrorCategory.InvalidOperation, fastPath, Resources.Messages.MissingVersion);
                return false;
            }

            //the provider is installing to like this folder: \WindowsPowerShell\Modules\PackageManagement\ProviderAssemblies\nuget\2.8.5.127
            //... providername\version\.dll
            var versionFolder = Path.Combine(request.DestinationPath(request), provider.Name, provider.Version);

            // if version folder exists, remove it
            if (Directory.Exists(versionFolder))
            {
                RemoveDirectory(versionFolder);
            }

            // create the directory if we successfully deleted it
            if (!Directory.Exists(versionFolder))
            {
                Directory.CreateDirectory(versionFolder);
            }

            var targetFile = Path.Combine(versionFolder, targetFilename);

            if (file != null) {
                try
                {
                    // is that file still there?
                    if (File.Exists(targetFile)) {
                        request.Error(ErrorCategory.InvalidOperation, fastPath, Constants.Messages.UnableToRemoveFile, targetFile);
                        return false;
                    }

                    request.Debug("Copying file '{0}' to '{1}'", file, targetFile);
                    try {
                        if (File.Exists(file))
                        {
                            // if this is a file
                            File.Copy(file, targetFile);
                        }
                        else if (Directory.Exists(file))
                        {
                            // if this is a directory, copy items over
                            CopyDirectory(file, versionFolder);
                        }
                    }
                    catch (Exception ex) {
                        request.Debug(ex.StackTrace);
                        return false;
                    }

                    if (File.Exists(targetFile)) {
                        request.Verbose(Resources.Messages.InstalledPackage, provider.Name, targetFile);
                        request.YieldFromSwidtag(provider, fastPath);

                        //Load the provider. This is needed when a provider has dependencies. For example, if Nuget provider has a dependent foobar 
                        // provider and when 'Install-PackageProvider -name NuGet', we want both NuGet and Foobar provider gets loaded.
                        PackageManagementService.LoadProviderAssembly(request, targetFile, false);
                        return true;
                    }

                }
                finally
                {
                    if (deleteFile) {
                        file.TryHardToDelete();
                    }
                }
            }            

            return false;
        }