Exemple #1
0
        static int Main(string[] args)
        {
            SystemEvents.SetConsoleEventHandler(ConsoleEventCallback);
            IDisposable impresonationContext = null;
            var         config = new ConfigurationBuilder().AddCloudFoundry().Build();

            var isConfigServerBound = config.AsEnumerable().Select(x => x.Key).Any(x => x == "vcap:services:p-config-server:0");

            Console.WriteLine(isConfigServerBound);
            foreach (var item in config.AsEnumerable())
            {
                Console.WriteLine($"{item.Key}: {item.Value}");
            }
            try
            {
                _options = LoadOptions(args);
                var impersonationRequired = !string.IsNullOrEmpty(_options.User);
                if (impersonationRequired)
                {
                    Impersonate();
                }
                else
                {
                    if (_options.UseSSL)
                    {
                        var netshargs = $"http delete urlacl http://*:{_options.Port}/";

                        var processStartInfo1 = new ProcessStartInfo("netsh", netshargs)
                        {
                            UseShellExecute        = false,
                            RedirectStandardError  = true,
                            RedirectStandardOutput = true,
                            RedirectStandardInput  = true,
                            CreateNoWindow         = true,
                            Verb = "runas"
                        };
                        _childProcess = Process.Start(processStartInfo1);
                        if (_childProcess == null)
                        {
                            throw new Exception("Can't add ssl cert binding");
                        }
                        _childProcess.BeginOutputReadLine();
                        _childProcess.BeginErrorReadLine();
                        _childProcess.OutputDataReceived += (sender, eventArgs) => Console.WriteLine(eventArgs.Data);
                        _childProcess.ErrorDataReceived  += (sender, eventArgs) => Console.Error.WriteLine(eventArgs.Data);
                        _childProcess.WaitForExit(10000);

                        var netshargs2 = $"http add urlacl https://*:{_options.Port}/ user={_options.OriginalUsername}";

                        var processStartInfo2 = new ProcessStartInfo("netsh", netshargs2)
                        {
                            UseShellExecute        = false,
                            RedirectStandardError  = true,
                            RedirectStandardOutput = true,
                            RedirectStandardInput  = true,
                            CreateNoWindow         = true,
                            Verb = "runas"
                        };
                        _childProcess = Process.Start(processStartInfo2);
                        if (_childProcess == null)
                        {
                            throw new Exception("Can't add ssl cert binding");
                        }
                        _childProcess.BeginOutputReadLine();
                        _childProcess.BeginErrorReadLine();
                        _childProcess.OutputDataReceived += (sender, eventArgs) => Console.WriteLine(eventArgs.Data);
                        _childProcess.ErrorDataReceived  += (sender, eventArgs) => Console.Error.WriteLine(eventArgs.Data);
                        _childProcess.WaitForExit(10000);

                        var addSslArgs       = $"http add sslcert ipport=0.0.0.0:{_options.Port} appid={{{_options.ApplicationInstanceId}}} certhash={_options.Thumbprint}";
                        var processStartInfo = new ProcessStartInfo("netsh", addSslArgs)
                        {
                            UseShellExecute        = false,
                            RedirectStandardError  = true,
                            RedirectStandardOutput = true,
                            RedirectStandardInput  = true,
                            CreateNoWindow         = true,
                            Verb = "runas"
                        };
                        _childProcess = Process.Start(processStartInfo);
                        if (_childProcess == null)
                        {
                            throw new Exception("Can't add ssl cert binding");
                        }
                        _childProcess.BeginOutputReadLine();
                        _childProcess.BeginErrorReadLine();
                        _childProcess.OutputDataReceived += (sender, eventArgs) => Console.WriteLine(eventArgs.Data);
                        _childProcess.ErrorDataReceived  += (sender, eventArgs) => Console.Error.WriteLine(eventArgs.Data);
                        _childProcess.WaitForExit(10000);
                    }


                    var appConfigTemplate = new ApplicationHostConfig {
                        Model = _options
                    };
                    var appConfigText = appConfigTemplate.TransformText();
                    ValidateRequiredDllDependencies(appConfigText);
                    var webConfigText = new WebConfig()
                    {
                        Model = _options
                    }.TransformText();
                    var aspNetText = new AspNetConfig().TransformText();

                    Directory.CreateDirectory(_options.TempDirectory);
                    Directory.CreateDirectory(_options.ConfigDirectory);
                    File.WriteAllText(_options.ApplicationHostConfigPath, appConfigText);
                    File.WriteAllText(_options.WebConfigPath, webConfigText);
                    File.WriteAllText(_options.AspnetConfigPath, aspNetText);

                    var webConfig   = Path.Combine(_options.AppRootPath, "web.config");
                    var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
                    var xdt         = Path.Combine(_options.AppRootPath, $"web.{environment}.config");
                    if (!string.IsNullOrEmpty(environment) && File.Exists(xdt))
                    {
                        Console.WriteLine($"Applying {xdt} to web.config");
                        var transform = new Microsoft.Web.XmlTransform.XmlTransformation(xdt);
                        var doc       = new XmlDocument();
                        doc.Load(webConfig);
                        transform.Apply(doc);

                        if (!File.Exists(webConfig + ".bak")) // backup original web.config as we're gonna transform into it's place
                        {
                            File.Move(webConfig, webConfig + ".bak");
                        }
                        doc.Save(webConfig);
                    }

                    if (isConfigServerBound)
                    {
                        config = new ConfigurationBuilder().AddConfigServer().Build();
                        Console.WriteLine("Config server binding found - replacing matching veriables in web.config");

                        var webConfigContent = File.ReadAllText(webConfig);
                        foreach (var configEntry in config.AsEnumerable())
                        {
                            webConfigContent = webConfigContent.Replace("#{" + configEntry.Key + "}", configEntry.Value);
                        }
                        File.WriteAllText(webConfig, webConfigContent);
                    }

                    Console.WriteLine("Activating HWC with following settings:");


                    try
                    {
                        Console.WriteLine($"ApplicationHost.config: {_options.ApplicationHostConfigPath}");
                        Console.WriteLine($"Web.config: {_options.WebConfigPath}");
//                        var process = Process.Start("cmd");
//                        var job = new Job();
//                        job.AddProcess(process.Handle);

                        HostableWebCore.Activate(_options.ApplicationHostConfigPath, _options.WebConfigPath, _options.ApplicationInstanceId);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        Console.Error.WriteLine("Access denied starting hostable web core. Start the application as administrator");
                        Console.WriteLine("===========================");
                        throw;
                    }


                    Console.WriteLine($"Server ID {_options.ApplicationInstanceId} started");
                    Console.WriteLine("PRESS Enter to shutdown");
                    // we gonna read on different thread here because Console.ReadLine is not the only way the program can end
                    // we're also listening to the system events where the app is ordered to shutdown. exitWaitHandle is used to
                    // hook up both of these events
                }
                new Thread(() =>
                {
                    Console.ReadLine();
                    _exitWaitHandle.Set();
                }).Start();
                _exitWaitHandle.WaitOne();
                return(0);
            }

            catch (ValidationException ve)
            {
                Console.Error.WriteLine(ve.Message);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
            }
            finally
            {
                Shutdown();
//                impresonationContext?.Dispose();
            }
            return(1);
        }
