using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Mail; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Web.Script.Serialization; namespace SeLtd.Setup { internal sealed class RepositorySettings { public string url { get; set; } public string branch { get; set; } public string folder { get; set; } } internal sealed class Prerequisite { public string id { get; set; } public string label { get; set; } public string executable { get; set; } public string[] paths { get; set; } public string[] probe { get; set; } public string help { get; set; } } internal sealed class Variable { public string name { get; set; } public string label { get; set; } public string type { get; set; } public string description { get; set; } public string source { get; set; } public string legacyValue { get; set; } } internal sealed class Step { public string action { get; set; } public string label { get; set; } public string tool { get; set; } public string[] arguments { get; set; } public string url { get; set; } public int timeout { get; set; } } internal sealed class SetupConfig { public RepositorySettings repository { get; set; } public Prerequisite[] prerequisites { get; set; } public Variable[] variables { get; set; } public Step[] prepare { get; set; } public Step[] install { get; set; } public string dockerContext { get; set; } public int webPort { get; set; } public string composeTemplate { get; set; } public string mariaDbInitDirectory { get; set; } public string[] legacySqlPrefixes { get; set; } } internal sealed class SetupEngine { private const string OverrideMarker = "# Generated by SE-LTD Setup "; private static readonly Regex EnvLine = new Regex(@"^(?[A-Za-z_][A-Za-z_0-9]*)\s*=\s*(?.*)$"); private static readonly Encoding Utf8 = new UTF8Encoding(false, true); private readonly string configDir; private readonly Dictionary tools = new Dictionary(); private string[] templateLines; internal readonly Dictionary Defaults = new Dictionary(); internal readonly Dictionary Values = new Dictionary(); internal readonly SetupConfig Config; internal string Folder { get; private set; } internal bool ExistingEnvironment { get; private set; } internal bool Legacy { get; set; } internal bool Remote { get; set; } internal SetupEngine(string configDir) { this.configDir = configDir; Config = new JavaScriptSerializer().Deserialize( File.ReadAllText(Path.Combine(configDir, "setup.config.json"), Utf8)); if (Config == null || Config.repository == null || Config.prerequisites == null || Config.variables == null || Config.variables.Length == 0 || Config.prepare == null || Config.install == null || string.IsNullOrWhiteSpace(Config.repository.folder) || string.IsNullOrWhiteSpace(Config.dockerContext) || Config.webPort < 1 || Config.webPort > 65535 || Config.variables.Select(variable => variable.name).Distinct().Count() != Config.variables.Length) throw new InvalidDataException("Die Datei setup.config.json ist unvollständig oder enthält doppelte Variablen."); } internal bool Check(Prerequisite item) { var candidates = (item.paths ?? new string[0]).Select(Environment.ExpandEnvironmentVariables) .Concat((Environment.GetEnvironmentVariable("PATH") ?? "").Split(';') .Select(path => path.Trim().Trim('"')) .Where(path => !string.IsNullOrWhiteSpace(path) && Path.IsPathRooted(path)) .Select(path => Path.Combine(path, item.executable))); var executable = candidates.FirstOrDefault(File.Exists); if (executable == null || (item.probe != null && Run(executable, item.probe, configDir, 15).Code != 0)) return false; tools[item.id] = executable; return true; } internal void Prepare(string folder, Action progress, CancellationToken cancellation = default(CancellationToken)) { Folder = Path.GetFullPath(folder); Legacy = Remote = false; for (int index = 0; index < Config.prepare.Length; index++) { cancellation.ThrowIfCancellationRequested(); var step = Config.prepare[index]; progress(StepLabel(step, index, Config.prepare.Length)); if (step.action == "checkout") Checkout(); else if (step.action == "template") LoadTemplate(); else if (step.action == "command") RunStep(step); else throw new InvalidDataException("Unbekannter Vorbereitungsschritt: " + step.action); } cancellation.ThrowIfCancellationRequested(); } internal void Install(Action progress, CancellationToken cancellation = default(CancellationToken)) { for (int index = 0; index < Config.install.Length; index++) { cancellation.ThrowIfCancellationRequested(); var step = Config.install[index]; progress(StepLabel(step, index, Config.install.Length)); if (step.action == "dockerReady") WaitForDocker(TimeoutFor(step, 180), progress); else if (step.action == "writeSetup") WriteSetup(); else if (step.action == "command") RunStep(step); else if (step.action == "http") CheckHttp(Expand(step.url), TimeoutFor(step, 45)); else throw new InvalidDataException("Unbekannter Installationsschritt: " + step.action); } cancellation.ThrowIfCancellationRequested(); } private static string StepLabel(Step step, int index, int count) { return string.Format("Schritt {0} von {1}: {2}", index + 1, count, step.label); } internal string LocalOrigin { get { return "http://localhost:" + Config.webPort + ",http://127.0.0.1:" + Config.webPort; } } internal string WebUrl { get { return "http://127.0.0.1:" + Config.webPort + "/"; } } internal static string GenerateSecret() { var bytes = new byte[32]; using (var rng = RandomNumberGenerator.Create()) rng.GetBytes(bytes); return BitConverter.ToString(bytes).Replace("-", "").ToLowerInvariant(); } internal string Validate(Variable variable, string value, bool existingController) { if (variable.type == "secret" || (variable.type == "legacyPassword" && !existingController)) { if (!Regex.IsMatch(value, @"\A[A-Za-z0-9._~-]{16,72}\z")) return "Bitte 16 bis 72 Zeichen verwenden. Erlaubt sind A–Z, a–z, 0–9 und . _ ~ -."; } else if (variable.type == "email") { try { if (new MailAddress(value).Address != value || !Regex.IsMatch(value, @"\A[A-Za-z0-9._+%\-]+@[A-Za-z0-9.\-]+\z")) return "Bitte eine einfache E-Mail-Adresse ohne Anzeigenamen eingeben."; } catch (FormatException) { return "Bitte eine gültige E-Mail-Adresse eingeben."; } catch (ArgumentException) { return "Bitte eine gültige E-Mail-Adresse eingeben."; } } else if (variable.type == "port") { int number; if (!int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out number) || number < 1 || number > 65535) return "Bitte eine Portnummer zwischen 1 und 65535 eingeben."; if (new[] { Config.webPort, 3306, 3008, 9090, 18110, 18111 }.Contains(number)) return "Dieser Port ist bereits für einen anderen SE-LTD-Dienst reserviert."; } else if (variable.type == "text" && !Regex.IsMatch(value, @"\A[A-Za-z0-9._+:/ -]+\z")) return "Bitte einen Wert ohne Sonder- oder Steuerzeichen eingeben."; return null; } private void Checkout() { var git = Tool("git"); var repo = Config.repository; if (string.IsNullOrWhiteSpace(repo.url) || string.IsNullOrWhiteSpace(repo.branch) || repo.branch.StartsWith("-")) throw new InvalidDataException("Repository oder Branch in setup.config.json fehlt."); Directory.CreateDirectory(Folder); if (!File.Exists(Path.Combine(Folder, ".git")) && !Directory.Exists(Path.Combine(Folder, ".git"))) { if (Directory.EnumerateFileSystemEntries(Folder).Any()) throw new InvalidOperationException("Der Ordner ist nicht leer und enthält kein Git-Projekt. Bitte einen leeren Ordner auswählen."); Require(Run(git, new[] { "clone", "--single-branch", "--branch", repo.branch, "--", repo.url, Folder }, configDir, 300), "Git konnte das Projekt nicht herunterladen."); return; } var root = Require(Run(git, new[] { "rev-parse", "--show-toplevel" }, Folder, 15), "Git-Ordner konnte nicht geprüft werden."); var origin = Require(Run(git, new[] { "remote", "get-url", "origin" }, Folder, 15), "Git-Server konnte nicht geprüft werden."); var branch = Require(Run(git, new[] { "branch", "--show-current" }, Folder, 15), "Git-Branch konnte nicht geprüft werden."); if (!SameFolder(root, Folder) || !string.Equals(origin, repo.url, StringComparison.Ordinal) || branch != repo.branch) throw new InvalidOperationException("Der Ordner verweist auf ein anderes Repository oder einen anderen Branch. Bitte einen anderen Ordner auswählen."); Require(Run(git, new[] { "pull", "--ff-only", "origin", repo.branch }, Folder, 300), "Git Pull konnte nicht ausgeführt werden."); } private void LoadTemplate() { var path = Path.Combine(Folder, ".env"); if (Require(Run(Tool("git"), new[] { "ls-files", "--", ".env" }, Folder, 15), "Git konnte die .env nicht prüfen.").Length != 0) throw new InvalidOperationException("Die Datei .env wird von Git verwaltet. Aus Sicherheitsgründen bitte zuerst aus dem Repository entfernen."); ExistingEnvironment = File.Exists(path); Defaults.Clear(); Values.Clear(); templateLines = File.ReadAllLines(ExistingEnvironment ? path : Path.Combine(Folder, ".env.example"), Utf8); foreach (string line in templateLines) { var match = EnvLine.Match(line); if (match.Success) Defaults[match.Groups["name"].Value] = match.Groups["value"].Value.Trim(); } if (ExistingEnvironment) { foreach (var pair in Defaults) Values[pair.Key] = pair.Value; return; } var names = new HashSet(Config.variables.Select(variable => variable.name)); var unknown = Defaults.Keys.Where(name => !names.Contains(name)).ToArray(); if (unknown.Length != 0) throw new InvalidDataException("Die .env-Vorlage enthält neue Variablen. Bitte setup.config.json ergänzen: " + string.Join(", ", unknown)); foreach (var variable in Config.variables) { if (variable.type == "secret" || variable.type == "legacyPassword") Values[variable.name] = GenerateSecret(); else { string value; if (!Defaults.TryGetValue(variable.name, out value)) throw new InvalidDataException("Die Variable " + variable.name + " fehlt in .env.example."); Values[variable.name] = value; } } } private void WriteSetup() { var path = Path.Combine(Folder, ".env"); var overridePath = Path.Combine(Folder, "compose.override.yaml"); if (ExistingEnvironment) return; var otherOverrides = new[] { "compose.override.yml", "docker-compose.override.yml", "docker-compose.override.yaml" }; if (otherOverrides.Any(name => File.Exists(Path.Combine(Folder, name)))) throw new InvalidOperationException("Ein anderer lokaler Compose-Override ist vorhanden. Der Assistent kann die Port- und Datenbank-Konfiguration nicht sicher zuordnen."); if (File.Exists(overridePath) && !(File.ReadLines(overridePath, Utf8).FirstOrDefault() ?? "").StartsWith(OverrideMarker, StringComparison.Ordinal)) throw new InvalidOperationException("compose.override.yaml wurde nicht von diesem Assistenten erstellt. Die Datei wurde nicht verändert."); if (File.Exists(path)) throw new InvalidOperationException(".env wurde inzwischen angelegt und wird nicht überschrieben. Bitte den Assistenten neu starten."); foreach (var variable in Config.variables) { if (variable.type == "sameAs") Values[variable.name] = Values[variable.source]; else if (variable.type == "remoteAccess") Values[variable.name] = Remote ? "*" : LocalOrigin; else if (variable.type == "legacyPassword" && Legacy) Values[variable.name] = variable.legacyValue; var error = Validate(variable, Values[variable.name], Legacy); if (error != null) throw new InvalidDataException(variable.name + ": " + error); } var overrideText = Expand(File.ReadAllText(Path.Combine(configDir, Config.composeTemplate), Utf8)); if (!overrideText.StartsWith(OverrideMarker, StringComparison.Ordinal)) throw new InvalidDataException("Die Markierung am Anfang der Compose-Vorlage fehlt."); var upstream = Path.Combine(Folder, Config.mariaDbInitDirectory); var init = Path.Combine(Folder, ".seltd-setup", "mariadb-init"); Directory.CreateDirectory(init); foreach (string file in Directory.GetFiles(upstream)) { var destination = Path.Combine(init, Path.GetFileName(file)); if (Path.GetExtension(file).Equals(".sql", StringComparison.OrdinalIgnoreCase)) File.WriteAllLines(destination, File.ReadAllLines(file, Utf8).Where(line => !(Config.legacySqlPrefixes ?? new string[0]).Any(prefix => line.TrimStart().StartsWith(prefix, StringComparison.OrdinalIgnoreCase))), Utf8); else File.Copy(file, destination, true); } var excludePath = Require(Run(Tool("git"), new[] { "rev-parse", "--git-path", "info/exclude" }, Folder, 15), "Lokale Git-Einstellungen konnten nicht gelesen werden."); excludePath = Path.Combine(Folder, excludePath); Directory.CreateDirectory(Path.GetDirectoryName(excludePath)); File.AppendAllText(excludePath, "\n/.env\n/.env.*.tmp\n/compose.override.yaml\n/.seltd-setup/\n", Utf8); File.WriteAllText(overridePath, overrideText, Utf8); var envValues = templateLines.Select(line => { var match = EnvLine.Match(line); return match.Success ? match.Groups["name"].Value + "=" + Values[match.Groups["name"].Value] : line; }); var tempPath = Path.Combine(Folder, ".env." + Guid.NewGuid().ToString("N") + ".tmp"); try { File.WriteAllLines(tempPath, envValues, Utf8); File.Move(tempPath, path); ExistingEnvironment = true; } finally { if (File.Exists(tempPath)) File.Delete(tempPath); } } private void WaitForDocker(int seconds, Action progress) { var deadline = DateTime.UtcNow.AddSeconds(seconds); var launched = false; do { var result = Docker(new[] { "info", "--format", "{{.OSType}}" }, 12); if (result.Code == 0 && result.Output.Trim() == "linux") { var installed = Require(Docker(new[] { "ps", "-a", "--filter", "name=^/seltd-", "--format", "{{.Names}}|{{.Label \"com.docker.compose.project.working_dir\"}}" }, 15), "Docker konnte laufende Installationen nicht prüfen."); foreach (var line in installed.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) { var parts = line.Split(new[] { '|' }, 2); if (parts.Length != 2 || string.IsNullOrEmpty(parts[1]) || !SameFolder(parts[1], Folder)) throw new InvalidOperationException("Docker enthält bereits eine SE-LTD-Installation (" + parts[0] + "). Bitte den ursprünglichen Projektordner wählen. Bestehende Container bleiben unverändert."); } return; } if (!launched) { launched = true; progress("Docker Desktop wird geöffnet. Bitte ggf. dessen Ersteinrichtung bestätigen."); using (Process.Start(new ProcessStartInfo(Tool("desktop")) { UseShellExecute = true })) { } } Thread.Sleep(3000); } while (DateTime.UtcNow < deadline); throw new InvalidOperationException("Docker Desktop ist noch nicht für Linux-Container bereit. Bitte Docker Desktop öffnen, die Einrichtung abschließen und es noch einmal versuchen."); } private void RunStep(Step step) { var arguments = (step.arguments ?? new string[0]).Select(Expand).ToArray(); var timeout = TimeoutFor(step, 60); try { var result = step.tool == "docker" ? Docker(arguments, timeout) : Run(Tool(step.tool), arguments, Folder, timeout); Require(result, step.label + " fehlgeschlagen."); } catch (Exception error) { string message = error.Message; foreach (var secret in Config.variables.Where(item => item.type == "secret" || item.type == "legacyPassword" || item.type == "sameAs")) { string value; if (Values.TryGetValue(secret.name, out value) && value.Length >= 4) message = message.Replace(value, "********"); } throw new InvalidOperationException(message); } } private static void CheckHttp(string url, int seconds) { var deadline = DateTime.UtcNow.AddSeconds(seconds); do { try { var request = (HttpWebRequest)WebRequest.Create(url); request.Proxy = null; request.Timeout = 3000; using (var response = (HttpWebResponse)request.GetResponse()) if ((int)response.StatusCode < 400) return; } catch (WebException) { } Thread.Sleep(2000); } while (DateTime.UtcNow < deadline); throw new InvalidOperationException("Die Prüfung von " + url + " war nicht erfolgreich. Details stehen in Docker Desktop bei den SE-LTD-Containern."); } private string Expand(string input) { return input.Replace("{{WEB_PORT}}", Config.webPort.ToString(CultureInfo.InvariantCulture)) .Replace("{{API_PORT}}", ApiPort()) .Replace("{{WEB_BIND}}", Remote ? "0.0.0.0" : "127.0.0.1") .Replace("{{DB_BIND}}", Legacy ? "0.0.0.0" : "127.0.0.1"); } private string ApiPort() { string value; if (Values.TryGetValue("VITE_API_PORT", out value)) { var match = Regex.Match(value, "^['\"]?([0-9]{1,5})['\"]?(?:\\s+#.*)?$"); if (match.Success) return match.Groups[1].Value; } return "18080"; } private string Tool(string id) { string path; if (!tools.TryGetValue(id, out path)) throw new InvalidOperationException("Voraussetzung fehlt: " + id); return path; } private Result Docker(string[] args, int seconds) { return Run(Tool("docker"), new[] { "--context", Config.dockerContext }.Concat(args), Folder, seconds, Defaults.Keys.Concat(Values.Keys).Concat(new[] { "COMPOSE_FILE", "COMPOSE_ENV_FILES", "COMPOSE_PROJECT_NAME" })); } private static bool SameFolder(string left, string right) { return string.Equals(Path.GetFullPath(left).TrimEnd('\\', '/'), Path.GetFullPath(right).TrimEnd('\\', '/'), StringComparison.OrdinalIgnoreCase); } private static int TimeoutFor(Step step, int fallback) { return step.timeout > 0 ? step.timeout : fallback; } private sealed class Result { internal int Code; internal string Output; internal string Error; } private static string Require(Result result, string message) { if (result.Code == 0) return result.Output.Trim(); var details = string.IsNullOrWhiteSpace(result.Error) ? result.Output : result.Error; if (details.Length > 1600) details = details.Substring(details.Length - 1600); throw new InvalidOperationException(message + "\n\n" + details.Trim()); } private static Result Run(string executable, IEnumerable arguments, string cwd, int seconds, IEnumerable clearEnvironment = null) { var start = new ProcessStartInfo(executable, string.Join(" ", arguments.Select(Quote))) { WorkingDirectory = cwd, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8 }; if (clearEnvironment != null) foreach (string variable in clearEnvironment) start.EnvironmentVariables.Remove(variable); using (var process = Process.Start(start)) { var output = process.StandardOutput.ReadToEndAsync(); var error = process.StandardError.ReadToEndAsync(); if (!process.WaitForExit(seconds * 1000)) { try { process.Kill(); } catch (InvalidOperationException) { } return new Result { Code = -1, Output = "", Error = "Zeitlimit erreicht." }; } if (!System.Threading.Tasks.Task.WaitAll(new System.Threading.Tasks.Task[] { output, error }, 5000)) return new Result { Code = -1, Output = "", Error = "Programmausgabe wurde nicht abgeschlossen." }; return new Result { Code = process.ExitCode, Output = output.Result.Replace("\0", ""), Error = error.Result.Replace("\0", "") }; } } private static string Quote(string arg) { // WSL parses its switches from the raw command line and rejects quoted flags. if (arg.Length > 0 && !arg.Any(character => char.IsWhiteSpace(character) || character == '"')) return arg; return "\"" + Regex.Replace(arg, "(\\\\*)(\"|$)", match => match.Groups[1].Value + match.Groups[1].Value + (match.Groups[2].Value == "\"" ? "\\\"" : "")) + "\""; } } }