Exemple #1
0
        internal void Inner(int port, string dir, ASCServer ascws)
        {
            if (ascws == null) // running from service
            {
                "Please avoid running the ASC server from service due to possibly incorrect initialization".Warn();

                Main(new string[] { ARG_IGNMTX });

                return;
            }

            "Connecting to the internal database ...".Msg();

            using (database = Database.Instance)
                try
                {
                    #region DATABASE INIT

                    ascws.tSQL = database;
#if DEBUG
                    database.DebugMode = true;
#endif
                    $"Connected to the database with the connection ID {{{database.Connection.ClientConnectionId}}}".Ok();

                    foreach (string table in new string[] { "ChatMembers", "ChatMessages", "Chats", "Messages", "Users", "UserAuthentifications" })
                    {
                        if (!database.Exists(table))
                        {
                            $"Table '{table}' could not be found. It will be re-created ...".Warn();

                            database.CreateNew(table);
                        }

                        $"Table '{table}' loaded.".Ok();
                    }

                    foreach (string function in new string[] { "Trim" })
                    {
                        if (!database.ContainsFunction(function))
                        {
                            $"Function '{function}' could not be found. It will be re-created ...".Warn();

                            database.CreateFunction(function);
                        }

                        $"Function '{function}' loaded.".Ok();
                    }

                    database.Cleanup();

                    $"{database.UserCount} registered user(s) have been found inside the database.".Msg();
                    $"{database.AdminCount} registered administrator(s) have been found inside the database.".Msg();
                    $"{database.MessageCount} sent message(s) have been found inside the database.".Msg();
                    $"{database.ChatCount} chat(s)/group(s) have been found inside the database.".Msg();

                    Authentification.Start();

                    #endregion
                    #region LOCATION UPDATER

                    $"Starting the location caching service with a cache-time of {HTTPServer.LOCATION_CACHE_TIME / 1000f:F1} seconds ...".Msg();

                    HTTPServer._locuptmr = new Timer(delegate
                    {
                        "Updating the location cache ...".Msg();

                        (string IP, GeoIPResult Result)[] ips;
Exemple #2
0
#pragma warning restore

        /// <summary>
        /// The application's main entry point
        /// </summary>
        /// <param name="args">Command line arguments</param>
        /// <returns>Return code</returns>
        public static int Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine(GREETING_MESSAGE);
#if DEBUG
            AppDomain.MonitoringIsEnabled = true;
#endif
            WindowsIdentity  identity  = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);

            ConsoleLogger.Flush();

            $"Application started with the following {args.Length} argument(s):".Msg();

            for (int i = 0; i < args.Length; i++)
            {
                $"    [{i}]: {args[i].Trim()}".Msg();
            }

            try
            {
                Win32.ShowWindow(Process.GetCurrentProcess().MainWindowHandle, 3);
            }
            catch
            {
                "Unable to resize console window ... aren't you running in GUI mode?".Warn();
            }

            if (!principal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                "This application is not running as administrator and will therefore have privilege and authorisation problems. Please restart it with elevated privilege.".Err();

                return(-1);
            }
            else
            {
                "Running as administrator. Perfect.".Ok();
            }

            string dir     = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName;
            int    retcode = 0;

            Directory.SetCurrentDirectory(dir);

            $"Running from '{dir}'".Info();

            using (Mutex m = new Mutex(false, Win32.MUTEX))
                try
                {
                    Console.CancelKeyPress += Console_CancelKeyPress;
                    AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;

                    if (m.WaitOne(0, false) || containsarg(args, ARG_IGNMTX))
                    {
                        if (containsarg(args, ARG_SLOWSTART))
                        {
                            foreach (Action <string[]> task in StartupTasks)
                            {
                                task(args);
                            }
                        }
                        else
                            Parallel.ForEach(StartupTasks, _ => _(args));

                        fixed(bool *bptr = &acceptconnections)
                        using (ServiceHost sh = BindCertificatePort(IPAddress.Any.ToString(), Win32.PORT, StoreName.TrustedPublisher, nameof(Properties.Resources.ASC)))
                            using (ASCServer ws = new ASCServer(Win32.PORT, bptr, null))
                                new Program().Inner(Win32.PORT, dir, ws);
                    }
                    else
                    {
                        "Cannot start the server, as an other instance of this application is already running.".Warn();
                    }
                }
                catch (ForcedShutdown)
                {
                    "Remote-forced (controlled) shutdown ...".Warn();
                }
            catch (Exception ex)
            {
                if (ex != null)
                {
                    ex.Err();
                }

                "Application-forced shutdown ...".Err();

                retcode = -1;
            }
            finally
            {
                Console.CancelKeyPress -= Console_CancelKeyPress;
                AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit;

                if (containsarg(args, ARG_DELFWL))
                {
                    "Removing previously set firewall rules ...".Msg();

                    foreach (int port in new int[] { Win32.PORT, Win32.PORT + 1 })
                    {
                        FirewallUtils.ClosePort(port);

                        $"Port {port} was successfully un-registered".Ok();
                    }
                }

                "Server shut down".Ok();

                m.Close();

                LoggerBase.StopAll(logger => {
                    if (!containsarg(args, ARG_NOLOG))
                    {
                        logger.Save(Directory.GetCurrentDirectory());
                    }
                });

                if (Debugger.IsAttached | (Win32.GetConsoleWindow() != IntPtr.Zero))
                {
                    "Press any key ...".Msg();

                    Console.ReadKey(true);
                }
            }

            return(retcode);
        }