/// <summary>
        /// Program entry point.
        /// </summary>
        /// <param name="Args">Program command line arguments.</param>
        static void Main(string[] Args)
        {
            log.Trace("(Args:'{0}')", string.Join(" ", Args));

            CUI.InitConsole();

            if ((Args.Length == 1) && (Args[0] == "TestMode"))
            {
                TestMode = true;
                log.Info("Test mode is enabled.");
                CUI.WriteRich("\n<yellow>Test mode ENABLED. Note that in test mode you can skip the port check by using port values between 50001 and 65535.</yellow>\n\n");
            }

            // Make sure the current directory is set to the directory of the main executable.
            string path = System.Reflection.Assembly.GetEntryAssembly().Location;

            path = Path.GetDirectoryName(path);
            Directory.SetCurrentDirectory(path);

            InstallationFile.Chown("./Logs");
            log.Debug("Rid is {0}.", SystemInfo.CurrentRuntime.Rid);

            if (SystemInfo.CurrentRuntime.IsLinux())
            {
                int sudoUid, sudoGid;
                if (int.TryParse(Environment.ExpandEnvironmentVariables("%SUDO_UID%"), out sudoUid) &&
                    int.TryParse(Environment.ExpandEnvironmentVariables("%SUDO_GID%"), out sudoGid))
                {
                    SudoUserGroup = string.Format("{0}:{1}", sudoUid, sudoGid);
                    UserName      = Environment.ExpandEnvironmentVariables("%SUDO_USER%");
                }

                if (string.IsNullOrEmpty(UserName))
                {
                    UserName = "******";
                }
            }
            else if (SystemInfo.CurrentRuntime.IsWindows())
            {
                UserName = Environment.ExpandEnvironmentVariables("%USERNAME%");
            }

            switch (SystemInfo.CurrentRuntime.Rid)
            {
            case Rid.ubuntu_14_04_x64:
            case Rid.ubuntu_16_04_x64:
            case Rid.ubuntu_16_10_x64:
            case Rid.win7_x64:
            case Rid.win8_x64:
            case Rid.win81_x64:
            case Rid.win10_x64:
                if (!InstallAll())
                {
                    log.Error("Installation failed.");
                }
                break;

            default:
                CUI.WriteLine(ConsoleColor.Red, "Error: Your operating system is not supported.");
                break;
            }

            CUI.FinitConsole();
            log.Trace("(-)");
        }
