public void GetCustomErrors(ServerManager srvman, WebVirtualDirectory virtualDir)
		{
			var config = srvman.GetWebConfiguration(virtualDir.FullQualifiedPath);
			//
			var httpErrorsSection = config.GetSection(Constants.HttpErrorsSection);

		    virtualDir.ErrorMode = (HttpErrorsMode)httpErrorsSection.GetAttributeValue("errorMode");
            virtualDir.ExistingResponse = (HttpErrorsExistingResponse)httpErrorsSection.GetAttributeValue("existingResponse");
			//
			var errorsCollection = httpErrorsSection.GetCollection();
			//
			var errors = new List<HttpError>();
			//
			foreach (var item in errorsCollection)
			{
				var item2Get = GetHttpError(item, virtualDir);
				//
				if (item2Get == null)
					continue;
				//
				errors.Add(item2Get);
			}
			//
			virtualDir.HttpErrors = errors.ToArray();
		}
 public LocksPanel(ServerManager server)
 {
     InitializeComponent();
     myServer = server;
     this.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
     | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)));
 }
Exemplo n.º 3
0
	// Use this for initialization
	void Start () {
        DontDestroyOnLoad( this );

        Instance = this;

        _SvrMgr = new ServerManager();
        _SvrMgr.Start();
	}
        public void GetAuthenticationSettings(ServerManager srvman, WebVirtualDirectory virtualDir)
        {
			var config = srvman.GetApplicationHostConfiguration();
			//
			var section = config.GetSection(Constants.BasicAuthenticationSection, virtualDir.FullQualifiedPath);
			//
			virtualDir.EnableBasicAuthentication = Convert.ToBoolean(section.GetAttributeValue(EnabledAttribute));
        }
Exemplo n.º 5
0
 private void button1_Click(object sender, EventArgs e)
 {
     server = new ServerManager(Port.Value);
     server.Start();
     server.OnClientConnect += ConnectClient;
     server.OnReviceData += ReviceData;
     ServerMsg("Server start");
 }
Exemplo n.º 6
0
	// Use this for initialization
	void Start () {
		server = FindObjectOfType<ServerManager> ();
		result = FindObjectOfType<ResultContainer> ();

		SPAWN_POSITION = new Vector3 (0f, 0.5f, 0f);

		startTime = Time.time;
		remainingTime = timeLength;
	}
        public UsersPanel(ServerManager server)
        {
            InitializeComponent();
            myServer = server;
            this.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
             | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)));

            BackButton.Hide();
            CancelButton.Hide();
        }
Exemplo n.º 8
0
 public SnapshotIOPanel(ServerManager server)
 {
     InitializeComponent();
     this.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
     | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)));
     IODataGrid.CellFormatting +=
     new System.Windows.Forms.DataGridViewCellFormattingEventHandler(
     this.IODataGrid_CellFormatting);
     myServer = server;
 }
        public RulesPanel(ServerManager server)
        {
            myServer = server;
            InitializeComponent();
            this.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)));

            EditRuleButton.Enabled = false;
            DeleteRuleButton.Enabled = false;
        }
        public PropertyBag GetAuthenticationSettings(ServerManager srvman, string siteId)
        {
            PropertyBag bag = new PropertyBag();
			var config = srvman.GetApplicationHostConfiguration();
			//
			var section = config.GetSection(Constants.WindowsAuthenticationSection, siteId);
			//
			bag[AuthenticationGlobals.IsLocked] = section.IsLocked;
			bag[AuthenticationGlobals.Enabled] = Convert.ToBoolean(section.GetAttributeValue(EnabledAttribute));
            return bag;
        }
		public PropertyBag GetClassicAspSettings(ServerManager srvman, string siteId)
        {
			var config = srvman.GetApplicationHostConfiguration();
			//
			var aspSection = config.GetSection(SectionName, siteId);
			//
			PropertyBag bag = new PropertyBag();
			//
			bag[ClassicAspGlobals.EnableParentPaths] = Convert.ToBoolean(aspSection.GetAttributeValue(EnableParentPathsAttribute));
			//
			return bag;
        }
Exemplo n.º 12
0
    void Start()
    {
        if (Network.isClient) {
            clientManager = ClientManager.Get();
            clientManager.stage = this;

        }
        else {
            serverManager = ServerManager.Get();
            serverManager.stage = this;
        }
        bounds = GetBounds();
        characterSpawnList = GameObject.FindGameObjectsWithTag("Spawn");
        chestSpawnList = GameObject.FindGameObjectsWithTag("ChestSpawn");
    }
		public PropertyBag GetAuthenticationSettings(ServerManager srvman, string siteId)
        {
			var config = srvman.GetApplicationHostConfiguration();
			//
			var section = config.GetSection(Constants.AnonymousAuthenticationSection, siteId);
			//
			PropertyBag bag = new PropertyBag();
			//
			bag[AuthenticationGlobals.AnonymousAuthenticationUserName] = Convert.ToString(section.GetAttributeValue(UserNameAttribute));
			bag[AuthenticationGlobals.AnonymousAuthenticationPassword] = Convert.ToString(section.GetAttributeValue(PasswordAttribute));
			bag[AuthenticationGlobals.Enabled] = Convert.ToBoolean(section.GetAttributeValue(EnabledAttribute));
			bag[AuthenticationGlobals.IsLocked] = section.IsLocked;
			//
			return bag;
        }
Exemplo n.º 14
0
        public static void Main()
        {
            if (DataCollection.apiKey == null)
            {
                string currentDirectory = Directory.GetCurrentDirectory();
                StreamReader reader = new StreamReader(@Path.Combine(currentDirectory, DataCollection.apiKeyPath));
                DataCollection.apiKey = reader.ReadLine();
                reader.Close();
            }

            System.Diagnostics.Debug.WriteLine("============================");
            System.Diagnostics.Debug.WriteLine("Data Collection Starts");

            for (int i = 0; i < DataCollection.serverList.Length; i++ )
            {
                // TODO: Query servers asynchronously
                ServerManager serverManager = new ServerManager(serverList[0], DataCollection.apiKey,
                    String.Format(DataCollection.inFilePrefixTemplate, serverList[0]),
                    String.Format(DataCollection.outFilePrefixTemplate, serverList[0]),
                    DataCollection.gameType);
                try
                {
                    // Suite 1: Scan a server from scratch
                    // DataCollection.SeedScanSuite(serverManager);

                    // Suite 2: Scan a type of games given existing players from a file
                    // DataCollection.ScanGamesFromPlayersSuite(serverManager);

                    // Suite 3: Collecting detailed game data from existing list of gameIds
                    DataCollection.ScanGamesFromGameIdsSuite(serverManager);
                }
                finally
                {
                    serverManager.CloseAllFiles();
                    System.Diagnostics.Debug.WriteLine("****************");
                    System.Diagnostics.Debug.WriteLine(String.Format("Error in collecting {0} server.", serverList[0]));
                }
            }

            System.Diagnostics.Debug.WriteLine("============================");
        }
        public SettingPair[] GetExtensionsInstalled(ServerManager srvman)
        {
            var settings = new List<SettingPair>();
			var config = srvman.GetApplicationHostConfiguration();

            var handlersSection = (HandlersSection) config.GetSection(Constants.HandlersSection, typeof (HandlersSection));

            var executalbesToLookFor = new[]
            {
                // Perl
                new KeyValuePair<string, string>(Constants.PerlPathSetting, "\\perl.exe"),
                // Php
                new KeyValuePair<string, string>(Constants.Php4PathSetting, "\\php.exe"),
                new KeyValuePair<string, string>(Constants.PhpPathSetting, "\\php-cgi.exe"),
                // Classic ASP
                new KeyValuePair<string, string>(Constants.AspPathSetting, @"\inetsrv\asp.dll"),
                // ASP.NET
                new KeyValuePair<string, string>(Constants.AspNet11PathSetting, @"\Framework\v1.1.4322\aspnet_isapi.dll"),
                new KeyValuePair<string, string>(Constants.AspNet20PathSetting, @"\Framework\v2.0.50727\aspnet_isapi.dll"),
                new KeyValuePair<string, string>(Constants.AspNet40PathSetting, @"\Framework\v4.0.30319\aspnet_isapi.dll"),
                // ASP.NET x64
                new KeyValuePair<string, string>(Constants.AspNet20x64PathSetting, @"\Framework64\v2.0.50727\aspnet_isapi.dll"),
                new KeyValuePair<string, string>(Constants.AspNet40x64PathSetting, @"\Framework64\v4.0.30319\aspnet_isapi.dll"),
            };

            foreach (var handler in handlersSection.Handlers)
            {
                foreach (var valuePair in executalbesToLookFor)
                {
                    var key = valuePair.Key;
                    if (handler.ScriptProcessor.EndsWith(valuePair.Value) && !settings.Exists(s => s.Name == key))
                    {
						settings.Add(new SettingPair{Name = valuePair.Key, Value = handler.ScriptProcessor});
                    }
                }
            }

            return settings.ToArray();
        }
		public string GetDefaultDocumentSettings(ServerManager srvman, string siteId)
		{
			// Load web site configuration
			var config = srvman.GetWebConfiguration(siteId);
			// Load corresponding section
			var section = config.GetSection(Constants.DefaultDocumentsSection);
			//
			var filesCollection = section.GetCollection("files");
			// Build default documents
			var defaultDocs = new List<String>();
			//
			foreach (var item in filesCollection)
			{
				var item2Get = GetDefaultDocument(item);
				//
				if (String.IsNullOrEmpty(item2Get))
					continue;
				//
				defaultDocs.Add(item2Get);
			}
			//
			return String.Join(",", defaultDocs.ToArray());
		}
Exemplo n.º 17
0
 public MainForm()
 {
     InitializeComponent();
     saveConfigToolStrip.Enabled = false;
     _serverManager = new ServerManager();
 }
Exemplo n.º 18
0
 public SettingsCommand(ServerManager serverManager, Settings.GameSettings gameSettings)
 {
     _serverManager = serverManager;
     GameSettings   = gameSettings;
 }
