public void set_api_key(ChocolateyConfiguration configuration) { var apiKey = configFileSettings.ApiKeys.FirstOrDefault(p => p.Source.is_equal_to(configuration.Sources)); if (apiKey == null) { configFileSettings.ApiKeys.Add(new ConfigFileApiKeySetting { Source = configuration.Sources, Key = NugetEncryptionUtility.EncryptString(configuration.ApiKeyCommand.Key), }); _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); this.Log().Info(() => "Added ApiKey for {0}".format_with(configuration.Sources)); } else { if (!NugetEncryptionUtility.DecryptString(apiKey.Key).to_string().is_equal_to(configuration.ApiKeyCommand.Key)) { apiKey.Key = NugetEncryptionUtility.EncryptString(configuration.ApiKeyCommand.Key); _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); this.Log().Info(() => "Updated ApiKey for {0}".format_with(configuration.Sources)); } else { this.Log().Warn(NO_CHANGE_MESSAGE); } } }
private static void add_or_remove_licensed_source(ChocolateyLicense license, ConfigFileSettings configFileSettings) { // do not enable or disable the source, in case the user has disabled it var addOrUpdate = license.IsValid; var sources = configFileSettings.Sources.Where(s => !s.Disabled).or_empty_list_if_null().ToList(); var configSource = new ConfigFileSourceSetting { Id = ApplicationParameters.ChocolateyLicensedFeedSourceName, Value = ApplicationParameters.ChocolateyLicensedFeedSource, UserName = "******", Password = NugetEncryptionUtility.EncryptString(license.Id), Priority = 10 }; if (addOrUpdate && !sources.Any(s => s.Id.is_equal_to(ApplicationParameters.ChocolateyLicensedFeedSourceName) && NugetEncryptionUtility.DecryptString(s.Password).is_equal_to(license.Id) ) ) { configFileSettings.Sources.Add(configSource); } if (!addOrUpdate) { configFileSettings.Sources.RemoveWhere(s => s.Id.is_equal_to(configSource.Id)); } }
public string get_api_key(ChocolateyConfiguration configuration, Action <ConfigFileApiKeySetting> keyAction) { string apiKeyValue = null; if (!string.IsNullOrWhiteSpace(configuration.Sources)) { var apiKey = configFileSettings.ApiKeys.FirstOrDefault(p => p.Source.TrimEnd('/').is_equal_to(configuration.Sources.TrimEnd('/'))); if (apiKey != null) { apiKeyValue = NugetEncryptionUtility.DecryptString(apiKey.Key).to_string(); if (keyAction != null) { keyAction.Invoke(new ConfigFileApiKeySetting { Key = apiKeyValue, Source = apiKey.Source }); } } } else { foreach (var apiKey in configFileSettings.ApiKeys.or_empty_list_if_null()) { var keyValue = NugetEncryptionUtility.DecryptString(apiKey.Key).to_string(); if (keyAction != null) { keyAction.Invoke(new ConfigFileApiKeySetting { Key = keyValue, Source = apiKey.Source }); } } } return(apiKeyValue); }
private static void add_or_remove_licensed_source(ChocolateyLicense license, ConfigFileSettings configFileSettings) { // do not enable or disable the source, in case the user has disabled it var addOrUpdate = license.IsValid; var sources = configFileSettings.Sources.or_empty_list_if_null().ToList(); var configSource = new ConfigFileSourceSetting { Id = ApplicationParameters.ChocolateyLicensedFeedSourceName, Value = ApplicationParameters.ChocolateyLicensedFeedSource, UserName = "******", Password = NugetEncryptionUtility.EncryptString(license.Id), Priority = 10, BypassProxy = false, AllowSelfService = false, VisibleToAdminsOnly = false, }; if (addOrUpdate && !sources.Any(s => s.Id.is_equal_to(ApplicationParameters.ChocolateyLicensedFeedSourceName) && NugetEncryptionUtility.DecryptString(s.Password).is_equal_to(license.Id) ) ) { configFileSettings.Sources.Add(configSource); } if (!addOrUpdate) { configFileSettings.Sources.RemoveWhere(s => s.Id.is_equal_to(configSource.Id)); } // ensure only one licensed source - helpful when moving between licenses configFileSettings.Sources.RemoveWhere(s => s.Id.is_equal_to(configSource.Id) && !NugetEncryptionUtility.DecryptString(s.Password).is_equal_to(license.Id)); }
public static void set_environment_variables(ChocolateyConfiguration config) { reset_environment_variables(config); Environment.SetEnvironmentVariable(ApplicationParameters.ChocolateyInstallEnvironmentVariableName, ApplicationParameters.InstallLocation); Environment.SetEnvironmentVariable("CHOCOLATEY_VERSION", config.Information.ChocolateyVersion); Environment.SetEnvironmentVariable("CHOCOLATEY_VERSION_PRODUCT", config.Information.ChocolateyProductVersion); Environment.SetEnvironmentVariable("OS_PLATFORM", config.Information.PlatformType.get_description_or_value()); Environment.SetEnvironmentVariable("OS_VERSION", config.Information.PlatformVersion.to_string()); Environment.SetEnvironmentVariable("OS_NAME", config.Information.PlatformName.to_string()); // experimental until we know if this value returns correctly based on the OS and not the current process. Environment.SetEnvironmentVariable("OS_IS64BIT", config.Information.Is64Bit ? "true" : "false"); Environment.SetEnvironmentVariable("IS_ADMIN", config.Information.IsUserAdministrator ? "true" : "false"); Environment.SetEnvironmentVariable("IS_PROCESSELEVATED", config.Information.IsProcessElevated ? "true" : "false"); Environment.SetEnvironmentVariable("TEMP", config.CacheLocation); if (config.Debug) { Environment.SetEnvironmentVariable("ChocolateyEnvironmentDebug", "true"); } if (config.Verbose) { Environment.SetEnvironmentVariable("ChocolateyEnvironmentVerbose", "true"); } if (!config.Features.CheckSumFiles) { Environment.SetEnvironmentVariable("ChocolateyIgnoreChecksums", "true"); } Environment.SetEnvironmentVariable("chocolateyRequestTimeout", config.WebRequestTimeoutSeconds.to_string() + "000"); Environment.SetEnvironmentVariable("chocolateyResponseTimeout", config.CommandExecutionTimeoutSeconds.to_string() + "000"); if (!string.IsNullOrWhiteSpace(config.Proxy.Location)) { var proxyCreds = string.Empty; if (!string.IsNullOrWhiteSpace(config.Proxy.User) && !string.IsNullOrWhiteSpace(config.Proxy.EncryptedPassword) ) { proxyCreds = "{0}:{1}@".format_with(config.Proxy.User, NugetEncryptionUtility.DecryptString(config.Proxy.EncryptedPassword)); Environment.SetEnvironmentVariable("chocolateyProxyUser", config.Proxy.User); Environment.SetEnvironmentVariable("chocolateyProxyPassword", NugetEncryptionUtility.DecryptString(config.Proxy.EncryptedPassword)); } Environment.SetEnvironmentVariable("http_proxy", "{0}{1}".format_with(proxyCreds, config.Proxy.Location)); Environment.SetEnvironmentVariable("https_proxy", "{0}{1}".format_with(proxyCreds, config.Proxy.Location)); Environment.SetEnvironmentVariable("chocolateyProxyLocation", config.Proxy.Location); } if (config.Features.UsePowerShellHost) { Environment.SetEnvironmentVariable("ChocolateyPowerShellHost", "true"); } if (config.Force) { Environment.SetEnvironmentVariable("ChocolateyForce", "true"); } set_licensed_environment(config); }
public void config_set(ChocolateyConfiguration configuration) { var encryptValue = configuration.ConfigCommand.Name.contains("password"); var config = config_get(configuration.ConfigCommand.Name); var configValue = encryptValue ? NugetEncryptionUtility.EncryptString(configuration.ConfigCommand.ConfigValue) : configuration.ConfigCommand.ConfigValue; if (config == null) { var setting = new ConfigFileConfigSetting { Key = configuration.ConfigCommand.Name, Value = configValue, }; configFileSettings.ConfigSettings.Add(setting); _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); this.Log().Warn(() => "Added {0} = {1}".format_with(setting.Key, setting.Value)); } else { var currentValue = encryptValue && !string.IsNullOrWhiteSpace(config.Value) ? NugetEncryptionUtility.DecryptString(config.Value) : config.Value; if (configuration.ConfigCommand.ConfigValue.is_equal_to(currentValue.to_string())) { this.Log().Warn(NO_CHANGE_MESSAGE); } else { config.Value = configValue; _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); this.Log().Warn(() => "Updated {0} = {1}".format_with(config.Key, config.Value)); } } }
public void source_add(ChocolateyConfiguration configuration) { var source = configFileSettings.Sources.FirstOrDefault(p => p.Id.is_equal_to(configuration.SourceCommand.Name)); if (source == null) { source = new ConfigFileSourceSetting { Id = configuration.SourceCommand.Name, Value = configuration.Sources, UserName = configuration.SourceCommand.Username, Password = NugetEncryptionUtility.EncryptString(configuration.SourceCommand.Password), Certificate = configuration.SourceCommand.Certificate, CertificatePassword = NugetEncryptionUtility.EncryptString(configuration.SourceCommand.CertificatePassword), Priority = configuration.SourceCommand.Priority, BypassProxy = configuration.SourceCommand.BypassProxy, AllowSelfService = configuration.SourceCommand.AllowSelfService, VisibleToAdminsOnly = configuration.SourceCommand.VisibleToAdminsOnly }; configFileSettings.Sources.Add(source); _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); if (!configuration.QuietOutput) { this.Log().Warn(() => "Added {0} - {1} (Priority {2})".format_with(source.Id, source.Value, source.Priority)); } } else { var currentPassword = string.IsNullOrWhiteSpace(source.Password) ? null : NugetEncryptionUtility.DecryptString(source.Password); var currentCertificatePassword = string.IsNullOrWhiteSpace(source.CertificatePassword) ? null : NugetEncryptionUtility.DecryptString(source.CertificatePassword); if (configuration.Sources.is_equal_to(source.Value) && configuration.SourceCommand.Priority == source.Priority && configuration.SourceCommand.Username.is_equal_to(source.UserName) && configuration.SourceCommand.Password.is_equal_to(currentPassword) && configuration.SourceCommand.CertificatePassword.is_equal_to(currentCertificatePassword) && configuration.SourceCommand.Certificate.is_equal_to(source.Certificate) && configuration.SourceCommand.BypassProxy == source.BypassProxy && configuration.SourceCommand.AllowSelfService == source.AllowSelfService && configuration.SourceCommand.VisibleToAdminsOnly == source.VisibleToAdminsOnly ) { if (!configuration.QuietOutput) { this.Log().Warn(NO_CHANGE_MESSAGE); } } else { source.Value = configuration.Sources; source.Priority = configuration.SourceCommand.Priority; source.UserName = configuration.SourceCommand.Username; source.Password = NugetEncryptionUtility.EncryptString(configuration.SourceCommand.Password); source.CertificatePassword = NugetEncryptionUtility.EncryptString(configuration.SourceCommand.CertificatePassword); source.Certificate = configuration.SourceCommand.Certificate; source.BypassProxy = configuration.SourceCommand.BypassProxy; source.AllowSelfService = configuration.SourceCommand.AllowSelfService; source.VisibleToAdminsOnly = configuration.SourceCommand.VisibleToAdminsOnly; _xmlService.serialize(configFileSettings, ApplicationParameters.GlobalConfigFileLocation); if (!configuration.QuietOutput) { this.Log().Warn(() => "Updated {0} - {1} (Priority {2})".format_with(source.Id, source.Value, source.Priority)); } } } }
protected override void Load(ContainerBuilder builder) { var viewModelAssembly = typeof(ShellViewModel).Assembly; var viewAssembly = typeof(ShellView).Assembly; // Register Providers builder.RegisterType <VersionNumberProvider>().As <IVersionNumberProvider>().SingleInstance(); builder.RegisterType <Elevation>().SingleInstance(); builder.RegisterType <ChocolateyConfigurationProvider>().As <IChocolateyConfigurationProvider>().SingleInstance(); builder.RegisterType <ChocolateyService>().As <IChocolateyService>().SingleInstance(); builder.RegisterType <DotNetFileSystem>().As <chocolatey.infrastructure.filesystem.IFileSystem>().SingleInstance(); builder.RegisterType <PackageArgumentsService>().As <IPackageArgumentsService>().SingleInstance(); builder.RegisterType <DefaultEncryptionUtility>().As <IEncryptionUtility>().SingleInstance(); // Register ViewModels builder.RegisterAssemblyTypes(viewModelAssembly) .Where(type => type.Name.EndsWith("ViewModel", StringComparison.Ordinal)) .Where(type => type.GetInterface(typeof(INotifyPropertyChanged).Name) != null) .AsSelf() .InstancePerDependency(); builder.RegisterType <PackageViewModel>().As <IPackageViewModel>(); var choco = Lets.GetChocolatey(initializeLogging: true); builder.RegisterInstance(choco.Container().GetInstance <IChocolateyConfigSettingsService>()) .As <IChocolateyConfigSettingsService>().SingleInstance(); builder.RegisterInstance(choco.Container().GetInstance <IXmlService>()) .As <IXmlService>().SingleInstance(); // Register Views builder.RegisterAssemblyTypes(viewAssembly) .Where(type => type.Name.EndsWith("View", StringComparison.Ordinal)) .AsSelf() .InstancePerDependency(); // Register the single window manager for this container builder.Register <IWindowManager>(c => new WindowManager()).InstancePerLifetimeScope(); // Register the single event aggregator for this container builder.Register <IEventAggregator>(c => new EventAggregator()).InstancePerLifetimeScope(); // Register Services builder.RegisterType <DialogService>().As <IDialogService>().SingleInstance(); builder.RegisterType <ProgressService>().As <IProgressService>().SingleInstance(); builder.RegisterType <PersistenceService>().As <IPersistenceService>().SingleInstance(); builder.RegisterType <LiteDBFileStorageService>().As <IFileStorageService>().SingleInstance(); builder.RegisterType <ChocolateyGuiCacheService>().As <IChocolateyGuiCacheService>().SingleInstance(); builder.RegisterType <AllowedCommandsService>().As <IAllowedCommandsService>().SingleInstance(); // Register Mapper var mapperConfiguration = new MapperConfiguration(config => { config.CreateMap <IPackageViewModel, IPackageViewModel>() .ForMember(vm => vm.IsInstalled, options => options.Ignore()); config.CreateMap <DataServicePackage, Package>() .ForMember(dest => dest.Authors, opt => opt.MapFrom(src => src.Authors.Split(','))) .ForMember(dest => dest.Owners, opt => opt.MapFrom(src => src.Owners.Split(','))); config.CreateMap <IPackage, Package>(); config.CreateMap <ConfigFileFeatureSetting, ChocolateyFeature>(); config.CreateMap <ConfigFileConfigSetting, ChocolateySetting>(); config.CreateMap <ConfigFileSourceSetting, Common.Models.ChocolateySource>() .ForMember(dest => dest.Password, opt => opt.MapFrom(src => NugetEncryptionUtility.DecryptString(src.Password))) .ForMember(dest => dest.CertificatePassword, opt => opt.MapFrom(src => NugetEncryptionUtility.DecryptString(src.CertificatePassword))); config.CreateMap <ChocolateySource, Common.Models.ChocolateySource>() .ForMember(dest => dest.VisibleToAdminsOnly, opt => opt.MapFrom(src => src.VisibleToAdminOnly)); config.CreateMap <AdvancedInstallViewModel, AdvancedInstall>() .ForMember( dest => dest.DownloadChecksum, opt => opt.Condition(source => !source.IgnoreChecksums)) .ForMember( dest => dest.DownloadChecksumType, opt => opt.Condition(source => !source.IgnoreChecksums && !string.IsNullOrEmpty(source.DownloadChecksum))) .ForMember( dest => dest.DownloadChecksum64bit, opt => opt.Condition(source => Environment.Is64BitOperatingSystem && !source.IgnoreChecksums && !source.Forcex86)) .ForMember( dest => dest.DownloadChecksumType64bit, opt => opt.Condition(source => Environment.Is64BitOperatingSystem && !source.IgnoreChecksums && !source.Forcex86 && !string.IsNullOrEmpty(source.DownloadChecksum64bit))) .ForMember( dest => dest.PackageParameters, opt => opt.Condition(source => !source.SkipPowerShell)) .ForMember( dest => dest.InstallArguments, opt => opt.Condition(source => !source.SkipPowerShell && !source.NotSilent)); }); builder.RegisterType <BundledThemeService>().As <IBundledThemeService>().SingleInstance(); builder.RegisterInstance(mapperConfiguration.CreateMapper()).As <IMapper>(); builder.Register(c => TranslationSource.Instance).SingleInstance(); try { var userDatabase = new LiteDatabase($"filename={Path.Combine(Bootstrapper.LocalAppDataPath, "data.db")};upgrade=true"); LiteDatabase globalDatabase; if (Hacks.IsElevated) { globalDatabase = new LiteDatabase($"filename={Path.Combine(Bootstrapper.AppDataPath, "Config", "data.db")};upgrade=true"); } else { if (!File.Exists(Path.Combine(Bootstrapper.AppDataPath, "Config", "data.db"))) { // Since the global configuration database file doesn't exist, we must be running in a state where an administrator user // has never run Chocolatey GUI. In this case, use null, which will mean attempts to use the global database will be ignored. globalDatabase = null; } else { // Since this is a non-administrator user, they should only have read permissions to this database globalDatabase = new LiteDatabase($"filename={Path.Combine(Bootstrapper.AppDataPath, "Config", "data.db")};readonly=true"); } } if (globalDatabase != null) { builder.RegisterInstance(globalDatabase).As <LiteDatabase>().SingleInstance().Named <LiteDatabase>(Bootstrapper.GlobalConfigurationDatabaseName); } var configService = new ConfigService(globalDatabase, userDatabase); configService.SetEffectiveConfiguration(); var iconService = new PackageIconService(userDatabase); builder.RegisterInstance(iconService).As <IPackageIconService>().SingleInstance(); builder.RegisterInstance(configService).As <IConfigService>().SingleInstance(); builder.RegisterInstance(new LiteDBFileStorageService(userDatabase)).As <IFileStorageService>().SingleInstance(); // Since there are two instances of LiteDB, they are added as named instances, so that they can be retrieved when required builder.RegisterInstance(userDatabase).As <LiteDatabase>().SingleInstance().Named <LiteDatabase>(Bootstrapper.UserConfigurationDatabaseName); } catch (IOException ex) { Bootstrapper.Logger.Error(ex, TranslationSource.Instance[nameof(Resources.Error_DatabaseAccessGui)]); throw; } builder.RegisterType <ImageService>().As <IImageService>().SingleInstance(); builder.RegisterType <VersionService>().As <IVersionService>().SingleInstance(); builder.RegisterType <SplashScreenService>().As <ISplashScreenService>().SingleInstance(); }
protected override void Load(ContainerBuilder builder) { var viewModelAssembly = typeof(ShellViewModel).Assembly; var viewAssembly = typeof(ShellView).Assembly; // Register Providers builder.RegisterType <VersionNumberProvider>().As <IVersionNumberProvider>().SingleInstance(); builder.RegisterType <Elevation>().SingleInstance(); builder.RegisterType <ChocolateyConfigurationProvider>().As <IChocolateyConfigurationProvider>().SingleInstance(); builder.RegisterType <ChocolateyService>().As <IChocolateyService>().SingleInstance(); builder.RegisterType <DotNetFileSystem>().As <chocolatey.infrastructure.filesystem.IFileSystem>().SingleInstance(); // Register ViewModels builder.RegisterAssemblyTypes(viewModelAssembly) .Where(type => type.Name.EndsWith("ViewModel", StringComparison.Ordinal)) .Where(type => type.GetInterface(typeof(INotifyPropertyChanged).Name) != null) .AsSelf() .InstancePerDependency(); builder.RegisterType <PackageViewModel>().As <IPackageViewModel>(); var choco = Lets.GetChocolatey(); builder.RegisterInstance(choco.Container().GetInstance <IChocolateyConfigSettingsService>()) .As <IChocolateyConfigSettingsService>().SingleInstance(); builder.RegisterInstance(choco.Container().GetInstance <IXmlService>()) .As <IXmlService>().SingleInstance(); // Register Views builder.RegisterAssemblyTypes(viewAssembly) .Where(type => type.Name.EndsWith("View", StringComparison.Ordinal)) .AsSelf() .InstancePerDependency(); // Register the single window manager for this container builder.Register <IWindowManager>(c => new WindowManager()).InstancePerLifetimeScope(); // Register the single event aggregator for this container builder.Register <IEventAggregator>(c => new EventAggregator()).InstancePerLifetimeScope(); // Register Services builder.RegisterType <ProgressService>().As <IProgressService>().SingleInstance(); builder.RegisterType <PersistenceService>().As <IPersistenceService>().SingleInstance(); builder.RegisterType <LiteDBFileStorageService>().As <IFileStorageService>().SingleInstance(); builder.RegisterType <ConfigService>().As <IConfigService>().SingleInstance(); builder.RegisterType <ChocolateyGuiCacheService>().As <IChocolateyGuiCacheService>().SingleInstance(); builder.RegisterType <AllowedCommandsService>().As <IAllowedCommandsService>().SingleInstance(); // Register Mapper var mapperConfiguration = new MapperConfiguration(config => { config.CreateMap <IPackageViewModel, IPackageViewModel>() .ForMember(vm => vm.IsInstalled, options => options.Ignore()); config.CreateMap <DataServicePackage, Package>() .ForMember(dest => dest.Authors, opt => opt.MapFrom(src => src.Authors.Split(','))) .ForMember(dest => dest.Owners, opt => opt.MapFrom(src => src.Owners.Split(','))); config.CreateMap <IPackage, Package>(); config.CreateMap <ConfigFileFeatureSetting, ChocolateyFeature>(); config.CreateMap <ConfigFileConfigSetting, ChocolateySetting>(); config.CreateMap <ConfigFileSourceSetting, Common.Models.ChocolateySource>() .ForMember(dest => dest.Password, opt => opt.MapFrom(src => NugetEncryptionUtility.DecryptString(src.Password))) .ForMember(dest => dest.CertificatePassword, opt => opt.MapFrom(src => NugetEncryptionUtility.DecryptString(src.CertificatePassword))); config.CreateMap <ChocolateySource, Common.Models.ChocolateySource>() .ForMember(dest => dest.VisibleToAdminsOnly, opt => opt.MapFrom(src => src.VisibleToAdminOnly)); }); builder.RegisterInstance(DialogCoordinator.Instance).As <IDialogCoordinator>(); builder.RegisterInstance(mapperConfiguration.CreateMapper()).As <IMapper>(); try { var database = new LiteDatabase($"filename={Path.Combine(Bootstrapper.LocalAppDataPath, "data.db")};upgrade=true"); builder.Register(c => database).SingleInstance(); } catch (IOException ex) { Bootstrapper.Logger.Error(ex, Resources.Error_DatabaseAccessGui); throw; } builder.RegisterType <ImageService>().As <IImageService>().SingleInstance(); builder.RegisterType <VersionService>().As <IVersionService>().SingleInstance(); builder.RegisterType <SplashScreenService>().As <ISplashScreenService>().SingleInstance(); }
public static void set_environment_variables(ChocolateyConfiguration config) { reset_environment_variables(config); Environment.SetEnvironmentVariable(ApplicationParameters.ChocolateyInstallEnvironmentVariableName, ApplicationParameters.InstallLocation); Environment.SetEnvironmentVariable("CHOCOLATEY_VERSION", config.Information.ChocolateyVersion); Environment.SetEnvironmentVariable("CHOCOLATEY_VERSION_PRODUCT", config.Information.ChocolateyProductVersion); Environment.SetEnvironmentVariable("OS_PLATFORM", config.Information.PlatformType.get_description_or_value()); Environment.SetEnvironmentVariable("OS_VERSION", config.Information.PlatformVersion.to_string()); Environment.SetEnvironmentVariable("OS_NAME", config.Information.PlatformName.to_string()); // experimental until we know if this value returns correctly based on the OS and not the current process. Environment.SetEnvironmentVariable("OS_IS64BIT", config.Information.Is64BitOperatingSystem ? "true" : "false"); Environment.SetEnvironmentVariable("PROCESS_IS64BIT", config.Information.Is64BitProcess ? "true" : "false"); Environment.SetEnvironmentVariable("USER_NAME", config.Information.UserName); Environment.SetEnvironmentVariable("USER_DOMAIN", config.Information.UserDomainName); Environment.SetEnvironmentVariable("IS_ADMIN", config.Information.IsUserAdministrator ? "true" : "false"); Environment.SetEnvironmentVariable("IS_SYSTEM", config.Information.IsUserSystemAccount ? "true" : "false"); Environment.SetEnvironmentVariable("IS_REMOTEDESKTOP", config.Information.IsUserRemoteDesktop ? "true" : "false"); Environment.SetEnvironmentVariable("IS_REMOTE", config.Information.IsUserRemote ? "true" : "false"); Environment.SetEnvironmentVariable("IS_PROCESSELEVATED", config.Information.IsProcessElevated ? "true" : "false"); Environment.SetEnvironmentVariable("TEMP", config.CacheLocation); Environment.SetEnvironmentVariable("TMP", config.CacheLocation); if (config.Debug) { Environment.SetEnvironmentVariable("ChocolateyEnvironmentDebug", "true"); } if (config.Verbose) { Environment.SetEnvironmentVariable("ChocolateyEnvironmentVerbose", "true"); } if (!config.Features.ChecksumFiles) { Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyIgnoreChecksums, "true"); } if (config.Features.AllowEmptyChecksums) { Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyAllowEmptyChecksums, "true"); } if (config.Features.AllowEmptyChecksumsSecure) { Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyAllowEmptyChecksumsSecure, "true"); } Environment.SetEnvironmentVariable("chocolateyRequestTimeout", config.WebRequestTimeoutSeconds.to_string() + "000"); if (config.CommandExecutionTimeoutSeconds != 0) { Environment.SetEnvironmentVariable("chocolateyResponseTimeout", config.CommandExecutionTimeoutSeconds.to_string() + "000"); } if (!string.IsNullOrWhiteSpace(config.Proxy.Location)) { var proxyCreds = string.Empty; if (!string.IsNullOrWhiteSpace(config.Proxy.User) && !string.IsNullOrWhiteSpace(config.Proxy.EncryptedPassword) ) { proxyCreds = "{0}:{1}@".format_with(config.Proxy.User, NugetEncryptionUtility.DecryptString(config.Proxy.EncryptedPassword)); Environment.SetEnvironmentVariable("chocolateyProxyUser", config.Proxy.User); Environment.SetEnvironmentVariable("chocolateyProxyPassword", NugetEncryptionUtility.DecryptString(config.Proxy.EncryptedPassword)); } Environment.SetEnvironmentVariable("http_proxy", "{0}{1}".format_with(proxyCreds, config.Proxy.Location)); Environment.SetEnvironmentVariable("https_proxy", "{0}{1}".format_with(proxyCreds, config.Proxy.Location)); Environment.SetEnvironmentVariable("chocolateyProxyLocation", config.Proxy.Location); if (!string.IsNullOrWhiteSpace(config.Proxy.BypassList)) { Environment.SetEnvironmentVariable("chocolateyProxyBypassList", config.Proxy.BypassList); Environment.SetEnvironmentVariable("no_proxy", config.Proxy.BypassList); } if (config.Proxy.BypassOnLocal) { Environment.SetEnvironmentVariable("chocolateyProxyBypassOnLocal", "true"); } } if (config.Features.UsePowerShellHost) { Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyPowerShellHost, "true"); } if (config.Force) { Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyForce, "true"); } if (config.Features.ExitOnRebootDetected) { Environment.SetEnvironmentVariable(ApplicationParameters.Environment.ChocolateyExitOnRebootDetected, "true"); } }
public bool run_action(ChocolateyConfiguration configuration, PackageResult packageResult, CommandNameType command) { var installerRun = false; var file = "chocolateyInstall.ps1"; switch (command) { case CommandNameType.uninstall: file = "chocolateyUninstall.ps1"; break; } var packageDirectory = packageResult.InstallLocation; if (packageDirectory.is_equal_to(ApplicationParameters.InstallLocation) || packageDirectory.is_equal_to(ApplicationParameters.PackagesLocation)) { packageResult.Messages.Add( new ResultMessage( ResultType.Error, "Install location is not specific enough, cannot run PowerShell script:{0} Erroneous install location captured as '{1}'".format_with(Environment.NewLine, packageResult.InstallLocation) ) ); return(false); } if (!_fileSystem.directory_exists(packageDirectory)) { packageResult.Messages.Add(new ResultMessage(ResultType.Error, "Package install not found:'{0}'".format_with(packageDirectory))); return(installerRun); } var powershellScript = _fileSystem.get_files(packageDirectory, file, SearchOption.AllDirectories); if (powershellScript.Count() != 0) { var chocoPowerShellScript = powershellScript.FirstOrDefault(); var failure = false; var package = packageResult.Package; Environment.SetEnvironmentVariable(ApplicationParameters.ChocolateyInstallEnvironmentVariableName, ApplicationParameters.InstallLocation); Environment.SetEnvironmentVariable("CHOCOLATEY_VERSION", configuration.Information.ChocolateyVersion); Environment.SetEnvironmentVariable("CHOCOLATEY_VERSION_PRODUCT", configuration.Information.ChocolateyProductVersion); Environment.SetEnvironmentVariable("OS_PLATFORM", configuration.Information.PlatformType.get_description_or_value()); Environment.SetEnvironmentVariable("OS_VERSION", configuration.Information.PlatformVersion.to_string()); Environment.SetEnvironmentVariable("OS_NAME", configuration.Information.PlatformName.to_string()); // experimental until we know if this value returns correctly based on the OS and not the current process. Environment.SetEnvironmentVariable("OS_IS64BIT", configuration.Information.Is64Bit ? "true" : "false"); Environment.SetEnvironmentVariable("IS_ADMIN", configuration.Information.IsUserAdministrator ? "true" : "false"); Environment.SetEnvironmentVariable("IS_PROCESSELEVATED", configuration.Information.IsProcessElevated ? "true" : "false"); Environment.SetEnvironmentVariable("chocolateyPackageName", package.Id); Environment.SetEnvironmentVariable("packageName", package.Id); Environment.SetEnvironmentVariable("chocolateyPackageVersion", package.Version.to_string()); Environment.SetEnvironmentVariable("packageVersion", package.Version.to_string()); Environment.SetEnvironmentVariable("chocolateyPackageFolder", packageDirectory); Environment.SetEnvironmentVariable("packageFolder", packageDirectory); Environment.SetEnvironmentVariable("installArguments", configuration.InstallArguments); Environment.SetEnvironmentVariable("installerArguments", configuration.InstallArguments); Environment.SetEnvironmentVariable("chocolateyInstallArguments", configuration.InstallArguments); Environment.SetEnvironmentVariable("packageParameters", configuration.PackageParameters); Environment.SetEnvironmentVariable("chocolateyPackageParameters", configuration.PackageParameters); if (configuration.ForceX86) { Environment.SetEnvironmentVariable("chocolateyForceX86", "true"); } if (configuration.OverrideArguments) { Environment.SetEnvironmentVariable("chocolateyInstallOverride", "true"); } Environment.SetEnvironmentVariable("TEMP", configuration.CacheLocation); if (configuration.NotSilent) { Environment.SetEnvironmentVariable("chocolateyInstallOverride", "true"); } if (configuration.Debug) { Environment.SetEnvironmentVariable("ChocolateyEnvironmentDebug", "true"); } if (configuration.Verbose) { Environment.SetEnvironmentVariable("ChocolateyEnvironmentVerbose", "true"); } if (!configuration.Features.CheckSumFiles) { Environment.SetEnvironmentVariable("ChocolateyIgnoreChecksums", "true"); } if (!string.IsNullOrWhiteSpace(configuration.Proxy.Location)) { var proxy_creds = string.Empty; if (!string.IsNullOrWhiteSpace(configuration.Proxy.User) && !string.IsNullOrWhiteSpace(configuration.Proxy.EncryptedPassword) ) { proxy_creds = "{0}:{1}@".format_with(configuration.Proxy.User, NugetEncryptionUtility.DecryptString(configuration.Proxy.EncryptedPassword)); Environment.SetEnvironmentVariable("chocolateyProxyUser", configuration.Proxy.User); Environment.SetEnvironmentVariable("chocolateyProxyPassword", NugetEncryptionUtility.DecryptString(configuration.Proxy.EncryptedPassword)); } Environment.SetEnvironmentVariable("http_proxy", "{0}{1}".format_with(proxy_creds, configuration.Proxy.Location)); Environment.SetEnvironmentVariable("https_proxy", "{0}{1}".format_with(proxy_creds, configuration.Proxy.Location)); Environment.SetEnvironmentVariable("chocolateyProxyLocation", configuration.Proxy.Location); } //todo:if (configuration.NoOutput) //{ // Environment.SetEnvironmentVariable("ChocolateyEnvironmentQuiet","true"); //} this.Log().Debug(ChocolateyLoggers.Important, "Contents of '{0}':".format_with(chocoPowerShellScript)); string chocoPowerShellScriptContents = _fileSystem.read_file(chocoPowerShellScript); this.Log().Debug(chocoPowerShellScriptContents.escape_curly_braces()); bool shouldRun = !configuration.PromptForConfirmation; if (!shouldRun) { this.Log().Info(ChocolateyLoggers.Important, () => "The package {0} wants to run '{1}'.".format_with(package.Id, _fileSystem.get_file_name(chocoPowerShellScript))); this.Log().Info(ChocolateyLoggers.Important, () => "Note: If you don't run this script, the installation will fail."); this.Log().Info(ChocolateyLoggers.Important, () => @"Note: To confirm automatically next time, use '-y' or consider setting 'allowGlobalConfirmation'. Run 'choco feature -h' for more details."); var selection = InteractivePrompt.prompt_for_confirmation(@"Do you want to run the script?", new[] { "yes", "no", "print" }, defaultChoice: null, requireAnswer: true); if (selection.is_equal_to("print")) { this.Log().Info(ChocolateyLoggers.Important, "------ BEGIN SCRIPT ------"); this.Log().Info(() => "{0}{1}{0}".format_with(Environment.NewLine, chocoPowerShellScriptContents.escape_curly_braces())); this.Log().Info(ChocolateyLoggers.Important, "------- END SCRIPT -------"); selection = InteractivePrompt.prompt_for_confirmation(@"Do you want to run this script?", new[] { "yes", "no" }, defaultChoice: null, requireAnswer: true); } if (selection.is_equal_to("yes")) { shouldRun = true; } if (selection.is_equal_to("no")) { Environment.ExitCode = 1; packageResult.Messages.Add(new ResultMessage(ResultType.Error, "User cancelled powershell portion of installation for '{0}'.{1} Specify -n to skip automated script actions.".format_with(powershellScript.FirstOrDefault(), Environment.NewLine))); } } if (shouldRun) { installerRun = true; var exitCode = PowershellExecutor.execute( wrap_script_with_module(chocoPowerShellScript, configuration), _fileSystem, configuration.CommandExecutionTimeoutSeconds, (s, e) => { if (string.IsNullOrWhiteSpace(e.Data)) { return; } //inspect for different streams if (e.Data.StartsWith("DEBUG:")) { this.Log().Debug(() => " " + e.Data); } else if (e.Data.StartsWith("WARNING:")) { this.Log().Warn(() => " " + e.Data); } else if (e.Data.StartsWith("VERBOSE:")) { this.Log().Info(ChocolateyLoggers.Verbose, () => " " + e.Data); } else { this.Log().Info(() => " " + e.Data); } }, (s, e) => { if (string.IsNullOrWhiteSpace(e.Data)) { return; } if (e.Data.is_equal_to(OPERATION_COMPLETED_SUCCESSFULLY) || e.Data.is_equal_to(INITIALIZE_DEFAULT_DRIVES)) { this.Log().Info(() => " " + e.Data); } else { failure = true; this.Log().Error(() => " " + e.Data); } }); if (exitCode != 0) { failure = true; } if (failure) { Environment.ExitCode = exitCode; packageResult.Messages.Add(new ResultMessage(ResultType.Error, "Error while running '{0}'.{1} See log for details.".format_with(powershellScript.FirstOrDefault(), Environment.NewLine))); } packageResult.Messages.Add(new ResultMessage(ResultType.Note, "Ran '{0}'".format_with(chocoPowerShellScript))); } } return(installerRun); }