Exemple #2
0
        static int Main(string[] args)
        {
            SystemEvents.SetConsoleEventHandler(ConsoleEventCallback);
            IDisposable impresonationContext = null;

            try
            {
                _options = LoadOptions(args);
                var impersonationRequired = !string.IsNullOrEmpty(_options.User);
                if (impersonationRequired)
                {
                    Impersonate();
                }
                else
                {
                    var appConfigTemplate = new ApplicationHostConfig {
                        Model = _options
                    };
                    var appConfigText = appConfigTemplate.TransformText();
                    ValidateRequiredDllDependencies(appConfigText);
                    var webConfigText = new WebConfig()
                    {
                        Model = _options
                    }.TransformText();
                    var aspNetText = new AspNetConfig().TransformText();

                    Directory.CreateDirectory(_options.TempDirectory);
                    Directory.CreateDirectory(_options.ConfigDirectory);
                    File.WriteAllText(_options.ApplicationHostConfigPath, appConfigText);
                    File.WriteAllText(_options.WebConfigPath, webConfigText);
                    File.WriteAllText(_options.AspnetConfigPath, aspNetText);

                    Console.WriteLine("Activating HWC with following settings:");

//                if (impersonationRequired)
//                {
//                    string userName = _options.User;
//                    string domain = null;
//                    var match = Regex.Match(_options.User, @"^(?<domain>\w+)\\(?<user>\w+)$"); // parse out domain from format DOMAIN\Username
//
//                    if (match.Success)
//                    {
//                        userName = match.Groups["user"].Value;
//                        domain = match.Groups["domain"].Value;
//                    }
//                    Console.WriteLine($"Impersonation user {userName} for domain {domain}");
//                    impresonationContext = Impersonation.LogonUser(domain, userName, _options.Password, LogonType.Service);
//                    Console.WriteLine(WindowsIdentity.GetCurrent().Name);
//                }
                    try
                    {
                        Console.WriteLine($"ApplicationHost.config: {_options.ApplicationHostConfigPath}");
                        Console.WriteLine($"Web.config: {_options.WebConfigPath}");
//                        var process = Process.Start("cmd");
//                        var job = new Job();
//                        job.AddProcess(process.Handle);
                        HostableWebCore.Activate(_options.ApplicationHostConfigPath, _options.WebConfigPath, _options.ApplicationInstanceId);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        Console.Error.WriteLine("Access denied starting hostable web core. Start the application as administrator");
                        Console.WriteLine("===========================");
                        throw;
                    }


                    Console.WriteLine($"Server ID {_options.ApplicationInstanceId} started");
                    Console.WriteLine("PRESS Enter to shutdown");
                    // we gonna read on different thread here because Console.ReadLine is not the only way the program can end
                    // we're also listening to the system events where the app is ordered to shutdown. exitWaitHandle is used to
                    // hook up both of these events
                }
                new Thread(() =>
                {
                    Console.ReadLine();
                    _exitWaitHandle.Set();
                }).Start();
                _exitWaitHandle.WaitOne();
                return(0);
            }

            catch (ValidationException ve)
            {
                Console.Error.WriteLine(ve.Message);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
            }
            finally
            {
                Shutdown();
//                impresonationContext?.Dispose();
            }
            Console.ReadLine();
            return(1);
        }