Exemplo n.º 19
0
        /// <summary>
        /// Creates a per application user, sets security access rules for the application deployment directory
        /// and adds a new site to IIS without starting it
        /// </summary>
        /// <param name="appInfo">Structure that contains parameters required for deploying the application.</param>
        /// <param name="version">The dot net framework version supported by the application.</param>
        private void DeployApp(ApplicationInfo appInfo, DotNetVersion version)
        {
            this.startupLogger.Info(Strings.DeployingAppOnIis);

            string aspNetVersion = GetAspDotNetVersion(version);
            string password      = appInfo.WindowsPassword;
            string userName      = appInfo.WindowsUserName;

            try
            {
                mut.WaitOne();
                using (ServerManager serverMgr = new ServerManager())
                {
                    DirectoryInfo deploymentDir = new DirectoryInfo(appInfo.Path);

                    DirectorySecurity deploymentDirSecurity = deploymentDir.GetAccessControl();

                    deploymentDirSecurity.SetAccessRule(
                        new FileSystemAccessRule(
                            userName,
                            FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify,
                            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                            PropagationFlags.None,
                            AccessControlType.Allow));

                    deploymentDir.SetAccessControl(deploymentDirSecurity);

                    Site mySite = serverMgr.Sites.Add(this.appName, appInfo.Path, appInfo.Port);
                    mySite.ServerAutoStart = false;

                    ApplicationPool applicationPool = serverMgr.ApplicationPools[this.appName];
                    if (applicationPool == null)
                    {
                        serverMgr.ApplicationPools.Add(this.appName);
                        applicationPool = serverMgr.ApplicationPools[this.appName];
                        applicationPool.ManagedRuntimeVersion        = aspNetVersion;
                        applicationPool.ProcessModel.IdentityType    = ProcessModelIdentityType.SpecificUser;
                        applicationPool.ProcessModel.UserName        = userName;
                        applicationPool.ProcessModel.Password        = password;
                        applicationPool.ProcessModel.LoadUserProfile = true;
                        if (this.cpuTarget == CpuTarget.X86)
                        {
                            applicationPool.Enable32BitAppOnWin64 = true;
                        }
                        else
                        {
                            applicationPool.Enable32BitAppOnWin64 = false;
                        }
                    }

                    mySite.Applications["/"].ApplicationPoolName = this.appName;
                    FirewallTools.OpenPort(appInfo.Port, appInfo.Name);
                    serverMgr.CommitChanges();
                }
            }
            finally
            {
                mut.ReleaseMutex();
                this.startupLogger.Info(Strings.FinishedAppDeploymentOnIis);
            }
        }
        public WebVirtualDirectory[] GetZooApplications(ServerManager srvman, string siteId)
        {
            if (!SiteExists(srvman, siteId))
                return new WebVirtualDirectory[] { };

            var vdirs = new List<WebVirtualDirectory>();
            var iisObject = srvman.Sites[siteId];
            //
            foreach (var item in iisObject.Applications)
            {
                Configuration cfg = item.GetWebConfiguration();
                string location = siteId + ConfigurationUtility.GetQualifiedVirtualPath(item.Path);
                ConfigurationSection section;
                try
                {
                    section = cfg.GetSection("system.webServer/heliconZoo", location);
                }
                catch(Exception)
                {
                    // looks like Helicon Zoo is not installed, return empty array
                    return vdirs.ToArray();
                }

                if (section.GetCollection().Count > 0)
                {
                    WebVirtualDirectory vdir = new WebVirtualDirectory
                        {
                            Name = ConfigurationUtility.GetNonQualifiedVirtualPath(item.Path),
                            ContentPath = item.VirtualDirectories[0].PhysicalPath
                        };

                    ConfigurationElement zooAppElement = section.GetCollection()[0];
                    ConfigurationElementCollection envColl = zooAppElement.GetChildElement("environmentVariables").GetCollection();
                        
                    foreach (ConfigurationElement env in  envColl)
                    {
                        if ((string) env.GetAttributeValue("name") == "CONSOLE_URL")
                        {
                            vdir.ConsoleUrl = ConfigurationUtility.GetQualifiedVirtualPath(item.Path);
                            if (!vdir.ConsoleUrl.EndsWith("/"))
                            {
                                vdir.ConsoleUrl += "/";
                            }
                            vdir.ConsoleUrl += (string)env.GetAttributeValue("value");
                        }
                    }
                        
                    vdirs.Add(vdir);
                        
                }
            }

            return vdirs.ToArray();
        }
 public void SetZooConsoleDisabled(ServerManager srvman, string siteId, string appName)
 {
     SetZooEnvironmentVariable(srvman, siteId, appName, "CONSOLE_URL", null);
 }
Exemplo n.º 22
0
        public SslDiagDialog(IServiceProvider provider, ServerManager server)
            : base(provider)
        {
            InitializeComponent();

            // from https://www.ibm.com/support/knowledgecenter/SSLTBW_2.1.0/com.ibm.zos.v2r1.ikya100/sigalg.htm
            var wellKnownSignatureAlgorithms = new Dictionary <string, bool>
            {
                { "1.2.840.113549.1.1.5", false }, // sha1RSA, not secure
                { "1.2.840.113549.1.1.14", true }, // sha224RSA, secure
                { "1.2.840.113549.1.1.11", true }, // sha256RSA, secure
                { "1.2.840.113549.1.1.12", true }, // sha384RSA, secure
                { "1.2.840.113549.1.1.13", true }, // sha512RSA, secure
                { "1.2.840.10040.4.3", false },    // sha1DSA, not secure
                { "1.2.840.10045.4.1", false },    // sha1ECDSA, not secure
                { "1.2.840.10045.4.3.1", true },   // sha224ECDSA, secure
                { "1.2.840.10045.4.3.2", true },   // sha256ECDSA, secure
                { "1.2.840.10045.4.3.3", true },   // sha384ECDSA, secure
                { "1.2.840.10045.4.3.4", true },   // sha512ECDSA, secure
            };

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnGenerate, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                txtResult.Clear();
                try
                {
                    Warn("IMPORTANT: This report might contain confidential information. Mask such before sharing with others.");
                    Warn("-----");

                    Debug($"System Time: {DateTime.Now}");
                    Debug($"Processor Architecture: {Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE")}");
                    Debug($"OS: {Environment.OSVersion}");
                    Debug($"Server Type: {server.Mode.AsString(EnumFormat.Description)}");
                    Debug(string.Empty);
                    Debug($"SERVER SSL PROTOCOLS{Environment.NewLine}");

                    bool?ssl10Enabled = GetProtocol("PCT 1.0");
                    Debug($"PCT 1.0: {ssl10Enabled}");
                    if (ssl10Enabled == true)
                    {
                        Warn("PCT 1.0 is not secure. Please disable it.");
                    }
                    else if (ssl10Enabled == null)
                    {
                        Warn("PCT 1.0 is not secure. OS default is used. You might explicitly disable it via registry.");
                    }

                    bool?ssl20Enabled = GetProtocol("SSL 2.0");
                    Debug($"SSL 2.0: {ssl20Enabled}");
                    if (ssl20Enabled == true)
                    {
                        Warn("SSL 2.0 is not secure. Please disable it.");
                    }
                    else if (ssl20Enabled == null)
                    {
                        Warn("SSL 2.0 is not secure. OS default is used. You might explicitly disable it via registry.");
                    }

                    bool?ssl30Enabled = GetProtocol("SSL 3.0");
                    Debug($"SSL 3.0: {ssl30Enabled}");
                    if (ssl30Enabled == true)
                    {
                        Warn("SSL 3.0 is not secure. Please disable it.");
                    }
                    else if (ssl30Enabled == null)
                    {
                        Warn("SSL 3.0 is not secure. OS default is used. You might explicitly disable it via registry.");
                    }

                    bool?tls10Enabled = GetProtocol("TLS 1.0");
                    Debug($"TLS 1.0: {tls10Enabled}");
                    if (tls10Enabled == true)
                    {
                        Warn("TLS 1.0 is not secure. Please disable it.");
                    }
                    else if (tls10Enabled == null)
                    {
                        Warn("TLS 1.0 is not secure. OS default is used. You might explicitly disable it via registry.");
                    }

                    bool?tls11Enabled = GetProtocol("TLS 1.1");
                    Debug($"TLS 1.1: {tls11Enabled}");
                    if (tls11Enabled == true)
                    {
                        Warn("TLS 1.1 is not secure. Please disable it.");
                    }
                    else if (tls11Enabled == null)
                    {
                        Warn("TLS 1.1 is not secure. OS default is used. You might explicitly disable it via registry.");
                    }

                    bool?tls12Enabled = GetProtocol("TLS 1.2");
                    Debug($"TLS 1.2: {tls12Enabled}");

                    Debug($"SChannel EventLogging: {GetEventLogging()} (hex)");
                    Warn($"To tune TLS related settings, please follow https://support.microsoft.com/en-us/kb/187498 or try out IIS Crypto from https://www.nartac.com/Products/IISCrypto/.");
                    Warn("Microsoft documentation on cipher suites can be found at https://docs.microsoft.com/en-us/windows/desktop/secauthn/cipher-suites-in-schannel.");
                    Debug("-----");

                    foreach (Site site in server.Sites)
                    {
                        Debug($"[W3SVC/{site.Id}]");
                        Debug($"ServerComment  : {site.Name}");
                        Debug($"ServerAutoStart: {site.ServerAutoStart}");
                        Debug($"ServerState    : {site.State}");
                        Debug(string.Empty);
                        foreach (Binding binding in site.Bindings)
                        {
                            Info($"BINDING: {binding.Protocol} {binding}");
                            if (binding.Protocol == "https")
                            {
                                if (binding.CertificateHash == null)
                                {
                                    // SNI mapping missing.
                                    Debug($"SSL Flags: {binding.SslFlags}");
                                    if (binding.SslFlags == SslFlags.Sni)
                                    {
                                        Error(
                                            $"Cannot find {binding.Host}:{binding.EndPoint.Port} combination for this SNI binding.");
                                    }
                                    else
                                    {
                                        var querySslCertificateInfo = Microsoft.Web.Administration.NativeMethods.QuerySslCertificateInfo(
                                            binding.EndPoint);
                                        Error(
                                            querySslCertificateInfo == null
                                                    ? $"Cannot find {binding.EndPoint} combination for this IP based binding."
                                                    : $"Cannot find certificate with thumpprint {querySslCertificateInfo.Hash} in store {querySslCertificateInfo.StoreName}.");
                                    }

                                    Debug(string.Empty);
                                    continue;
                                }

                                var hashString = Hex.ToHexString(binding.CertificateHash);
                                Debug($"SSLCertHash: {hashString}");
                                if (site.Server.SupportsSni)
                                {
                                    Debug($"SSL Flags: {binding.SslFlags}");
                                }

                                Debug("Testing EndPoint: 127.0.0.1");

                                var personal = new X509Store(binding.CertificateStoreName, StoreLocation.LocalMachine);
                                try
                                {
                                    personal.Open(OpenFlags.MaxAllowed);
                                    var selectedItem = personal.Certificates.Find(X509FindType.FindByThumbprint, hashString, false);
                                    if (selectedItem.Count == 0)
                                    {
                                        Error($"Cannot find certificate with thumbprint {hashString} in store {binding.CertificateStoreName}.");
                                    }
                                    else
                                    {
                                        var cert = selectedItem[0];
                                        Debug($"#CertName: {cert.FriendlyName}");
                                        Debug($"#Version: {cert.Version}");
                                        if (cert.HasPrivateKey)
                                        {
                                            if (PublicNativeMethods.IsProcessElevated)
                                            {
                                                var newHandle     = IntPtr.Zero;
                                                int newCount      = 0;
                                                var shouldRelease = false;
                                                if (NativeMethods.CryptAcquireCertificatePrivateKey(
                                                        cert.Handle, 0, IntPtr.Zero, ref newHandle, ref newCount,
                                                        ref shouldRelease))
                                                {
                                                    Debug(
                                                        "#You have a private key that corresponds to this certificate.");
                                                }
                                                else
                                                {
                                                    Error("#You have a private key that corresponds to this certificate but CryptAcquireCertificatePrivateKey failed.");
                                                    Rollbar.RollbarLocator.RollbarInstance.Error(
                                                        "CryptAcquireCertificatePrivateKey failed");
                                                }

                                                if (shouldRelease)
                                                {
                                                    NativeMethods.CloseHandle(newHandle);
                                                }
                                            }
                                            else
                                            {
                                                Warn("It seems that you have a private key that corresponds to this certificate. Please run Jexus Manager as administrator and SSL Diag can report in more details.");
                                            }
                                        }
                                        else
                                        {
                                            Error(
                                                "#You don't have a private key that corresponds to this certificate.");
                                        }

                                        var signatureAlgorithm = cert.SignatureAlgorithm;
                                        Debug($"#Signature Algorithm: {signatureAlgorithm.FriendlyName}");
                                        if (wellKnownSignatureAlgorithms.ContainsKey(signatureAlgorithm.Value))
                                        {
                                            if (!wellKnownSignatureAlgorithms[signatureAlgorithm.Value])
                                            {
                                                Warn("Modern web browsers require signature algorithm to be secure. This signature algorithm is not secure, and might trigger warnings and/or errors.");
                                            }
                                        }
                                        else
                                        {
                                            Warn("This certificate uses a not-well-known signature algorithm, which might not be supported by all web browsers and servers.");
                                        }

                                        AsymmetricAlgorithm key = cert.GetECDsaPublicKey();
                                        if (key == null)
                                        {
                                            key = cert.GetRSAPublicKey();
                                        }

                                        Debug($"#Key Exchange Algorithm: {key.KeyExchangeAlgorithm} Key Size: {key.KeySize}");
                                        if (key.SignatureAlgorithm.Equals("ECDSA", StringComparison.OrdinalIgnoreCase))
                                        {
                                            Warn("This is an ECC certificate, so certain (old) web browsers/clients might not be able to support it.");
                                        }
                                        else
                                        {
                                            Warn("This is not an ECC certificate, so *_ECDSA_* cipher suites cannot be used.");
                                        }

                                        Debug($"#Subject: {cert.Subject}");
                                        Debug($"#Issuer: {cert.Issuer}");
                                        Debug($"#Validity: From {cert.NotBefore:G} To {cert.NotAfter:G}");
                                        var now = DateTime.UtcNow;
                                        if (now < cert.NotBefore)
                                        {
                                            Warn("This certificate is not yet valid.");
                                        }

                                        if (cert.NotAfter < now)
                                        {
                                            Error("This certificate is already expired.");
                                        }

                                        Debug($"#Serial Number: {cert.SerialNumber}");
                                        Debug($"DS Mapper Usage: {(binding.UseDsMapper ? "Enabled" : "Disabled")}");
                                        Debug($"Archived: {cert.Archived}");

                                        var hasSAN = false;
                                        foreach (var extension in cert.Extensions)
                                        {
                                            if (extension.Oid.Value == "2.5.29.15")
                                            {
                                                Debug($"#Key Usage: {((X509KeyUsageExtension)extension).KeyUsages}");
                                                continue;
                                            }

                                            if (extension.Oid.Value == "2.5.29.37")
                                            {
                                                var usages           = ((X509EnhancedKeyUsageExtension)extension).EnhancedKeyUsages;
                                                var enhancedKeyUsage = usages.Cast <Oid>().Select(usage => $"{usage.FriendlyName} ({usage.Value})")
                                                                       .Combine(",");

                                                Debug($"#Enhanced Key Usage: {enhancedKeyUsage}");
                                                continue;
                                            }

                                            if (extension.Oid.Value == "2.5.29.17")
                                            {
                                                var name = extension.Format(true).TrimEnd();
                                                Debug($"#Subject Alternative Name: {name}");
                                                hasSAN = true;
                                                continue;
                                            }

                                            if (extension.Oid.FriendlyName == "Basic Constraints")
                                            {
                                                var ext = (X509BasicConstraintsExtension)extension;
                                                Debug(
                                                    $"#Basic Constraints: Subject Type={(ext.CertificateAuthority ? "CA" : "End Entity")}, Path Length Constraint={(ext.HasPathLengthConstraint ? ext.PathLengthConstraint.ToString() : "None")}");
                                            }
                                        }

                                        if (!hasSAN)
                                        {
                                            Warn("Modern web browsers require Subject Alternative Name extension to present. This certificate does not have SAN extension, so might trigger warnings and/or errors.");
                                        }

                                        X509Chain chain   = X509Chain.Create();
                                        chain.ChainPolicy = new X509ChainPolicy
                                        {
                                            RevocationMode = X509RevocationMode.Online
                                        };
                                        bool valid = chain.Build(cert);
                                        if (valid)
                                        {
                                            Debug("Certificate verified.");
                                        }
                                        else
                                        {
                                            Error("Certificate validation failed.");
                                        }

                                        foreach (var item in chain.ChainStatus)
                                        {
                                            Warn(item.StatusInformation);
                                        }
                                    }

                                    personal.Close();
                                }
                                catch (CryptographicException ex)
                                {
                                    Error($"Problems detected on certificate store {binding.CertificateStoreName}.");
                                    if (ex.HResult != Microsoft.Web.Administration.NativeMethods.NonExistingStore)
                                    {
                                        RollbarLocator.RollbarInstance.Info($"CryptographicException {ex.HResult} from SslDiag.");
                                        throw;
                                    }

                                    Error($"Invalid certificate store {binding.CertificateStoreName}.");
                                }
                            }

                            Debug(string.Empty);
                        }
                    }
                }
                catch (CryptographicException ex)
                {
                    Debug(ex.ToString());
                    Rollbar.RollbarLocator.RollbarInstance.Error(ex, custom: new Dictionary <string, object> {
                        { "hResult", ex.HResult }
                    });
                }
                catch (Exception ex)
                {
                    Debug(ex.ToString());
                    Rollbar.RollbarLocator.RollbarInstance.Error(ex);
                }
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnSave, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                var fileName = DialogHelper.ShowSaveFileDialog(null, "Text Files|*.txt|All Files|*.*", null);
                if (string.IsNullOrEmpty(fileName))
                {
                    return;
                }

                File.WriteAllText(fileName, txtResult.Text);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnVerify, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                txtResult.Clear();
            }));
        }
    	public string GetPhysicalPath(ServerManager srvman, WebVirtualDirectory virtualDir)
        {
			string siteId = (virtualDir.ParentSiteName == null) 
				? virtualDir.Name : virtualDir.ParentSiteName;
			//
			var iisObject = srvman.Sites[siteId];
				
			if (iisObject == null)
				return null;

			//
			var iisAppObject = iisObject.Applications[virtualDir.VirtualPath];

			if (iisAppObject == null)
				return null;

			//
			var iisDirObject = iisAppObject.VirtualDirectories["/"];

			if (iisDirObject == null)
				return null;

			//
			return iisDirObject.PhysicalPath;
        }