示例#2
0
        public override bool Configure()
        {
            log.Trace("()");

            bool res = false;

            Dictionary <string, string> conf;

            if (!ConfigurationByRid.TryGetValue(SystemInfo.CurrentRuntime.Rid, out conf))
            {
                log.Trace("(-)[UNSUPPORTED]:{0}", res);
                return(res);
            }

            bool done = false;

            while (!done)
            {
                string appDataDir = Environment.ExpandEnvironmentVariables(conf["Application data directory"]);

                string dataDir = InstallationFile.AskForEmptyDirectory(string.Format("Where do you want <white>CAN server application data</white> to be stored? [{0}] ", appDataDir), appDataDir);
                conf["Application data directory"] = dataDir;
                GeneralConfiguration.SharedValues.Add("Can-DataDir", dataDir);

                string confFile = Path.Combine(dataDir, conf["Configuration file"]);


                int apiPort = int.Parse(conf["API port"]);
                while (GeneralConfiguration.UsedPorts.ContainsKey(apiPort))
                {
                    apiPort++;
                }
                conf["API port"] = apiPort.ToString();
                log.Debug("Selected port {0} as CAN server's API port.", apiPort);
                GeneralConfiguration.UsedPorts.Add(apiPort, "CAN server API interface");
                GeneralConfiguration.SharedValues.Add("CAN server API interface", apiPort.ToString());


                int swarmPort = int.Parse(conf["Swarm port"]);
                swarmPort          = AskForOpenPort(string.Format("Please enter a port number for <white>CAN server swarm interface</white>. This port will have to be open and publicly accessible from the Internet. [{0}] ", swarmPort), swarmPort, "CAN server swarm interface");
                conf["Swarm port"] = swarmPort.ToString();

                int gatewayPort = int.Parse(conf["Gateway port"]);
                gatewayPort          = AskForOpenPort(string.Format("Please enter a port number for <white>CAN server gateway interface</white>. This port will have to be open and publicly accessible from the Internet. [{0}] ", gatewayPort), gatewayPort, "CAN server gateway interface");
                conf["Gateway port"] = gatewayPort.ToString();


                string ipfs = SystemInfo.CurrentRuntime.IsLinux() ? Path.Combine(GeneralConfiguration.SharedValues["CanDir"], "ipfs") : Path.Combine(GeneralConfiguration.SharedValues["CanDir"], "ipfs.exe");

                string initIpfsScript        = SystemInfo.CurrentRuntime.IsLinux() ? Path.Combine(InstallationFile.TemporaryDirectoryName, "ipfsinit.sh") : Path.Combine(InstallationFile.TemporaryDirectoryName, "ipfsinit.cmd");
                string initIpfsScriptContent = SystemInfo.CurrentRuntime.IsLinux() ?
                                               string.Format("#/bin/base\n"
                                                             + "\n"
                                                             + "export IOPCAN_PATH=\"{0}\"\n"
                                                             + "\"{1}\" init\n", dataDir, ipfs)
          :
                                               string.Format("@set \"IOPCAN_PATH={0}\"\n"
                                                             + "\"{1}\" init\n", dataDir, ipfs);


                CUI.WriteRich("Creating <white>CAN server init script</white>... ");
                if (InstallationFile.CreateFileWriteTextChown(initIpfsScript, initIpfsScriptContent))
                {
                    CUI.WriteOk();
                    CUI.WriteRich("Creating <white>CAN server daemon script</white>... ");

                    string daemonIpfsScript = SystemInfo.CurrentRuntime.IsLinux() ? Path.Combine(GeneralConfiguration.SharedValues["CanDir"], "iop-can") : Path.Combine(GeneralConfiguration.SharedValues["CanDir"], "iop-can.cmd");
                    GeneralConfiguration.SharedValues[Name + "-executable"]      = daemonIpfsScript;
                    GeneralConfiguration.SharedValues[Name + "-executable-args"] = string.Format("\"{0}\"", daemonIpfsScript);

                    string daemonIpfsScriptContent = SystemInfo.CurrentRuntime.IsLinux() ?
                                                     string.Format("#/bin/base\n"
                                                                   + "\n"
                                                                   + "export IOPCAN_PATH=\"{0}\"\n"
                                                                   + "\"{1}\" daemon &\n", dataDir, ipfs)
            :
                                                     string.Format("@set \"IOPCAN_PATH={0}\"\n"
                                                                   + "\"{1}\" daemon\n", dataDir, ipfs);

                    if (InstallationFile.CreateFileWriteTextChown(daemonIpfsScript, daemonIpfsScriptContent))
                    {
                        CUI.WriteOk();
                        done = true;

                        CUI.WriteRich("Starting <white>CAN server init script</white>... ");
                        ConsoleProcess initScriptProcess = SystemInfo.CurrentRuntime.IsLinux() ? new ConsoleProcess("bash", string.Format("-x ./{0}", initIpfsScript)) : new ConsoleProcess("cmd.exe", string.Format("/C {0}", initIpfsScript));
                        if (initScriptProcess.RunAndWaitSuccessExit(20000))
                        {
                            CUI.WriteOk();

                            InstallationFile.Chown(dataDir);

                            CUI.WriteRich("Loading <white>CAN server configuration file</white>... ");
                            try
                            {
                                string[] lines = File.ReadAllLines(confFile);
                                CUI.WriteOk();

                                bool          addressesSection = false;
                                List <string> confLines        = new List <string>();
                                foreach (string line in lines)
                                {
                                    string confLine = line;

                                    if (addressesSection)
                                    {
                                        if (confLine.Contains("/ip4/0.0.0.0/tcp/14001"))
                                        {
                                            confLine = confLine.Replace("tcp/14001", string.Format("tcp/{0}", conf["Swarm port"]));
                                        }
                                        else if (confLine.Contains("ip6/::/tcp/14001"))
                                        {
                                            confLine = confLine.Replace("tcp/14001", string.Format("tcp/{0}", conf["Swarm port"]));
                                        }
                                        else if (confLine.Contains("/ip4/127.0.0.1/tcp/15001"))
                                        {
                                            confLine = confLine.Replace("tcp/15001", string.Format("tcp/{0}", conf["API port"]));
                                        }
                                        else if (confLine.Contains("/ip4/127.0.0.1/tcp/18080"))
                                        {
                                            confLine = confLine.Replace("tcp/18080", string.Format("tcp/{0}", conf["Gateway port"]));
                                        }
                                        else if (confLine.Trim().EndsWith("},"))
                                        {
                                            addressesSection = false;
                                        }
                                    }
                                    else
                                    {
                                        addressesSection = confLine.Contains("\"Addresses\":");
                                    }

                                    confLines.Add(confLine);
                                }


                                CUI.WriteRich("Writing new <white>CAN server configuration file</white>... ");
                                if (InstallationFile.CreateFileWriteTextChown(confFile, string.Join("\n", confLines)))
                                {
                                    CUI.WriteOk();

                                    res = true;
                                }
                                else
                                {
                                    CUI.WriteFailed();
                                    CUI.WriteRich("<red>ERROR:</red> unable to write to file <white>{0}</white>.\n", confFile);
                                }
                            }
                            catch (Exception e)
                            {
                                log.Error("Exception occurred: {0}", e.ToString());
                                CUI.WriteFailed();
                                CUI.WriteRich("<red>ERROR:</red> unable to read file <white>{0}</white>.\n", confFile);
                            }
                        }
                        else
                        {
                            CUI.WriteFailed();
                        }
                    }
                    else
                    {
                        CUI.WriteFailed();
                        CUI.WriteRich("<red>ERROR:</red> unable to write to <white>{0}</white>. Please try again.\n", daemonIpfsScript);
                    }

                    try
                    {
                        File.Delete(initIpfsScript);
                    }
                    catch (Exception e)
                    {
                        log.Error("Exception occurred: {0}", e.ToString());
                    }
                }
                else
                {
                    CUI.WriteFailed();
                    CUI.WriteRich("<red>ERROR:</red> unable to write to <white>{0}</white>. Please try again.\n", initIpfsScript);
                }
            }


            log.Trace("(-):{0}", res);
            return(res);
        }
