Exemplo n.º 1
0
        /// <summary>
        /// The Main Thread: This is where your Service is Run.
        /// </summary>
        static void Main(string[] args)
        {
            //Check if the global application path exists, if not create it
            string sGlobalPath = MOTR_Settings.GetGlobalApplicationPath();

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

            //Static service variable to handle the service
            m_TheService = new WindowsService();

            //Default values before startup
            iHTTP = MOTR_Settings.GetNumber("http");
            if (iHTTP == 0)
            {
                iHTTP = 80;
                MOTR_Settings.SetNumber("http", iHTTP);
            }
            iHTTPS = MOTR_Settings.GetNumber("https");
            //If iHTTPS = 0 then the https will not open

            //This is function is before Mutex, so it will be runned each time!
            //If one of the parameters is to generate a cert, then we are creating in the same path
            for (int i = 0; i < args.Length; i++)
            {
                string sArg = args[i].ToUpper();
                if (sArg == "-CERT")
                {
                    string name   = "MOTRd";
                    string domain = "";
                    if (args.Length > i + 1)
                    {
                        domain = "*." + args[i + 1];
                        name   = domain;
                    }

                    CertGenerator m_Generator = new CertGenerator();
                    if (m_Generator.GenerateAndSave(name, domain))
                    {
                        LogEventInformation("MOTR certificate generated success");
                    }
                    else
                    {
                        LogEventError("MOTR certification generation error");
                    }
                    return;
                }

                //Wait 5 seconds
                if (sArg == "-WAIT")
                {
                    Thread.Sleep(3000);
                    return;
                }

                //Port override with parameters
                if (sArg.Contains("HTTPS"))
                {
                    string[] aString = sArg.Split('=');
                    if (aString.Length > 1)
                    {
                        iHTTPS = Convert.ToInt32(aString[1]);
                    }
                }
                else if (sArg.Contains("HTTP"))
                {
                    string[] aString = sArg.Split('=');
                    if (aString.Length > 1)
                    {
                        iHTTP = Convert.ToInt32(aString[1]);
                    }
                }

                //Check for tool update
                if (sArg == "-TOOLUPDATE")
                {
                    Console.WriteLine("Update tools...");
                    ArrayList aTools = new ArrayList();
                    aTools.Add("handbreak");
                    aTools.Add("unrar");

                    //Update all the tools used
                    for (int o = 0; o < aTools.Count; o++)
                    {
                        string sLocalVersion = MOTR_Settings.GetCurrentToolVersion(aTools[o].ToString());
                        string sWebVersion   = MOTR_Settings.GetWebsiteToolVersion(aTools[o].ToString());

                        //Updates
                        if (sLocalVersion != sWebVersion)
                        {
                            Console.Write("Updating " + aTools[o].ToString() + " to v" + sWebVersion + "... ");
                            bool bRet = MOTR_Settings.UpdateTool(aTools[o].ToString(), sWebVersion);
                            if (bRet)
                            {
                                Console.WriteLine("success");
                            }
                            else
                            {
                                Console.WriteLine("failed");
                            }
                        }
                        else
                        {
                            Console.WriteLine(aTools[o].ToString() + " already in latest version");
                        }
                    }
                    return;
                }
            }


            //======================================================
            //Create the global mutex and set its security
            bool  bFirstInstance = false;
            Mutex mutex          = null;

            try
            {
                //Create a mutex with security globally
                oMutexSecurity = new MutexSecurity();
                oMutexSecurity.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), MutexRights.FullControl, AccessControlType.Allow));

                mutex = new Mutex(true, "Global\\MOTRD Mutex for single instances", out bFirstInstance);
                mutex.SetAccessControl(oMutexSecurity);
            }
            catch (Exception ex)
            {
                LogEventError("Only one instance of MOTRd is allowed, please check if service is running or taskmanager for motrd.exe. Only one instance is allowed!");
                Console.WriteLine("Error: " + ex.Message.ToString());
                m_TheService.Stop();
                return;
            }

            //Check if we are going to run as service or not :)
            bool bRunAsService = true;

            if (Environment.UserInteractive)
            {
                bRunAsService = false;
            }

            if (bRunAsService)
            {
                //Check if there are other instances
                if (mutex.WaitOne(TimeSpan.Zero, true))
                {
                    ServiceBase.Run(m_TheService);
                }
                else
                {
                    LogEventError("Only one instance of MOTRd is allowed, please stop service or check taskmanager for motrd.exe");
                    m_TheService.Stop();
                    return;
                }
            }
            else
            {
                //Check if there are other instances
                if (mutex.WaitOne(TimeSpan.Zero, true))
                {
                    Console.ForegroundColor = ConsoleColor.DarkBlue;
                    Console.WriteLine("Starting in console...");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Press Q to quit");
                    Console.Write("Args: ");
                    for (int i = 0; i < args.Length; i++)
                    {
                        Console.Write(args[i] + ", ");
                    }
                    Console.WriteLine("");
                    Console.ResetColor();
                    MOTR_Settings.ShowAllSettings(); //test
                    //Lager en "fake" service og starter den lik en normal service vil kjøre
                    m_TheService.StartServiceAsConsole(args);
                    while (true)
                    {
                        char cKey = Console.ReadKey().KeyChar;
                        if (cKey == 'Q' || cKey == 'q')
                        {
                            break;
                        }
                    }
                    m_TheService.StopServiceAsConsole();
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("ERROR: MOTRd is already running.");
                    Console.ResetColor();
                    Console.WriteLine("Could be running as service, also check taskmanager for motrd.exe");
                    Console.WriteLine("Press any key to quit");
                    Console.ReadKey();
                }
            }
        }