Exemplo n.º 24
0
        public void TestIisExpressUnlockSectionWithRuntimeTag()
        {
            var directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            Environment.SetEnvironmentVariable("JEXUS_TEST_HOME", directoryName);

            if (directoryName == null)
            {
                return;
            }

            string Current    = Path.Combine(directoryName, @"applicationHost.config");
            string Original   = Path.Combine(directoryName, @"original2.config");
            var    siteConfig = TestHelper.CopySiteConfig(directoryName, "original.config");

            File.Copy(Original, Current, true);
            TestHelper.FixPhysicalPathMono(Current);

            {
                // add the section.
                var file = XDocument.Load(Current);
                var root = file.Root;
                if (root == null)
                {
                    return;
                }

                var windows = root.XPathSelectElement(
                    "/configuration/configSections/sectionGroup[@name='system.webServer']/sectionGroup[@name='security']/sectionGroup[@name='authentication']/section[@name='windowsAuthentication']");
                windows.SetAttributeValue("overrideModeDefault", "Allow");
                file.Save(Current);
            }

            {
                // add the section.
                var file = XDocument.Load(siteConfig);
                var root = file.Root;
                if (root == null)
                {
                    return;
                }

                var pool     = root.XPathSelectElement("/configuration/system.webServer");
                var security = new XElement("security");
                pool.Add(security);
                var authentication = new XElement("authentication");
                security.Add(authentication);
                var windows = new XElement("windowsAuthentication");
                authentication.Add(windows);
                windows.SetAttributeValue("enabled", true);

                var tag = "<runtime>" +
                          "<asm:assemblyBinding xmlns:asm=\"urn:schemas-microsoft-com:asm.v1\">" +
                          "<asm:dependentAssembly>" +
                          "<asm:assemblyIdentity name=\"Newtonsoft.Json\" publicKeyToken=\"30ad4fe6b2a6aeed\" culture=\"neutral\" />" +
                          "<asm:bindingRedirect oldVersion=\"4.5.0.0-9.0.0.0\" newVersion=\"9.0.0.0\" />" +
                          "</asm:dependentAssembly>" +
                          "</asm:assemblyBinding>" +
                          "</runtime>";
                var runtime = XElement.Parse(tag);
                file.Root?.Add(runtime);
                file.Save(siteConfig);
            }

#if IIS
            var server = new ServerManager(Current);
#else
            var server = new IisExpressServerManager(Current);
#endif
            var config = server.Sites[0].Applications[0].GetWebConfiguration();

            // enable Windows authentication
            var windowsSection =
                config.GetSection("system.webServer/security/authentication/windowsAuthentication");
            Assert.True((bool)windowsSection["enabled"]);
#if IIS
            windowsSection.SetAttributeValue("enabled", false);
            var exception = Assert.Throws <COMException>(() => server.CommitChanges());
            Assert.Equal(0xc00cef03, (uint)exception.HResult);
            Assert.Equal("Exception from HRESULT: 0xC00CEF03", exception.Message);
#else
            server.CommitChanges();
#endif
        }
Exemplo n.º 25
0
        public void TestIisExpressDuplicateSection()
        {
            var directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            Environment.SetEnvironmentVariable("JEXUS_TEST_HOME", directoryName);

            if (directoryName == null)
            {
                return;
            }

            string Current    = Path.Combine(directoryName, @"applicationHost.config");
            string Original   = Path.Combine(directoryName, @"original2.config");
            var    siteConfig = TestHelper.CopySiteConfig(directoryName, "original.config");

            File.Copy(Original, Current, true);
            TestHelper.FixPhysicalPathMono(Current);

            {
                // modify the path
                var file = XDocument.Load(Current);
                var root = file.Root;
                if (root == null)
                {
                    return;
                }

                var location    = root.XPathSelectElement("/configuration/location[@path='WebSite2']");
                var newLocation = new XElement("location");
                location.AddAfterSelf(newLocation);
                newLocation.SetAttributeValue("path", "WebSite1");
                var webServer = new XElement("system.webServer");
                newLocation.Add(webServer);
                var document = new XElement("defaultDocument");
                document.SetAttributeValue("enabled", false);
                webServer.Add(document);
                var files = new XElement("files");
                document.Add(files);
                var add = new XElement("add");
                add.SetAttributeValue("value", "home1.html");
                files.Add(add);

                file.Save(Current);
            }

            {
                // Add the section.
                var file = XDocument.Load(siteConfig);
                var root = file.Root;
                if (root == null)
                {
                    return;
                }

                var doc = root.XPathSelectElement("/configuration/system.webServer/defaultDocument");
                doc.SetAttributeValue("enabled", true);
                var add = root.XPathSelectElement("/configuration/system.webServer/defaultDocument/files/add");
                add.SetAttributeValue("value", "home2.html");
                file.Save(siteConfig);
            }
#if IIS
            var server = new ServerManager(Current);
#else
            var server = new IisExpressServerManager(Current);
#endif
            var config  = server.Sites[0].Applications[0].GetWebConfiguration();
            var section =
                config.GetSection("system.webServer/defaultDocument");
            Assert.Equal(true, section["enabled"]);
            {
                var files = section.GetCollection("files");
                Assert.Equal(8, files.Count);
                Assert.Equal("home2.html", files[0]["value"]);
                Assert.True(files[0].IsLocallyStored);
                Assert.Equal("home1.html", files[1]["value"]);
                Assert.False(files[1].IsLocallyStored);

                files.RemoveAt(1);
            }

            server.CommitChanges();

            const string Expected = @"expected3.config";
            TestHelper.FixPhysicalPathMono(Expected);
            XmlAssert.Equal(Expected, Current);
            TestHelper.AssertSiteConfig(directoryName, Expected);
        }
        public void GetApplicationSiteDetail(string applicationName)
        {
            ServerManager  serverManager  = new ServerManager();
            SiteCollection siteCollection = serverManager.Sites;

            _logger.InfoFormat("[{0}] - =============================================", MethodInfo.GetCurrentMethod().Name);
            if ((siteCollection != null) && (siteCollection.Any()))
            {
                ApplicationPoolCollection applicationPoolCollection = serverManager.ApplicationPools;
                string previousApplicationPoolName = string.Empty;
                string currentApplicationPoolName  = string.Empty;

                _logger.InfoFormat("[{0}] - applicationName: {1}", MethodInfo.GetCurrentMethod().Name, applicationName);

                Site site = siteCollection.FirstOrDefault(p => p.Name == applicationName);
                if (site != null)
                {
                    _logger.InfoFormat("[{0}] - site.Id: {1}", MethodInfo.GetCurrentMethod().Name, site.Id);
                    _logger.InfoFormat("[{0}] - site.Name: {1}", MethodInfo.GetCurrentMethod().Name, site.Name);
                    _logger.InfoFormat("[{0}] - site.ServerAutoStart: {1}", MethodInfo.GetCurrentMethod().Name, site.ServerAutoStart);
                    _logger.InfoFormat("[{0}] - site.State: {1}", MethodInfo.GetCurrentMethod().Name, (int)site.State);
                    _logger.InfoFormat("[{0}] - site.State[string]: {1}", MethodInfo.GetCurrentMethod().Name, site.State);

                    BindingCollection bindings = site.Bindings;
                    _logger.InfoFormat("[{0}] - ======================", MethodInfo.GetCurrentMethod().Name);
                    foreach (Binding binding in bindings)
                    {
                        _logger.InfoFormat("[{0}] - binding.Protocol: {1}", MethodInfo.GetCurrentMethod().Name, binding.Protocol);
                        _logger.InfoFormat("[{0}] - binding.BindingInformation: {1}", MethodInfo.GetCurrentMethod().Name, binding.BindingInformation);
                        _logger.InfoFormat("[{0}] - ===========", MethodInfo.GetCurrentMethod().Name);
                    }
                    _logger.InfoFormat("[{0}] - ======================", MethodInfo.GetCurrentMethod().Name);

                    ApplicationCollection applications = site.Applications;
                    foreach (Application itemApplication in site.Applications)
                    {
                        currentApplicationPoolName = itemApplication.ApplicationPoolName;

                        _logger.InfoFormat("[{0}] - itemApplication.ApplicationPoolName: {1}", MethodInfo.GetCurrentMethod().Name, currentApplicationPoolName);
                        _logger.InfoFormat("[{0}] - itemApplication.EnabledProtocols: {1}", MethodInfo.GetCurrentMethod().Name, itemApplication.EnabledProtocols);
                        _logger.InfoFormat("[{0}] - itemApplication.Path: {1}", MethodInfo.GetCurrentMethod().Name, itemApplication.Path);

                        if ((string.IsNullOrWhiteSpace(previousApplicationPoolName) || (currentApplicationPoolName != previousApplicationPoolName)))
                        {
                            previousApplicationPoolName = currentApplicationPoolName;
                            GetApplicationPoolDetail(applicationPoolCollection, currentApplicationPoolName);
                        }
                        else
                        {
                            _logger.InfoFormat("[{0}] - using same ApplicationPoolName", MethodInfo.GetCurrentMethod().Name);
                        }

                        _logger.InfoFormat("[{0}] - ===========", MethodInfo.GetCurrentMethod().Name);
                        foreach (VirtualDirectory itemVirtualDirectory in itemApplication.VirtualDirectories)
                        {
                            _logger.InfoFormat("[{0}] - itemVirtualDirectory.LogonMethod: {1}", MethodInfo.GetCurrentMethod().Name, (int)itemVirtualDirectory.LogonMethod);
                            _logger.InfoFormat("[{0}] - itemVirtualDirectory.LogonMethod[string]: {1}", MethodInfo.GetCurrentMethod().Name, itemVirtualDirectory.LogonMethod);
                            _logger.InfoFormat("[{0}] - itemVirtualDirectory.UserName: {1}", MethodInfo.GetCurrentMethod().Name, itemVirtualDirectory.UserName);
                            _logger.InfoFormat("[{0}] - itemVirtualDirectory.Password: {1}", MethodInfo.GetCurrentMethod().Name, itemVirtualDirectory.Password);
                            _logger.InfoFormat("[{0}] - itemVirtualDirectory.Path: {1}", MethodInfo.GetCurrentMethod().Name, itemVirtualDirectory.Path);
                            _logger.InfoFormat("[{0}] - itemVirtualDirectory.PhysicalPath: {1}", MethodInfo.GetCurrentMethod().Name, itemVirtualDirectory.PhysicalPath);
                            _logger.InfoFormat("[{0}] - ===========", MethodInfo.GetCurrentMethod().Name);
                        }
                        _logger.InfoFormat("[{0}] - ======================", MethodInfo.GetCurrentMethod().Name);
                    }
                }
                else
                {
                    _logger.InfoFormat("[{0}] - ApplicationSite doesn't exists", MethodInfo.GetCurrentMethod().Name);
                }
            }
            else
            {
                _logger.InfoFormat("[{0}] - Server doesn't have any ApplicationSite", MethodInfo.GetCurrentMethod().Name);
            }
            _logger.InfoFormat("[{0}] - =============================================", MethodInfo.GetCurrentMethod().Name);
        }
