KAZIK/build/installer/CasinoSetup/InstallPaths.cs

140 lines
5 KiB
C#

using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Xml;
using System.Xml.Linq;
namespace CasinoSetup;
public static class InstallPaths
{
public const string ReceiptName = "casino-install.xml";
public static string Normalize(string path)
{
string fullPath = Path.GetFullPath(path);
if (fullPath.TrimEnd('\\', '/') == Path.GetPathRoot(fullPath).TrimEnd('\\', '/'))
{
throw new IOException("Нельзя устанавливать игру в корень диска.");
}
return fullPath.TrimEnd('\\', '/');
}
public static string SafeFile(string root, string relative)
{
if (string.IsNullOrWhiteSpace(relative) || Path.IsPathRooted(relative) || relative.Contains(':') || relative.Contains('\\') || relative.Split('/').Any((string p) => p == ".." || p == "." || p.Length == 0 || p.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || IsDevice(p) || p.EndsWith(".", StringComparison.Ordinal) || p.EndsWith(" ", StringComparison.Ordinal)))
{
throw new IOException("Недопустимый путь в пакете: " + relative);
}
string fullPath = Path.GetFullPath(Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar)));
if (!fullPath.StartsWith(root.TrimEnd('\\') + "\\", StringComparison.OrdinalIgnoreCase))
{
throw new IOException("Путь выходит за пределы установки.");
}
NoLinks(fullPath);
return fullPath;
}
private static bool IsDevice(string name)
{
string text = name.Split('.')[0].ToUpperInvariant();
if (!new string[6] { "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$" }.Contains(text))
{
if (text.Length == 4 && (text.StartsWith("COM") || text.StartsWith("LPT")) && text[3] >= '1')
{
return text[3] <= '9';
}
return false;
}
return true;
}
public static void NoLinks(string path)
{
string text = path;
while (!string.IsNullOrEmpty(text))
{
if ((Directory.Exists(text) || File.Exists(text)) && (File.GetAttributes(text) & FileAttributes.ReparsePoint) != 0)
{
throw new IOException("Папка установки не должна содержать символические ссылки: " + text);
}
text = Path.GetDirectoryName(text);
}
}
public static void ValidateTarget(string target, string package)
{
target = Normalize(target);
NoLinks(target);
Environment.SpecialFolder[] array = new Environment.SpecialFolder[8]
{
Environment.SpecialFolder.Windows,
Environment.SpecialFolder.System,
Environment.SpecialFolder.ProgramFiles,
Environment.SpecialFolder.ProgramFilesX86,
Environment.SpecialFolder.UserProfile,
Environment.SpecialFolder.DesktopDirectory,
Environment.SpecialFolder.LocalApplicationData,
Environment.SpecialFolder.ApplicationData
};
foreach (Environment.SpecialFolder specialFolder in array)
{
string folderPath = Environment.GetFolderPath(specialFolder);
if (!string.IsNullOrEmpty(folderPath))
{
bool flag = specialFolder == Environment.SpecialFolder.Windows || specialFolder == Environment.SpecialFolder.System;
if (target.Equals(folderPath.TrimEnd('\\'), StringComparison.OrdinalIgnoreCase) || (flag && target.StartsWith(folderPath.TrimEnd('\\') + "\\", StringComparison.OrdinalIgnoreCase)))
{
throw new IOException("Выберите отдельную папку для игры, не системную папку.");
}
}
}
if (!string.IsNullOrEmpty(package) && Path.GetFullPath(package).StartsWith(target + "\\", StringComparison.OrdinalIgnoreCase))
{
throw new IOException("Переместите установщик за пределы выбранной папки.");
}
}
public static XDocument ReadXml(Stream stream)
{
XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
xmlReaderSettings.DtdProcessing = DtdProcessing.Prohibit;
xmlReaderSettings.XmlResolver = null;
xmlReaderSettings.MaxCharactersInDocument = 16777216L;
XmlReaderSettings settings = xmlReaderSettings;
using XmlReader reader = XmlReader.Create(stream, settings);
return XDocument.Load(reader);
}
public static string HashFile(string path)
{
using FileStream inputStream = File.OpenRead(path);
using SHA256 sHA = SHA256.Create();
return Hex(sHA.ComputeHash(inputStream));
}
public static string Hex(byte[] bytes)
{
return BitConverter.ToString(bytes).Replace("-", "").ToLowerInvariant();
}
public static long Number(XElement e, string name)
{
long num = long.Parse((string)e.Attribute(name), CultureInfo.InvariantCulture);
if (num < 0)
{
throw new InvalidDataException("Отрицательный размер в пакете.");
}
return num;
}
public static void CheckHash(string hash)
{
if (hash == null || hash.Length != 64 || hash.Any((char c) => !Uri.IsHexDigit(c)))
{
throw new InvalidDataException("Некорректная контрольная сумма.");
}
}
}