示例#3
0
        public override bool Configure()
        {
            log.Trace("()");

            bool res = false;

            Dictionary <string, string> conf;

            if (!ConfigurationByRid.TryGetValue(SystemInfo.CurrentRuntime.Rid, out conf))
            {
                log.Trace("(-)[UNSUPPORTED]:{0}", res);
                return(res);
            }

            bool done = false;

            while (!done)
            {
                string appDataDir = Environment.ExpandEnvironmentVariables(conf["Application data directory"]);

                string dataDir = InstallationFile.AskForEmptyDirectory(string.Format("Where do you want <white>Profile server application data</white> to be stored? [{0}] ", appDataDir), appDataDir);
                conf["Application data directory"] = dataDir;
                GeneralConfiguration.SharedValues.Add("Ps-DataDir", dataDir);

                string confFile     = Path.Combine(GeneralConfiguration.SharedValues["PsDir"], "ProfileServer.conf");
                string shutdownFile = Path.Combine(GeneralConfiguration.SharedValues["PsDir"], "shutdown.signal");
                GeneralConfiguration.SharedValues["Ps-ShutdownFile"] = shutdownFile;

                string exeFile = Path.Combine(GeneralConfiguration.SharedValues["PsDir"], "ProfileServer");
                GeneralConfiguration.SharedValues[Name + "-executable"]      = exeFile;
                GeneralConfiguration.SharedValues[Name + "-executable-args"] = string.Format("\"{0}\"", exeFile);

                int primaryPort = int.Parse(conf["Primary port"]);
                primaryPort          = AskForOpenPort(string.Format("Please enter a port number for <white>Profile server primary interface</white>. This port will have to be open and publicly accessible from the Internet. [{0}] ", primaryPort), primaryPort, "Profile server primary interface");
                conf["Primary port"] = primaryPort.ToString();

                int otherPort = int.Parse(conf["Other port"]);
                otherPort          = AskForOpenPort(string.Format("Please enter a port number for <white>other interfaces of Profile server</white>. This port will have to be open and publicly accessible from the Internet. [{0}] ", otherPort), otherPort, "Profile server other interfaces");
                conf["Other port"] = otherPort.ToString();


                int canApiPort   = int.Parse(GeneralConfiguration.SharedValues["CAN server API interface"]);
                int locLocalPort = int.Parse(GeneralConfiguration.SharedValues["LOC server local interface"]);

                string imagesDir = Path.Combine(dataDir, "images");
                string tmpDir    = Path.Combine(dataDir, "tmp");
                string dbFile    = Path.Combine(dataDir, "ProfileServer.db");
                string pfxFile   = Path.Combine(dataDir, "ProfileServer.pfx");


                string confFileContents = ConfigurationFileTemplate
                                          .Replace("$EXTERNAL_ADDR", GeneralConfiguration.ExternalIpAddress.ToString())
                                          .Replace("$PRIMARY_PORT", conf["Primary port"])
                                          .Replace("$NEIGHBOR_PORT", conf["Other port"])
                                          .Replace("$NON_CUSTOMER_PORT", conf["Other port"])
                                          .Replace("$CUSTOMER_PORT", conf["Other port"])
                                          .Replace("$APP_SERVICE_PORT", conf["Other port"])
                                          .Replace("$PFX_CERT_FILE", pfxFile)
                                          .Replace("$IMAGES_DIR", imagesDir)
                                          .Replace("$TMP_DIR", tmpDir)
                                          .Replace("$DB_FILE", dbFile)
                                          .Replace("$TMP_DIR", tmpDir)
                                          .Replace("$LOC_PORT", locLocalPort.ToString())
                                          .Replace("$CAN_API_PORT", canApiPort.ToString());

                CUI.WriteRich("Writing <white>Profile server's configuration</white> to <white>{0}</white>... ", confFile);
                if (InstallationFile.CreateFileWriteTextChown(confFile, confFileContents))
                {
                    CUI.WriteOk();

                    done = true;

                    bool   error        = true;
                    string dbSourceFile = Path.Combine(GeneralConfiguration.SharedValues["PsDir"], "ProfileServer.db");
                    if (string.Compare(dbFile, dbSourceFile, true) != 0)
                    {
                        CUI.WriteRich("Copying <white>Profile server's database file</white> to <white>{0}</white>... ", dbFile);
                        try
                        {
                            File.Copy(dbSourceFile, dbFile);
                            InstallationFile.Chown(dbFile);

                            CUI.WriteOk();
                            error = false;
                        }
                        catch (Exception e)
                        {
                            log.Error("Exception occurred: {0}", e.ToString());
                            CUI.WriteFailed();
                        }
                    }

                    if (!error)
                    {
                        CUI.WriteRich("Loading <white>Profile server's logging configuration file</white>... ");
                        try
                        {
                            string nlogConfFile         = Path.Combine(GeneralConfiguration.SharedValues["PsDir"], "NLog.config");
                            string nlogConfFileContents = File.ReadAllText(nlogConfFile);
                            CUI.WriteOk();

                            nlogConfFileContents = nlogConfFileContents.Replace("${basedir}/Logs/", Path.Combine(dataDir, "Logs") + Path.DirectorySeparatorChar);
                            CUI.WriteRich("Updating <white>Profile server's logging configuration file</white>... ");
                            if (InstallationFile.CreateFileWriteTextChown(nlogConfFile, nlogConfFileContents))
                            {
                                CUI.WriteOk();

                                CUI.WriteRich("Creating <white>Profile server's TLS certificate</white>... ");
                                string openssl = SystemInfo.CurrentRuntime.IsLinux() ? "openssl" : Path.Combine(GeneralConfiguration.SharedValues["OpenSslDir"], "openssl.exe");
                                if (InstallationFile.GeneratePfxCertificate(openssl, pfxFile))
                                {
                                    CUI.WriteOk();
                                    res = true;
                                }
                                else
                                {
                                    log.Error("Failed to generate PFX certificate '{0}'.", pfxFile);
                                    CUI.WriteFailed();
                                }
                            }
                            else
                            {
                                log.Error("Failed to write NLog configuration to '{0}'.", nlogConfFile);
                                CUI.WriteFailed();
                            }
                        }
                        catch (Exception e)
                        {
                            log.Error("Exception occurred: {0}", e.ToString());
                            CUI.WriteFailed();
                        }
                    }
                }
                else
                {
                    CUI.WriteFailed();
                    CUI.WriteRich("<red>ERROR:</red> unable to write to <white>{0}</white>. Please try again.\n", confFile);
                }
            }


            log.Trace("(-):{0}", res);
            return(res);
        }