Exemplo n.º 27
0
        public void TestIisExpressUnlockSection()
        {
            var directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            Environment.SetEnvironmentVariable("JEXUS_TEST_HOME", directoryName);

            if (directoryName == null)
            {
                return;
            }

            string Current    = Path.Combine(directoryName, @"applicationHost.config");
            string Original   = Path.Combine(directoryName, @"original2.config");
            var    siteConfig = TestHelper.CopySiteConfig(directoryName, "original.config");

            File.Copy(Original, Current, true);
            TestHelper.FixPhysicalPathMono(Current);

            {
                // add the section.
                var file = XDocument.Load(Current);
                var root = file.Root;
                if (root == null)
                {
                    return;
                }

                var windows = root.XPathSelectElement("/configuration/configSections/sectionGroup[@name='system.webServer']/sectionGroup[@name='security']/sectionGroup[@name='authentication']/section[@name='windowsAuthentication']");
                windows.SetAttributeValue("overrideModeDefault", "Allow");
                file.Save(Current);
            }

            {
                // add the section.
                var file = XDocument.Load(siteConfig);
                var root = file.Root;
                if (root == null)
                {
                    return;
                }

                var pool     = root.XPathSelectElement("/configuration/system.webServer");
                var security = new XElement("security");
                pool.Add(security);
                var authentication = new XElement("authentication");
                security.Add(authentication);
                var windows = new XElement("windowsAuthentication");
                authentication.Add(windows);
                windows.SetAttributeValue("enabled", true);
                file.Save(siteConfig);
            }

#if IIS
            var server = new ServerManager(Current);
#else
            var server = new IisExpressServerManager(Current);
#endif
            var config = server.Sites[0].Applications[0].GetWebConfiguration();

            // enable Windows authentication
            var windowsSection =
                config.GetSection("system.webServer/security/authentication/windowsAuthentication");
            Assert.True((bool)windowsSection["enabled"]);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Set FTP External Firewall IP.
        /// </summary>
        /// <param name="newIpAddress">The new ip address to use.</param>
        public static void SetFtpExternalFirewallIp(IPAddress newIpAddress)
        {
            if (newIpAddress != null)
            {
                using (var serverManager = new ServerManager())
                {
                    // Configure the external IP address of the firewall.
                    serverManager.GetApplicationHostConfiguration()
                    .GetSection("system.applicationHost/sites")
                    .GetChildElement("siteDefaults")
                    .GetChildElement("ftpServer")
                    .GetChildElement("firewallSupport")
                    .SetAttributeValue("externalIp4Address", newIpAddress.ToString());

                    // Record updated sites.
                    if (MailModule.TemplateIISAdditionalDetails.ContainsKey("SITES"))
                    {
                        MailModule.TemplateIISAdditionalDetails["SITES"] = new Tuple <string, string, string> [serverManager.Sites.Count];
                    }
                    else
                    {
                        MailModule.TemplateIISAdditionalDetails.Add("SITES", new Tuple <string, string, string> [serverManager.Sites.Count]);
                    }

                    // Iterate sites and update ip.
                    for (var i = 0; i < serverManager.Sites.Count; i++)
                    {
                        // Current site.
                        var site = serverManager.Sites[i];

                        if (site.GetChildElement("ftpServer") != null)
                        {
                            // Get previous ip.
                            var previousIpAddress = site.GetChildElement("ftpServer")
                                                    .GetChildElement("firewallSupport")
                                                    .GetAttributeValue("externalIp4Address").ToString();

                            // Configure the external IP address of the firewall.
                            site.GetChildElement("ftpServer")
                            .GetChildElement("firewallSupport")
                            .SetAttributeValue("externalIp4Address", newIpAddress.ToString());

                            if (MailModule.TemplateIISAdditionalDetails.ContainsKey("SITES") &&
                                MailModule.TemplateIISAdditionalDetails["SITES"] is Tuple <string, string, string>[] sites)
                            {
                                // Record site.
                                sites[i] = new Tuple <string, string, string>(site.Name, previousIpAddress, newIpAddress.ToString());
                            }

                            // Log ip address update.
                            File.AppendAllText(WhatIsMyIp.LogFilePath + $@"{ DateTime.Now:(yyyy-MM-dd)}.log", $@"{DateTime.Now} - Updated IIS FTP Site ({site.Name}) External IP Address to: {newIpAddress}{Environment.NewLine}");
                        }
                    }

                    //Commit changes.
                    serverManager.CommitChanges();

                    if (serverManager.Sites.Count > 0)
                    {
                        // Send out email notification.
                        MailModule.Send(MailModule.SmtpHost, MailModule.SmtpPort,
                                        MailModule.EmailTo, MailModule.EmailFrom,
                                        @"IIS FTP Firewall External Ip Updated!", "SITES",
                                        MailModule.EnableSsl, MailModule.Templates.IIS);

                        // Send report to admin.
                        File.AppendAllText(WhatIsMyIp.LogFilePath + $@"{ DateTime.Now:(yyyy-MM-dd)}.log", $@"{DateTime.Now} - Email sent out to: {MailModule.EmailTo}{Environment.NewLine}{Environment.NewLine}");
                    }

                    // Update progress.
                    File.AppendAllText(WhatIsMyIp.LogFilePath + $@"{ DateTime.Now:(yyyy-MM-dd)}.log", $@"{DateTime.Now} - Update complete!{Environment.NewLine}{Environment.NewLine}");
                }
            }
        }
        public void SetUp()
        {
            const string Original     = @"original.config";
            const string OriginalMono = @"original.mono.config";

            if (Helper.IsRunningOnMono())
            {
                File.Copy("Website1/original.config", "Website1/web.config", true);
                File.Copy(OriginalMono, Current, true);
            }
            else
            {
                File.Copy("Website1\\original.config", "Website1\\web.config", true);
                File.Copy(Original, Current, true);
            }

            Environment.SetEnvironmentVariable(
                "JEXUS_TEST_HOME",
                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            _server = new ServerManager(Current)
            {
                Mode = WorkingMode.IisExpress
            };

            var serviceContainer = new ServiceContainer();

            serviceContainer.RemoveService(typeof(IConfigurationService));
            serviceContainer.RemoveService(typeof(IControlPanel));
            var scope = ManagementScope.Site;

            serviceContainer.AddService(typeof(IControlPanel), new ControlPanel());
            serviceContainer.AddService(
                typeof(IConfigurationService),
                new ConfigurationService(
                    null,
                    _server.Sites[0].GetWebConfiguration(),
                    scope,
                    null,
                    _server.Sites[0],
                    null,
                    null,
                    null,
                    _server.Sites[0].Name));

            serviceContainer.RemoveService(typeof(IManagementUIService));
            var mock = new Mock <IManagementUIService>();

            mock.Setup(
                action =>
                action.ShowMessage(
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    It.IsAny <MessageBoxButtons>(),
                    It.IsAny <MessageBoxIcon>(),
                    It.IsAny <MessageBoxDefaultButton>())).Returns(DialogResult.Yes);
            serviceContainer.AddService(typeof(IManagementUIService), mock.Object);

            var module = new CachingModule();

            module.TestInitialize(serviceContainer, null);

            _feature = new CachingFeature(module);
            _feature.Load();
        }
Exemplo n.º 30
0
        public static List <SiteInfo> GetSiteInfo()
        {
            List <SiteInfo> siteList = new List <SiteInfo>();

            if (TestMode)
            {
                siteList.Add(new SiteInfo(1, "Test Site", "TestAppPool", "%windir%\\inetpub\\logs\\", "running", "OK"));
            }
            else
            {
                try
                {
                    ServerManager  server = new ServerManager();
                    SiteCollection sites  = server.Sites;
                    foreach (Site site in sites)
                    {
                        //Get AdvancedLogging Directory
                        string SiteName = Convert.ToString(site.Name);
                        string LogPath;
                        string Status = "OK";
                        try {
                            //Load AppSettings to see if AdvancedLogging is configured
                            string AdvancedLoggingSiteDirectory = Settings.GetAppSetting("AdvancedLoggingSiteDirectory");
                            ConfigurationElement   logAttr      = site.GetChildElement("advancedLogging");
                            ConfigurationAttribute logPathAttr  = logAttr.GetAttribute("directory");
                            //Check the app.config to see AdvancedLogging site name directory format
                            if (AdvancedLoggingSiteDirectory == "%siteName")
                            {
                                if (Settings.GetAppSetting("AdvancedLoggingSiteDirectoryAllCaps") == "true")
                                {
                                    LogPath = "*" + Convert.ToString(logPathAttr.Value) + SiteName.ToUpper() + "\\";
                                }
                                else
                                {
                                    LogPath = "*" + Convert.ToString(logPathAttr.Value) + SiteName + "\\";
                                }
                            }
                            else if (AdvancedLoggingSiteDirectory != "error")
                            {
                                LogPath = "*" + Convert.ToString(logPathAttr.Value) + AdvancedLoggingSiteDirectory + "\\";
                            }
                            else
                            {
                                LogPath = "*" + Convert.ToString(logPathAttr.Value);
                            }
                            //Strip off any beginning identifiers and check if directory exists
                            if (!System.IO.Directory.Exists(@LogPath.Trim(new Char[] { ' ', '*', '.', '!' })))
                            {
                                LogPath = "!" + LogPath;
                                Status  = "error";
                            }
                        } catch (Exception ex)
                        {
                            //ApplicationDefaults defaults = site.ApplicationDefaults;
                            LogPath = Convert.ToString(site.LogFile);
                            Status  = "error";
                        }
                        site.Applications[0].ToString();

                        siteList.Add(new SiteInfo(Convert.ToInt32(site.Id), SiteName, site.Applications[0].ApplicationPoolName.ToString(), LogPath, site.State.ToString(), Status));
                    }
                }
                catch (Exception e)
                {
                    siteList.Add(new SiteInfo(0, "Error", "Error Loading Site", "Error", "Error", "Error"));
                    ErrorHandler.logError("Error Connecting to IIS Manager", "There was an error thrown while connecting to the IIS Manager, see inner exception for details", "error", true, e);
                }
            }
            return(siteList);
        }
Exemplo n.º 31
0
        private void RestartAspen()
        {
            int i = 1;

            while (i < 5)

            {
                var    serverName  = ConfigurationManager.AppSettings.Get("Borrego " + i);
                string appPoolName = ".NET 4.Aspen";


                if (!string.IsNullOrEmpty(serverName) && !string.IsNullOrEmpty(appPoolName))
                {
                    try
                    {
                        using (ServerManager manager = ServerManager.OpenRemote(serverName))
                        {
                            ApplicationPool appPool = manager.ApplicationPools.FirstOrDefault(ap => ap.Name == appPoolName);

                            //Don't bother trying to recycle if we don't have an app pool
                            if (appPool != null)
                            {
                                //Get the current state of the app pool
                                bool appPoolRunning = appPool.State == ObjectState.Started || appPool.State == ObjectState.Starting;
                                bool appPoolStopped = appPool.State == ObjectState.Stopped || appPool.State == ObjectState.Stopping;

                                //The app pool is running, so stop it first.
                                if (appPoolRunning)
                                {
                                    //Wait for the app to finish before trying to stop
                                    while (appPool.State == ObjectState.Starting)
                                    {
                                        System.Threading.Thread.Sleep(1000);
                                    }

                                    //Stop the app if it isn't already stopped
                                    if (appPool.State != ObjectState.Stopped)
                                    {
                                        appPool.Stop();
                                    }
                                    appPoolStopped = true;
                                }

                                //Only try restart the app pool if it was running in the first place, because there may be a reason it was not started.
                                if (appPoolStopped && appPoolRunning)
                                {
                                    //Wait for the app to finish before trying to start
                                    while (appPool.State == ObjectState.Stopping)
                                    {
                                        System.Threading.Thread.Sleep(1000);
                                    }

                                    //Start the app
                                    appPool.Start();
                                }
                                i++;
                            }
                            else
                            {
                                throw new Exception(string.Format("An Application Pool does not exist with the name {0}.{1}", serverName, appPoolName));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("Unable to restart the application pools for {0}.{1}", serverName, appPoolName), ex.InnerException);
                    }
                }
            }
        }
 public BpmonlineConfiguration(ServerManager serverManager)
 {
     _serverManager = serverManager;
     InitializeComponent();
 }
Exemplo n.º 33
0
 public ServerGameEndState(ServerManager manager) : base(manager)
 {
 }
Exemplo n.º 34
0
 public TcpNetServer()
 {
     messages = new Queue <NetIncomingMessage>();
     server   = new ServerManager();
 }
        public ServerBinding[] GetSiteBindings(ServerManager srvman, string siteId)
        {
			var iisObject = srvman.Sites[siteId];
			// get server bingings
			var bindings = new List<ServerBinding>();
			//
			foreach (var bindingObj in iisObject.Bindings)
			{
                // return only "http" bindings
                if (String.Equals(bindingObj.Protocol, Uri.UriSchemeHttp, StringComparison.InvariantCultureIgnoreCase))
                {
                    string[] parts = bindingObj.BindingInformation.Split(':');
                    // append binding
                    bindings.Add(new ServerBinding(bindingObj.Protocol, parts[0], parts[1], parts[2]));
                }
			}
			//
			return bindings.ToArray();
        }
Exemplo n.º 36
0
        private void InstallWebSites(string name, string directory, IEnumerable <WebSiteBinding> bindings, ServerManager iis)
        {
            if (bindings.Any())
            {
                var webServerBinding = bindings.First();
                var site             = iis.Sites.Add(name, webServerBinding.Protocol, webServerBinding.Information, directory);

                foreach (var b in bindings.Skip(1))
                {
                    site.Bindings.Add(b.Information, b.Protocol);
                }
            }
        }
    	public WebVirtualDirectory[] GetVirtualDirectories(ServerManager srvman, string siteId)
		{
            if (!SiteExists(srvman, siteId))
                return new WebVirtualDirectory[] { };

			var vdirs = new List<WebVirtualDirectory>();
			var iisObject = srvman.Sites[siteId];
			//
			foreach (var item in iisObject.Applications)
			{
				// Skip root application which is web site itself
				if (item.Path == "/")
					continue;
				//
				vdirs.Add(new WebVirtualDirectory
				{
					Name = ConfigurationUtility.GetNonQualifiedVirtualPath(item.Path),
					ContentPath = item.VirtualDirectories[0].PhysicalPath
				});
			}
			//
			return vdirs.ToArray();
		}
Exemplo n.º 38
0
    // Use this for initialization
    void Start()
    {
        insMenu = insMenu.GetComponent<Canvas>();
        insMenu.enabled = false;
        refreshButton.GetComponent<Text>().enabled = false;
        serverStartButton.GetComponent<Text>().enabled = false;
        roomButton.GetComponent<Text>().enabled = false;

        gm = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>();
        svrmgr = GameObject.FindGameObjectWithTag("NetworkManager").GetComponent<ServerManager>();
    }
        public void SetZooConsoleEnabled(ServerManager srvman, string siteId, string appName)
        {

            Random random = new Random((int) DateTime.Now.Ticks);
            byte[] bytes = new byte[8];
            random.NextBytes(bytes);
            string consoleUrl = "console_" + Convert.ToBase64String(bytes);
            SetZooEnvironmentVariable(srvman, siteId, appName, "CONSOLE_URL", consoleUrl);

        }
 public JObject Index()
 {
     return(this.BuildResponse(HttpStatusCode.OK).AddAttribute("servers", ServerManager.Save()));
 }
        public void SetZooEnvironmentVariable(ServerManager srvman, string siteId, string appName, string envName, string envValue)
        {
            if (!SiteExists(srvman, siteId))
                return;

            
            var iisObject = srvman.Sites[siteId];
            //
            foreach (var item in iisObject.Applications)
            {
                

                if (appName == ConfigurationUtility.GetNonQualifiedVirtualPath(item.Path))
                {
                    Configuration cfg = item.GetWebConfiguration();
                    ConfigurationSection section = cfg.GetSection("system.webServer/heliconZoo");
                    ConfigurationElement zooAppElement = section.GetCollection()[0];
                    ConfigurationElementCollection envColl = zooAppElement.GetChildElement("environmentVariables").GetCollection();

                    //remove all CONSOLE_URLs
                    for (int i = 0; i < envColl.Count; )
                    {
                        if (String.Compare(envColl[i].GetAttributeValue("name").ToString(), envName, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            envColl.RemoveAt(i);        
                        }
                        else
                        {
                            ++i;
                        }
                        
                    }

                    // do not set empty value
                    if (!string.IsNullOrEmpty(envValue))
                    {
                        ConfigurationElement el = envColl.CreateElement();
                        el.SetAttributeValue("name", envName);
                        el.SetAttributeValue("value", envValue);
                        envColl.Add(el);
                    }

                    
                    srvman.CommitChanges();
                }

              

            }
         
        }
Exemplo n.º 42
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            state = ClientState.Offline;
            serverManager = new ServerManager();
            regForm = new RegForm();
            gameForm = new GameForm();
            var i = gameForm.Handle;
            Context = new ApplicationContext(regForm);
            Application.Run(Context);
        }
Exemplo n.º 43
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            //FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider();
            //provider.Mappings[".image"] = "image/png";
            //provider.Mappings.Remove(".mp4");

            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),
            //    //RequestPath = new PathString("/imgs"),
            //    //ContentTypeProvider = provider,
            //    ContentTypeProvider = new MyContentTypeProvider(),
            //    DefaultContentType = "image/png",
            //    HttpsCompression = HttpsCompressionMode.Compress,
            //    ServeUnknownFileTypes = true,
            //    OnPrepareResponse = (response) =>
            //    {
            //        response.Context.Response.Headers[HeaderNames.CacheControl] = $"public,max-age=31536000";
            //        response.Context.Response.Headers[HeaderNames.Pragma] = $"public,max-age=31536000";
            //        response.Context.Response.Headers[HeaderNames.Expires] = DateTime.UtcNow.AddYears(1).ToString("R");

            //        if (response.Context.Request.Path.StartsWithSegments("/imgs"))
            //        {
            //            if (response.Context.User.Identity.IsAuthenticated)
            //            {
            //                if (response.Context.User.IsInRole("Admin"))
            //                {
            //                    return;
            //                }
            //                else
            //                {
            //                    response.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            //                    throw new UnauthorizedAccessException();
            //                }
            //            }
            //            else
            //            {
            //                response.Context.Response.Redirect("/Identity/Account/Login");
            //            }
            //        }
            //    }
            //});

            //UseDefaultFiles must be called before UseStaticFiles to serve the default file.
            //default.htm default.html index.htm index.html
            //app.UseDefaultFiles();
            // Serve my app-specific default file, if present.
            //DefaultFilesOptions options = new DefaultFilesOptions();
            //options.DefaultFileNames.Clear();
            //options.DefaultFileNames.Add("mydefault.html");
            //app.UseDefaultFiles(options);

            //app.UseStaticFiles(); // For the wwwroot folder
            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),
            //    RequestPath = "/StaticFiles"
            //});

            //app.UseStaticFiles(); // For the wwwroot folder
            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles", "imgs")),
            //    RequestPath = "/MyImages"
            //});
            //app.UseDirectoryBrowser(new DirectoryBrowserOptions
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles", "imgs")),
            //    RequestPath = "/MyImages"
            //});

            //UseFileServer combines the functionality of UseStaticFiles, UseDefaultFiles, and UseDirectoryBrowser.
            //app.UseFileServer();
            //The following code builds upon the parameterless overload by enabling directory browsing:
            //app.UseFileServer(enableDirectoryBrowsing: true);

            //Using the file hierarchy and preceding code, URLs resolve as follows:
            //URI                                                       Response
            //http://<server_address>/StaticFiles/images/banner1.svg	MyStaticFiles/images/banner1.svg
            //http://<server_address>/StaticFiles	                    MyStaticFiles/default.html
            app.UseStaticFiles(); // For the wwwroot folder
            app.UseFileServer(new FileServerOptions
            {
                FileProvider            = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),
                RequestPath             = "/MyStaticFiles",
                EnableDirectoryBrowsing = false,
            });

            //https://www.iana.org/assignments/media-types/media-types.xhtml    See MIME content types.
            // Set up custom content types - associating file extension to MIME type
            var provider = new FileExtensionContentTypeProvider();

            // Add new mappings
            provider.Mappings[".myapp"] = "application/x-msdownload";
            provider.Mappings[".htm3"]  = "text/html";
            provider.Mappings[".image"] = "image/png";
            // Replace an existing mapping
            provider.Mappings[".rtf"] = "application/x-msdownload";
            // Remove MP4 videos.
            provider.Mappings.Remove(".mp4");
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider                  = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "imgs")),
                RequestPath                   = "/MyImages",
                ContentTypeProvider           = provider,
                DefaultContentType            = "image/png",
                ServeUnknownFileTypes         = true,
                HttpsCompression              = HttpsCompressionMode.Compress,
                RedirectToAppendTrailingSlash = true,
                OnPrepareResponse             = (sfrc) =>
                {
                    if (sfrc.File.Exists && !sfrc.File.IsDirectory)
                    {
                        var name       = sfrc.File.Name;
                        var lastModify = sfrc.File.LastModified;
                        var length     = sfrc.File.Length;
                        var pp         = sfrc.File.PhysicalPath;
                        if (name.Contains("1") && length > 273519)
                        {
                            sfrc.Context.Response.Redirect("/Identity/Account/Login");
                        }
                    }

                    var startsWithSegmentsImages = sfrc.Context.Request.Path.StartsWithSegments("/MyImages");
                    var isAuthenticated          = sfrc.Context.User.Identity.IsAuthenticated;
                    var isInRoleAdmin            = sfrc.Context.User.IsInRole("Admin");
                    if (startsWithSegmentsImages)
                    {
                        if (isAuthenticated)
                        {
                            if (isInRoleAdmin)
                            {
                                return;
                            }
                            else
                            {
                                sfrc.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                                throw new UnauthorizedAccessException();
                            }
                        }
                        else
                        {
                            sfrc.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                            sfrc.Context.Response.Redirect("/Identity/Account/Login");
                        }
                    }
                }
            });
            app.UseDirectoryBrowser(new DirectoryBrowserOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "imgs")),
                RequestPath  = "/MyImages",
                RedirectToAppendTrailingSlash = true,
            });

            //Static File Middleware understands almost 400 known file content types
            //If no middleware handles the request, a 404 Not Found response is returned.
            //The following code enables serving unknown types and renders the unknown file as an image:
            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    ServeUnknownFileTypes = true,
            //    DefaultContentType = "image/png"
            //});

            using (ServerManager serverManager = new ServerManager())
            {
                Configuration config = serverManager.GetWebConfiguration("Contoso");

                // var directoryBrowseSection = config.GetSection("system.webServer/directoryBrowse");

                //enabled Optional Boolean attribute.
                //Specifies whether directory browsing is enabled (true) or disabled (false) on the Web server.
                //The default value is false.

                //directoryBrowseSection["enabled"] = true;

                //showFlags Optional flags attribute.
                //The showFlags attribute can have one or more of the following possible values.
                //If you specify more than one value, separate the values with a comma (,).
                //The default values are Date, Time, Size, Extension.
                //Value       Description
                //Date        Includes the last modified date for a file or directory in a directory listing.
                //Extension   Includes a file name extension for a file in a directory listing.
                //LongDate    Includes the last modified date in extended format for a file in a directory listing.
                //None        Specifies that only the file or directory names are returned in a directory listing.
                //Size        Includes the file size for a file in a directory listing.
                //Time        Includes the last modified time for a file or directory in a directory listing.

                //directoryBrowseSection["showFlags"] = @"Date, Time, Size, Extension, LongDate";

                serverManager.CommitChanges();
            }

            //◘◘◘◘◘◘◘◘

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
Exemplo n.º 44
0
        /// <summary>
        /// Removes the application - reachable at the specified port - and its application pools from IIS.
        /// Note: Stops the application pools and the application if necessary
        /// </summary>
        /// <param name="port">The port.</param>
        private static void Delete(int port)
        {
            mut.WaitOne();

            try
            {
                using (ServerManager serverMgr = new ServerManager())
                {
                    Site currentSite = null;
                    foreach (Site site in serverMgr.Sites)
                    {
                        if (site.Bindings != null && site.Bindings[0] != null && site.Bindings[0].EndPoint != null && site.Bindings[0].EndPoint.Port == port)
                        {
                            currentSite = site;
                            break;
                        }
                    }

                    int retryCount = 20;
                    while (retryCount > 0)
                    {
                        try
                        {
                            serverMgr.Sites[currentSite.Name].Stop();
                            break;
                        }
                        catch (System.Runtime.InteropServices.COMException)
                        {
                            // todo log exception
                        }

                        retryCount--;
                    }

                    int time = 0;
                    while (serverMgr.Sites[currentSite.Name].State != ObjectState.Stopped && time < 300)
                    {
                        Thread.Sleep(100);
                        time++;
                    }

                    if (time == 300)
                    {
                        KillApplicationProcesses(currentSite.Applications["/"].ApplicationPoolName);
                    }

                    serverMgr.Sites.Remove(currentSite);
                    serverMgr.CommitChanges();
                    FirewallTools.ClosePort(port);
                    ApplicationPool applicationPool = serverMgr.ApplicationPools[currentSite.Applications["/"].ApplicationPoolName];
                    serverMgr.ApplicationPools[applicationPool.Name].Stop();
                    time = 0;
                    while (serverMgr.ApplicationPools[applicationPool.Name].State != ObjectState.Stopped && time < 300)
                    {
                        Thread.Sleep(100);
                        time++;
                    }

                    if (serverMgr.ApplicationPools[applicationPool.Name].State != ObjectState.Stopped && time == 300)
                    {
                        KillApplicationProcesses(applicationPool.Name);
                    }

                    serverMgr.ApplicationPools.Remove(applicationPool);
                    serverMgr.CommitChanges();
                    string username = null;
                    username = applicationPool.ProcessModel.UserName;
                    if (username != null)
                    {
                        string path = currentSite.Applications["/"].VirtualDirectories["/"].PhysicalPath;
                        if (Directory.Exists(path))
                        {
                            DirectoryInfo     deploymentDir         = new DirectoryInfo(path);
                            DirectorySecurity deploymentDirSecurity = deploymentDir.GetAccessControl();
                            deploymentDirSecurity.RemoveAccessRuleAll(new FileSystemAccessRule(username, FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify, AccessControlType.Allow));
                            deploymentDir.SetAccessControl(deploymentDirSecurity);
                        }
                    }
                }
            }
            finally
            {
                mut.ReleaseMutex();
            }
        }
Exemplo n.º 45
0
        private void InstallWebApplications(string directory, IEnumerable <WebSiteBinding> bindings, ServerManager iis)
        {
            if (bindings.Any())
            {
                var bindingGroups = bindings.GroupBy(b => new BindingGroup {
                    Information = b.Information, Protocol = b.Protocol
                });

                foreach (var bindingGroup in bindingGroups)
                {
                    var site = iis.Sites.Single(s => s.Bindings.Any(b => b.BindingInformation == bindingGroup.Key.Information && b.Protocol == bindingGroup.Key.Protocol));
                    foreach (var webSiteBinding in bindingGroup)
                    {
                        site.Applications.Add(webSiteBinding.Path, directory);
                    }
                }
            }
        }
Exemplo n.º 46
0
        public static void Main(string[] args)
        {
            var consoleTitle = $"ACEmulator - v{ServerBuildInfo.FullVersion}";

            Console.Title = consoleTitle;

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit        += new EventHandler(OnProcessExit);

            // Typically, you wouldn't force the current culture on an entire application unless you know sure your application is used in a specific region (which ACE is not)
            // We do this because almost all of the client/user input/output code does not take culture into account, and assumes en-US formatting.
            // Without this, many commands that require special characters like , and . will break
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            // Init our text encoding options. This will allow us to use more than standard ANSI text, which the client also supports.
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

            // Look for the log4net.config first in the current environment directory, then in the ExecutingAssembly location
            var exeLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var containerConfigDirectory = "/ace/Config";
            var log4netConfig            = Path.Combine(exeLocation, "log4net.config");
            var log4netConfigExample     = Path.Combine(exeLocation, "log4net.config.example");
            var log4netConfigContainer   = Path.Combine(containerConfigDirectory, "log4net.config");

            if (IsRunningInContainer && File.Exists(log4netConfigContainer))
            {
                File.Copy(log4netConfigContainer, log4netConfig, true);
            }

            var log4netFileInfo = new FileInfo("log4net.config");

            if (!log4netFileInfo.Exists)
            {
                log4netFileInfo = new FileInfo(log4netConfig);
            }

            if (!log4netFileInfo.Exists)
            {
                var exampleFile = new FileInfo(log4netConfigExample);
                if (!exampleFile.Exists)
                {
                    Console.WriteLine("log4net Configuration file is missing.  Please copy the file log4net.config.example to log4net.config and edit it to match your needs before running ACE.");
                    throw new Exception("missing log4net configuration file");
                }
                else
                {
                    if (!IsRunningInContainer)
                    {
                        Console.WriteLine("log4net Configuration file is missing,  cloning from example file.");
                        File.Copy(log4netConfigExample, log4netConfig);
                    }
                    else
                    {
                        if (!File.Exists(log4netConfigContainer))
                        {
                            Console.WriteLine("log4net Configuration file is missing, ACEmulator is running in a container,  cloning from docker file.");
                            var log4netConfigDocker = Path.Combine(exeLocation, "log4net.config.docker");
                            File.Copy(log4netConfigDocker, log4netConfig);
                            File.Copy(log4netConfigDocker, log4netConfigContainer);
                        }
                        else
                        {
                            File.Copy(log4netConfigContainer, log4netConfig);
                        }
                    }
                }
            }

            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());

            XmlConfigurator.ConfigureAndWatch(logRepository, log4netFileInfo);

            if (Environment.ProcessorCount < 2)
            {
                log.Warn("Only one vCPU was detected. ACE may run with limited performance. You should increase your vCPU count for anything more than a single player server.");
            }

            // Do system specific initializations here
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // On many windows systems, the default resolution for Thread.Sleep is 15.6ms. This allows us to command a tighter resolution
                    MM_BeginPeriod(1);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }

            log.Info("Starting ACEmulator...");

            if (IsRunningInContainer)
            {
                log.Info("ACEmulator is running in a container...");
            }

            var configFile            = Path.Combine(exeLocation, "Config.js");
            var configConfigContainer = Path.Combine(containerConfigDirectory, "Config.js");

            if (IsRunningInContainer && File.Exists(configConfigContainer))
            {
                File.Copy(configConfigContainer, configFile, true);
            }

            if (!File.Exists(configFile))
            {
                if (!IsRunningInContainer)
                {
                    DoOutOfBoxSetup(configFile);
                }
                else
                {
                    if (!File.Exists(configConfigContainer))
                    {
                        DoOutOfBoxSetup(configFile);
                        File.Copy(configFile, configConfigContainer);
                    }
                    else
                    {
                        File.Copy(configConfigContainer, configFile);
                    }
                }
            }

            log.Info("Initializing ConfigManager...");
            ConfigManager.Initialize();

            if (ConfigManager.Config.Server.WorldName != "ACEmulator")
            {
                consoleTitle  = $"{ConfigManager.Config.Server.WorldName} | {consoleTitle}";
                Console.Title = consoleTitle;
            }

            if (ConfigManager.Config.Offline.PurgeDeletedCharacters)
            {
                log.Info($"Purging deleted characters, and their possessions, older than {ConfigManager.Config.Offline.PurgeDeletedCharactersDays} days ({DateTime.Now.AddDays(-ConfigManager.Config.Offline.PurgeDeletedCharactersDays)})...");
                ShardDatabaseOfflineTools.PurgeCharactersInParallel(ConfigManager.Config.Offline.PurgeDeletedCharactersDays, out var charactersPurged, out var playerBiotasPurged, out var possessionsPurged);
                log.Info($"Purged {charactersPurged:N0} characters, {playerBiotasPurged:N0} player biotas and {possessionsPurged:N0} possessions.");
            }

            if (ConfigManager.Config.Offline.PurgeOrphanedBiotas)
            {
                log.Info($"Purging orphaned biotas...");
                ShardDatabaseOfflineTools.PurgeOrphanedBiotasInParallel(out var numberOfBiotasPurged);
                log.Info($"Purged {numberOfBiotasPurged:N0} biotas.");
            }

            if (ConfigManager.Config.Offline.AutoUpdateWorldDatabase)
            {
                CheckForWorldDatabaseUpdate();

                if (ConfigManager.Config.Offline.AutoApplyWorldCustomizations)
                {
                    AutoApplyWorldCustomizations();
                }
            }
            else
            {
                log.Info($"AutoUpdateWorldDatabase is disabled...");
            }

            if (ConfigManager.Config.Offline.AutoApplyDatabaseUpdates)
            {
                AutoApplyDatabaseUpdates();
            }
            else
            {
                log.Info($"AutoApplyDatabaseUpdates is disabled...");
            }

            // This should only be enabled manually. To enable it, simply uncomment this line
            //ACE.Database.OfflineTools.Shard.BiotaGuidConsolidator.ConsolidateBiotaGuids(0xC0000000, out int numberOfBiotasConsolidated, out int numberOfErrors);

            ShardDatabaseOfflineTools.CheckForBiotaPropertiesPaletteOrderColumnInShard();

            log.Info("Initializing ServerManager...");
            ServerManager.Initialize();

            log.Info("Initializing DatManager...");
            DatManager.Initialize(ConfigManager.Config.Server.DatFilesDirectory, true);

            log.Info("Initializing DatabaseManager...");
            DatabaseManager.Initialize();

            if (DatabaseManager.InitializationFailure)
            {
                log.Fatal("DatabaseManager initialization failed. ACEmulator will now abort startup.");
                ServerManager.StartupAbort();
                Environment.Exit(0);
            }

            log.Info("Starting DatabaseManager...");
            DatabaseManager.Start();

            log.Info("Starting PropertyManager...");
            PropertyManager.Initialize();

            log.Info("Initializing GuidManager...");
            GuidManager.Initialize();

            if (ConfigManager.Config.Server.ServerPerformanceMonitorAutoStart)
            {
                log.Info("Server Performance Monitor auto starting...");
                ServerPerformanceMonitor.Start();
            }

            if (ConfigManager.Config.Server.WorldDatabasePrecaching)
            {
                log.Info("Precaching Weenies...");
                DatabaseManager.World.CacheAllWeenies();
                log.Info("Precaching Cookbooks...");
                DatabaseManager.World.CacheAllCookbooks();
                log.Info("Precaching Events...");
                DatabaseManager.World.GetAllEvents();
                log.Info("Precaching House Portals...");
                DatabaseManager.World.CacheAllHousePortals();
                log.Info("Precaching Points Of Interest...");
                DatabaseManager.World.CacheAllPointsOfInterest();
                log.Info("Precaching Spells...");
                DatabaseManager.World.CacheAllSpells();
                log.Info("Precaching Treasures - Death...");
                DatabaseManager.World.CacheAllTreasuresDeath();
                log.Info("Precaching Treasures - Material Base...");
                DatabaseManager.World.CacheAllTreasureMaterialBase();
                log.Info("Precaching Treasures - Material Groups...");
                DatabaseManager.World.CacheAllTreasureMaterialGroups();
                log.Info("Precaching Treasures - Material Colors...");
                DatabaseManager.World.CacheAllTreasureMaterialColor();
                log.Info("Precaching Treasures - Wielded...");
                DatabaseManager.World.CacheAllTreasureWielded();
            }
            else
            {
                log.Info("Precaching World Database Disabled...");
            }

            log.Info("Initializing PlayerManager...");
            PlayerManager.Initialize();

            log.Info("Initializing HouseManager...");
            HouseManager.Initialize();

            log.Info("Initializing InboundMessageManager...");
            InboundMessageManager.Initialize();

            log.Info("Initializing SocketManager...");
            SocketManager.Initialize();

            log.Info("Initializing WorldManager...");
            WorldManager.Initialize();

            log.Info("Initializing EventManager...");
            EventManager.Initialize();

            // Free up memory before the server goes online. This can free up 6 GB+ on larger servers.
            log.Info("Forcing .net garbage collection...");
            for (int i = 0; i < 10; i++)
            {
                GC.Collect();
            }

            // This should be last
            log.Info("Initializing CommandManager...");
            CommandManager.Initialize();

            if (!PropertyManager.GetBool("world_closed", false).Item)
            {
                WorldManager.Open(null);
            }
        }
Exemplo n.º 47
0
 /// <summary>
 /// Initializes a new instance of the class.
 /// </summary>
 public DcsLabNodeManager(ServerManager server) : base(server)
 {
 }
Exemplo n.º 48
0
        public void MissingWebsiteConfig()
        {
            var directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            Environment.SetEnvironmentVariable("JEXUS_TEST_HOME", directoryName);

            if (directoryName == null)
            {
                return;
            }

            string Current  = Path.Combine(directoryName, @"applicationHost.config");
            string Original = Path.Combine(directoryName, @"original2.config");
            string Expected = Path.Combine(directoryName, @"expected.config");

            File.Copy(Original, Current, true);
            TestHelper.FixPhysicalPathMono(Current);
            File.Delete(TestHelper.GetSiteConfig(directoryName));

#if IIS
            var server = new ServerManager(Current);
#else
            var server = new IisExpressServerManager(Current);
#endif
            TestCases.IisExpressMissingWebsiteConfig(server);

            {
                // reorder entities to match IIS result.
                var file = XDocument.Load(Current);
                var root = file.Root;
                if (root == null)
                {
                    return;
                }

                var pool = root.XPathSelectElement("/configuration/system.applicationHost/applicationPools/add[@name='Clr4IntegratedAppPool']");
                pool.SetAttributeValue("managedPipelineMode", "Integrated");
#if !IIS
                var windows = root.XPathSelectElement("/configuration/location[@path='WebSite2']/system.webServer/security/authentication/windowsAuthentication");
                windows?.SetAttributeValue("enabled", true);

                var security = root.XPathSelectElement("/configuration/location[@path='WebSite1']/system.webServer/security");
                security.Remove();
                var httpLogging = root.XPathSelectElement("/configuration/location[@path='WebSite1']/system.webServer/httpLogging");
                httpLogging.AddAfterSelf(security);

                var extended = windows.Element("extendedProtection");
                extended?.SetAttributeValue("flags", "None");
#endif
                file.Save(Current);
            }

            {
                // reorder entities to match IIS result.
                var file = XDocument.Load(TestHelper.GetSiteConfig(directoryName));
                var root = file.Root;
                if (root == null)
                {
                    return;
                }

                var top           = root.XPathSelectElement("/configuration/system.webServer/defaultDocument");
                var staticContent = root.XPathSelectElement("/configuration/system.webServer/staticContent");
                staticContent?.Remove();
                top.AddBeforeSelf(staticContent);
#if !IIS
                var rewrite        = root.XPathSelectElement("/configuration/system.webServer/rewrite");
                var urlCompression = root.XPathSelectElement("/configuration/system.webServer/urlCompression");
                urlCompression.Remove();
                var httpErrors = root.XPathSelectElement("/configuration/system.webServer/httpErrors");
                httpErrors?.Remove();
                var security = root.XPathSelectElement("/configuration/system.webServer/security");
                security.Remove();
                rewrite.AddAfterSelf(httpErrors, urlCompression, security);
                httpErrors?.Element("error")?.SetAttributeValue("prefixLanguageFilePath", string.Empty);
                httpErrors?.Element("error")?.SetAttributeValue("responseMode", "File");

                // IMPORTANT: workaround an IIS issue.
                var document = root.XPathSelectElement("/configuration/system.webServer/defaultDocument/files/add[@value='index.htm']");
                var item     = new XElement("add",
                                            new XAttribute("value", "index.html"));
                document?.AddAfterSelf(item);

                var clear  = root.XPathSelectElement("/configuration/system.webServer/defaultDocument/files/clear");
                var remove = new XElement("remove",
                                          new XAttribute("value", "index.html"));
                clear?.AddAfterSelf(remove);
#endif
                file.Save(TestHelper.GetSiteConfig(directoryName));
            }

            TestHelper.FixPhysicalPathMono(Expected);
            XmlAssert.Equal(Expected, Current);
            TestHelper.AssertSiteConfig(directoryName, "expected1.config");
        }
Exemplo n.º 49
0
 public TcpNetServer()
 {
     messages = new Queue<NetIncomingMessage>();
     server = new ServerManager();
 }
 /// <summary>
 /// Initializes a new instance of <see cref="AudioModule"/> class.
 /// </summary>
 public AudioParrotModule(ServerManager server)
 {
     _servers = server;
 }
Exemplo n.º 51
0
 /// <summary>
 /// Initializes a new instance of the class.
 /// </summary>
 public OPCServerNodeManager(ServerManager server)
     : base(server)
 {
 }
Exemplo n.º 52
0
 public ServersByExitNodeViewModel(string countryCode, sbyte userTier, ServerManager serverManager)
 {
     CountryCode    = countryCode;
     _userTier      = userTier;
     _serverManager = serverManager;
 }
Exemplo n.º 53
0
 private void Awake()
 {
     serverManager = gameObject.GetComponent <ServerManager>();
 }
Exemplo n.º 54
0
        public SslDiagDialog(IServiceProvider provider, ServerManager server)
            : base(provider)
        {
            InitializeComponent();

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnGenerate, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                txtResult.Clear();
                try
                {
                    Debug($"System Time: {DateTime.Now}");
                    Debug($"Processor Architecture: {Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE")}");
                    Debug($"OS: {Environment.OSVersion}");
                    Debug($"{server.Type}");
                    Debug(Environment.NewLine);
                    Debug($"SERVER SSL PROTOCOLS{Environment.NewLine}");
                    Debug($"PCT 1.0: {GetProtocol("PCT 1.0")}");
                    Debug($"SSL 2.0: {GetProtocol("SSL 2.0")}");
                    Debug($"SSL 3.0: {GetProtocol("SSL 3.0")}");
                    Debug($"TLS 1.0: {GetProtocol("TLS 1.0")}");
                    Debug($"TLS 1.1: {GetProtocol("TLS 1.1")}");
                    Debug($"TLS 1.2: {GetProtocol("TLS 1.2")}");

                    Debug($"SChannel EventLogging: {GetEventLogging()} (hex)");
                    Debug("-----");

                    foreach (Site site in server.Sites)
                    {
                        Debug($"[W3SVC/{site.Id}]");
                        Debug($"ServerComment  : {site.Name}");
                        Debug($"ServerAutoStart: {site.ServerAutoStart}");
                        Debug($"ServerState    : {site.State}");
                        Debug(string.Empty);
                        foreach (Binding binding in site.Bindings)
                        {
                            Info($"BINDING: {binding.Protocol} {binding}");
                            if (binding.Protocol == "https")
                            {
                                var hashString = Hex.ToHexString(binding.CertificateHash);
                                Debug($"SSLCertHash: {hashString}");
                                if (site.Server.SupportsSni)
                                {
                                    Debug($"SSL Flags: {binding.SslFlags}");
                                }

                                Debug("Testing EndPoint: 127.0.0.1");

                                var personal = new X509Store(binding.CertificateStoreName, StoreLocation.LocalMachine);
                                try
                                {
                                    personal.Open(OpenFlags.MaxAllowed);
                                    var selectedItem = personal.Certificates.Find(X509FindType.FindByThumbprint, hashString, false);
                                    if (selectedItem.Count == 0)
                                    {
                                        Error($"Cannot find certificate with thumbprint {hashString} in store {binding.CertificateStoreName}.");
                                    }
                                    else
                                    {
                                        var cert = selectedItem[0];
                                        Debug($"#CertName: {cert.FriendlyName}");
                                        Debug($"#Version: {cert.Version}");
                                        if (cert.HasPrivateKey)
                                        {
                                            Debug("#You have a private key that corresponds to this certificate.");
                                        }
                                        else
                                        {
                                            Error("#You don't have a private key that corresponds to this certificate.");
                                        }

                                        var key = cert.PublicKey.Key;
                                        Debug($"#Signature Algorithm: {cert.SignatureAlgorithm.FriendlyName}");
                                        Debug($"#Key Exchange Algorithm: {key.KeyExchangeAlgorithm} Key Size: {key.KeySize}");
                                        Debug($"#Subject: {cert.Subject}");
                                        Debug($"#Issuer: {cert.Issuer}");
                                        Debug($"#Validity: From {cert.NotBefore:U} To {cert.NotAfter:U}");
                                        Debug($"#Serial Number: {cert.SerialNumber}");
                                        Debug($"DS Mapper Usage: {(binding.UseDsMapper ? "Enabled" : "Disabled")}");
                                        Debug($"Archived: {cert.Archived}");

                                        foreach (var extension in cert.Extensions)
                                        {
                                            if (extension.Oid.FriendlyName == "Key Usage")
                                            {
                                                Debug($"#Key Usage: {((X509KeyUsageExtension)extension).KeyUsages}");
                                                continue;
                                            }

                                            if (extension.Oid.FriendlyName == "Enhanced Key Usage")
                                            {
                                                var usages           = ((X509EnhancedKeyUsageExtension)extension).EnhancedKeyUsages;
                                                var enhancedKeyUsage = usages.Cast <Oid>().Select(usage => $"{usage.FriendlyName} ({usage.Value})")
                                                                       .Combine(",");

                                                Debug($"#Enhanced Key Usage: {enhancedKeyUsage}");
                                                continue;
                                            }

                                            if (extension.Oid.FriendlyName == "Basic Constraints")
                                            {
                                                var ext = (X509BasicConstraintsExtension)extension;
                                                Debug(
                                                    $"#Basic Constraints: Subject Type={(ext.CertificateAuthority ? "CA" : "End Entity")}, Path Length Constraint={(ext.HasPathLengthConstraint ? ext.PathLengthConstraint.ToString() : "None")}");
                                            }
                                        }

                                        X509Chain chain        = X509Chain.Create();
                                        X509ChainPolicy policy = new X509ChainPolicy();
                                        policy.RevocationMode  = X509RevocationMode.NoCheck;
                                        chain.ChainPolicy      = policy;
                                        bool valid             = chain.Build(cert);
                                        if (valid)
                                        {
                                            Debug("Certificate verified.");
                                        }
                                        else
                                        {
                                            Error("Certificate valication failed.");
                                        }

                                        foreach (var item in chain.ChainStatus)
                                        {
                                            Warn(item.StatusInformation);
                                        }
                                    }

                                    personal.Close();
                                }
                                catch (CryptographicException ex)
                                {
                                    if (ex.HResult != NativeMethods.NonExistingStore)
                                    {
                                        throw;
                                    }

                                    Error($"Invalid certificate store {binding.CertificateStoreName}.");
                                }
                            }

                            Debug(string.Empty);
                        }
                    }
                }
                catch (CryptographicException ex)
                {
                    Debug(ex.ToString());
                    RollbarDotNet.Rollbar.Report(ex, custom: new Dictionary <string, object> {
                        { "hResult", ex.HResult }
                    });
                }
                catch (Exception ex)
                {
                    Debug(ex.ToString());
                    RollbarDotNet.Rollbar.Report(ex);
                }
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnSave, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                var dialog = new SaveFileDialog
                {
                    Filter = "Text Files|*.txt|All Files|*.*"
                };
                if (dialog.ShowDialog() == DialogResult.Cancel)
                {
                    return;
                }

                File.WriteAllText(dialog.FileName, txtResult.Text);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnVerify, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                txtResult.Clear();
            }));
        }
Exemplo n.º 55
0
 private Server(ServerManager manager)
 {
     this.manager = manager;
 }
Exemplo n.º 56
0
 public BasicNetworkEvent(string action, ArrayList data, ServerManager serverManager)
 {
     this.action        = action;
     this.data          = data;
     this.serverManager = serverManager;
 }
Exemplo n.º 57
0
 static void Main(string[] args)
 {
     serverManager = new ServerManager();
 }
Exemplo n.º 58
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="applicationPoolName"></param>
 /// <param name="identityType"></param>
 /// <param name="applicationPoolIdentity"></param>
 /// <param name="password"></param>
 /// <param name="managedRuntimeVersion"></param>
 /// <param name="autoStart"></param>
 /// <param name="enable32BitAppOnWin64"></param>
 /// <param name="managedPipelineMode"></param>
 /// <param name="queueLength"></param>
 /// <param name="idleTimeout"></param>
 /// <param name="periodicRestartPrivateMemory"></param>
 /// <param name="periodicRestartTime"></param>
 /// <returns></returns>
 public static bool CreateApplicationPool(string applicationPoolName, ProcessModelIdentityType identityType, string applicationPoolIdentity, string password,
                                          string managedRuntimeVersion, bool autoStart, bool enable32BitAppOnWin64, ManagedPipelineMode managedPipelineMode, long queueLength, TimeSpan idleTimeout,
                                          long periodicRestartPrivateMemory, TimeSpan periodicRestartTime)
 {
     try
     {
         if (identityType == ProcessModelIdentityType.SpecificUser)
         {
             if (string.IsNullOrEmpty(applicationPoolName))
             {
                 throw new ArgumentNullException("applicationPoolName", "CreateApplicationPool: applicationPoolName is null or empty.");
             }
             if (string.IsNullOrEmpty(applicationPoolIdentity))
             {
                 throw new ArgumentNullException("applicationPoolIdentity", "CreateApplicationPool: applicationPoolIdentity is null or empty.");
             }
             if (string.IsNullOrEmpty(password))
             {
                 throw new ArgumentNullException("password", "CreateApplicationPool: password is null or empty.");
             }
         }
         using (ServerManager mgr = new ServerManager())
         {
             ApplicationPool newAppPool = mgr.ApplicationPools.Add(applicationPoolName);
             if (identityType == ProcessModelIdentityType.SpecificUser)
             {
                 newAppPool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser;
                 newAppPool.ProcessModel.UserName     = applicationPoolIdentity;
                 newAppPool.ProcessModel.Password     = password;
             }
             else
             {
                 newAppPool.ProcessModel.IdentityType = identityType;
             }
             if (!string.IsNullOrEmpty(managedRuntimeVersion))
             {
                 newAppPool.ManagedRuntimeVersion = managedRuntimeVersion;
             }
             newAppPool.AutoStart             = autoStart;
             newAppPool.Enable32BitAppOnWin64 = enable32BitAppOnWin64;
             newAppPool.ManagedPipelineMode   = managedPipelineMode;
             if (queueLength > 0)
             {
                 newAppPool.QueueLength = queueLength;
             }
             if (idleTimeout != TimeSpan.MinValue)
             {
                 newAppPool.ProcessModel.IdleTimeout = idleTimeout;
             }
             if (periodicRestartPrivateMemory > 0)
             {
                 newAppPool.Recycling.PeriodicRestart.PrivateMemory = periodicRestartPrivateMemory;
             }
             if (periodicRestartTime != TimeSpan.MinValue)
             {
                 newAppPool.Recycling.PeriodicRestart.Time = periodicRestartTime;
             }
             mgr.CommitChanges();
         }
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message, ex);
     }
     return(true);
 }
Exemplo n.º 59
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="siteName"></param>
        /// <param name="applicationPath"></param>
        /// <param name="applicationPool"></param>
        /// <param name="virtualDirectoryPath"></param>
        /// <param name="physicalPath"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool AddApplication(string siteName, string applicationPath, string applicationPool, string virtualDirectoryPath, string physicalPath, string userName, string password)
        {
            try
            {
                if (string.IsNullOrEmpty(siteName))
                {
                    throw new ArgumentNullException("siteName", "AddApplication: siteName is null or empty.");
                }
                if (string.IsNullOrEmpty(applicationPath))
                {
                    throw new ArgumentNullException("applicationPath", "AddApplication: application path is null or empty.");
                }
                if (string.IsNullOrEmpty(physicalPath))
                {
                    throw new ArgumentNullException("PhysicalPath", "AddApplication: Invalid physical path.");
                }
                if (string.IsNullOrEmpty(applicationPool))
                {
                    throw new ArgumentNullException("ApplicationPool", "AddApplication: application pool namespace is Nullable or empty.");
                }
                using (ServerManager mgr = new ServerManager())
                {
                    ApplicationPool appPool = mgr.ApplicationPools[applicationPool];
                    if (appPool == null)
                    {
                        throw new Exception("Application Pool: " + applicationPool + " does not exist.");
                    }

                    Site site = mgr.Sites[siteName];
                    if (site != null)
                    {
                        Application app = site.Applications[applicationPath];
                        if (app != null)
                        {
                            throw new Exception("Application: " + applicationPath + " already exists.");
                        }
                        else
                        {
                            app      = site.Applications.CreateElement();
                            app.Path = applicationPath;
                            app.ApplicationPoolName = applicationPool;
                            VirtualDirectory vDir = app.VirtualDirectories.CreateElement();
                            vDir.Path         = virtualDirectoryPath;
                            vDir.PhysicalPath = physicalPath;
                            if (!string.IsNullOrEmpty(userName))
                            {
                                if (string.IsNullOrEmpty(password))
                                {
                                    throw new Exception("Invalid Virtual Directory User Account Password.");
                                }
                                else
                                {
                                    vDir.UserName = userName;
                                    vDir.Password = password;
                                }
                            }
                            app.VirtualDirectories.Add(vDir);
                        }
                        site.Applications.Add(app);
                        mgr.CommitChanges();
                        return(true);
                    }
                    else
                    {
                        throw new Exception("Site: " + siteName + " does not exist.");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
Exemplo n.º 60
0
        public static void OnUpdate()
        {
            if (ServerManager.ColonyTracker != null)
            {
                foreach (var colony in ServerManager.ColonyTracker.ColoniesByID.Values)
                {
                    if (_magicUpdateTime < Time.SecondsSinceStartDouble)
                    {
                        foreach (var follower in colony.Followers)
                        {
                            var inv = SettlerInventory.GetSettlerInventory(follower);

                            if (inv.MagicItemUpdateTime < Time.SecondsSinceStartDouble)
                            {
                                foreach (var item in inv.Armor)
                                {
                                    if (item.Value.Id != 0 && ArmorFactory.ArmorLookup.TryGetValue(item.Value.Id, out var armor))
                                    {
                                        armor.Update();

                                        if (armor.HPTickRegen != 0)
                                        {
                                            follower.Heal(armor.HPTickRegen);
                                        }
                                    }
                                }

                                if (Items.Weapons.WeaponFactory.WeaponLookup.TryGetValue(inv.Weapon.Id, out var wep))
                                {
                                    wep.Update();

                                    if (wep.HPTickRegen != 0)
                                    {
                                        follower.Heal(wep.HPTickRegen);
                                    }
                                }

                                var hasBandages = colony.Stockpile.Contains(TreatedBandage.Item.ItemIndex) ||
                                                  colony.Stockpile.Contains(Bandage.Item.ItemIndex);

                                if (hasBandages &&
                                    follower.health < follower.Colony.NPCHealthMax &&
                                    !HealingOverTimeNPC.NPCIsBeingHealed(follower))
                                {
                                    var healing = false;

                                    if (follower.Colony.NPCHealthMax - follower.health > TreatedBandage.INITIALHEAL)
                                    {
                                        colony.Stockpile.TryRemove(TreatedBandage.Item.ItemIndex);
                                        healing = true;
                                        ServerManager.SendAudio(follower.Position.Vector, GameLoader.NAMESPACE + ".Bandage");

                                        var heal = new HealingOverTimeNPC(follower, TreatedBandage.INITIALHEAL,
                                                                          TreatedBandage.TOTALHOT, 5,
                                                                          TreatedBandage.Item.ItemIndex);
                                    }

                                    if (!healing)
                                    {
                                        colony.Stockpile.TryRemove(Bandage.Item.ItemIndex);
                                        healing = true;
                                        ServerManager.SendAudio(follower.Position.Vector, GameLoader.NAMESPACE + ".Bandage");

                                        var heal = new HealingOverTimeNPC(follower, Bandage.INITIALHEAL, Bandage.TOTALHOT, 5,
                                                                          Bandage.Item.ItemIndex);
                                    }
                                }


                                inv.MagicItemUpdateTime += 5000;
                            }
                        }
                    }


                    if (_updateTime < Time.SecondsSinceStartDouble && colony.OwnerIsOnline())
                    {
                        NPCBase lastNPC = null;

                        foreach (var follower in colony.Followers)
                        {
                            if (TimeCycle.IsDay)
                            {
                                if (lastNPC == null ||
                                    UnityEngine.Vector3.Distance(lastNPC.Position.Vector, follower.Position.Vector) > 15 &&
                                    Random.NextBool())
                                {
                                    lastNPC = follower;
                                    ServerManager.SendAudio(follower.Position.Vector, GameLoader.NAMESPACE + ".TalkingAudio");
                                }
                            }
                        }
                    }

                    var cs = ColonyState.GetColonyState(colony);

                    if (cs.SettlersEnabled)
                    {
                        if (EvaluateSettlers(cs) ||
                            EvaluateLaborers(cs) ||
                            EvaluateBeds(cs))
                        {
                            colony.SendCommonData();
                        }
                    }

                    UpdateFoodUse(cs);
                }
            }

            if (_magicUpdateTime < Time.SecondsSinceStartDouble)
            {
                _magicUpdateTime = Time.SecondsSinceStartDouble + 1;
            }

            if (_updateTime < Time.SecondsSinceStartDouble && TimeCycle.IsDay)
            {
                _updateTime = Time.SecondsSinceStartDouble + _UPDATE_TIME;
            }
        }