// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace WPFMA
{
    /// <summary>How worried to be about a file. Notes are things worth knowing that are normal in Unity tools.</summary>
    internal enum SafetyLevel
    {
        Clean = 0,
        Note = 1,
        Check = 2,
        Danger = 3
    }

    internal sealed class SafetyReason
    {
        public SafetyLevel Level;
        public string Text;
        public string Evidence;
    }

    /// <summary>One file that can run code (or pretends not to).</summary>
    internal sealed class SafetyItem
    {
        public string Path;
        public string Guid;
        public string Kind;
        public SafetyLevel Level;
        public string Summary;
        public long Size;
        public string Hash;
        public bool Managed;
        public bool LoadsInEditor;
        public bool Trusted;
        public readonly List<SafetyReason> Reasons = new List<SafetyReason>();

        /// <summary>The level after the user's trust: a trusted file is only a note.</summary>
        public SafetyLevel Shown { get { return Trusted && Level > SafetyLevel.Note ? SafetyLevel.Note : Level; } }

        public bool IsCompiled { get { return Kind == SafetyScanner.KindDll || Kind == SafetyScanner.KindNative; } }

        /// <summary>Unity runs it (scripts, DLLs, compiler settings), as opposed to a program it never touches.</summary>
        public bool RunsInUnity
        {
            get { return Kind == SafetyScanner.KindScript || IsCompiled || Kind == SafetyScanner.KindCompiler; }
        }
    }

    internal sealed class SafetyReport
    {
        public string Source;
        public bool IsPackage;
        public int Files;
        public string Error;
        public readonly List<SafetyItem> Items = new List<SafetyItem>();

        public SafetyLevel Level
        {
            get
            {
                var level = SafetyLevel.Clean;
                foreach (var item in Items)
                    if (item.Shown > level)
                        level = item.Shown;
                return level == SafetyLevel.Note ? SafetyLevel.Clean : level;
            }
        }

        public int Count(SafetyLevel level)
        {
            return Items.Count(i => i.Shown == level);
        }

        public IEnumerable<SafetyItem> Flagged
        {
            get { return Items.Where(i => i.Shown >= SafetyLevel.Check); }
        }

        public int Compiled
        {
            get { return Items.Count(i => i.IsCompiled); }
        }

        /// <summary>A few words for a list row: "clean", "2 DLLs", "dangerous".</summary>
        public string Badge
        {
            get
            {
                if (Error != null)
                    return "can't read";
                if (Level == SafetyLevel.Danger)
                    return "dangerous";
                int dlls = Items.Count(i => i.IsCompiled && !i.Trusted);
                if (Level == SafetyLevel.Check)
                    return dlls > 0 ? dlls + (dlls == 1 ? " DLL" : " DLLs") : "check";
                return "clean";
            }
        }
    }

    /// <summary>
    /// Looks through .unitypackage files and project folders for things that can run code, and for the
    /// tell-tale signs of token loggers and other malware: reading Discord's token folder or browser
    /// passwords, sending data to webhooks, starting with Windows, hidden PowerShell, code hidden in
    /// encoded text. Plain .NET only (no Unity calls), so it can run on a background thread.
    /// It can't prove a file is safe; it catches the common tricks.
    /// </summary>
    internal static class SafetyScanner
    {
        internal const string KindScript = "Script";
        internal const string KindDll = "DLL";
        internal const string KindNative = "Native plugin";
        internal const string KindProgram = "Program";
        internal const string KindCompiler = "Compiler settings";
        internal const string KindHidden = "Hidden program";
        internal const string KindPath = "Bad path";

        /// <summary>Set by the editor side: whether the user trusted a file with this hash.</summary>
        internal static Func<string, bool> IsTrusted;

        private const int HeadBytes = 8192;
        private const long TextLimit = 8L * 1024 * 1024;
        private const long BinaryLimit = 96L * 1024 * 1024;

        private static readonly HashSet<string> ScriptExtensions = Set(".cs");
        private static readonly HashSet<string> DllExtensions = Set(".dll");
        private static readonly HashSet<string> NativeExtensions = Set(".so", ".dylib", ".bundle", ".pyd");
        private static readonly HashSet<string> CompilerExtensions = Set(".rsp");

        // Windows runs these when double-clicked. Unity never does.
        private static readonly HashSet<string> ProgramExtensions = Set(
            ".exe", ".msi", ".msix", ".bat", ".cmd", ".ps1", ".psm1", ".vbs", ".vbe", ".js", ".jse", ".wsf", ".wsh",
            ".hta", ".jar", ".com", ".scr", ".pif", ".lnk", ".cpl", ".reg", ".sh", ".py", ".pyw", ".appref-ms");

        // Almost only ever used to trick people.
        private static readonly HashSet<string> DangerousExtensions = Set(".scr", ".pif", ".hta", ".com", ".cpl", ".lnk", ".vbe", ".jse", ".wsf");

        // Programs written as text: read them for the same tricks as scripts.
        private static readonly HashSet<string> TextProgramExtensions = Set(".bat", ".cmd", ".ps1", ".psm1", ".vbs", ".js", ".wsf", ".hta", ".sh", ".py", ".pyw", ".reg");

        // Quiet unless something in them is suspicious (docs sites and tool scripts ship these).
        private static readonly HashSet<string> QuietProgramExtensions = Set(".js", ".py", ".sh");

        // A program hiding behind one of these is never an accident.
        private static readonly HashSet<string> MediaExtensions = Set(
            ".png", ".jpg", ".jpeg", ".tga", ".psd", ".tif", ".tiff", ".gif", ".bmp", ".exr", ".hdr", ".fbx", ".obj", ".blend",
            ".wav", ".mp3", ".ogg", ".mp4", ".mat", ".prefab", ".asset", ".anim", ".controller", ".txt", ".pdf", ".shader");

        private static HashSet<string> Set(params string[] values)
        {
            return new HashSet<string>(values, StringComparer.OrdinalIgnoreCase);
        }

        // ---- What to look for ---------------------------------------------------------------------------------------

        [Flags]
        private enum Sig
        {
            None = 0,
            Steal = 1 << 0,
            Keylog = 1 << 1,
            Persist = 1 << 2,
            Defender = 1 << 3,
            Alloc = 1 << 4,
            Thread = 1 << 5,
            Send = 1 << 6,
            Fetch = 1 << 7,
            Run = 1 << 8,
            Shell = 1 << 9,
            Hidden = 1 << 10,
            Load = 1 << 11,
            Net = 1 << 12,
            Upload = 1 << 13,
            Download = 1 << 14,
            ExeName = 1 << 15,
            AutoRun = 1 << 16,
            UserDir = 1 << 17,
            Screen = 1 << 18,
            Win32 = 1 << 19,
            Obfuscated = 1 << 20,
            Unprotect = 1 << 21,
            BrowserFile = 1 << 22,
            BrowserName = 1 << 23,
            Packed = 1 << 24,
            HiddenExe = 1 << 25,
            Blob = 1 << 26,
            Decodes = 1 << 27,
            TestFile = 1 << 28
        }

        private sealed class Rule
        {
            public Sig Sig;
            public SafetyLevel Level;
            public string Text;
            public string Anchor;
            public Regex Pattern;
        }

        private static Rule Find(Sig sig, SafetyLevel level, string needle, string text)
        {
            // "a/b" in a needle matches a/b, a\b and a\\b, as paths are written in code.
            var parts = needle.Split('/');
            string pattern = string.Join(@"[\\/]+", parts.Select(Regex.Escape));
            string anchor = parts.OrderByDescending(p => p.Length).First();
            return new Rule { Sig = sig, Level = level, Text = text, Anchor = anchor, Pattern = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) };
        }

        private static Rule Match(Sig sig, SafetyLevel level, string anchor, string pattern, string text)
        {
            return new Rule { Sig = sig, Level = level, Text = text, Anchor = anchor, Pattern = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) };
        }

        private const string TokenFolder = "Reads the folder where Discord and browsers keep your login token";
        private const string DiscordFolder = "Looks inside Discord's app folders";
        private const string Wallets = "Looks for crypto wallets";
        private const string StartWithWindows = "Makes a program start every time Windows starts";
        private const string DefenderText = "Tries to switch off or get around Windows Defender";
        private const string OddTool = "Uses a Windows tool that malware often abuses";
        private const string PasteSite = "Downloads from a paste or file-sharing site (often used to hide code)";
        private const string CollectSite = "Talks to a site often used to collect stolen data";
        private const string LoadsCode = "Loads extra code while it runs";
        private const string Scrambled = "Scrambled so nobody can read what it does";

        /// <summary>
        /// The marker in WPFMA's test files (like antivirus test files): harmless, but treated as dangerous so the
        /// whole warning, report and quarantine can be tried safely.
        /// </summary>
        internal const string TestMarker = "WPFMA-SAFETY-TEST-FILE";

        private static readonly Rule[] Rules =
        {
            Find(Sig.TestFile, SafetyLevel.Danger, TestMarker, "Has WPFMA's test marker (this file is harmless)"),

            // Stealing logins
            Find(Sig.Steal, SafetyLevel.Danger, "local storage/leveldb", TokenFolder),
            // With the colon: the bare ID is just the rickroll video.
            Find(Sig.Steal, SafetyLevel.Danger, "dQw4w9WgXcQ:", "Has the code word used to unlock saved Discord tokens"),
            Match(Sig.Steal, SafetyLevel.Danger, "{6}", @"\{2[3-6]\}.{1,24}\{6\}.{1,24}\{2[5-9]\}", "Searches for Discord tokens (has the token pattern)"),
            Match(Sig.Steal, SafetyLevel.Danger, "mfa", @"mfa(\\){1,2}\.\[", "Searches for Discord tokens (has the token pattern)"),
            Find(Sig.Steal, SafetyLevel.Danger, "discord/local storage", DiscordFolder),
            Find(Sig.Steal, SafetyLevel.Danger, "roaming/discord", DiscordFolder),
            Find(Sig.Steal, SafetyLevel.Danger, "discordcanary", DiscordFolder),
            Find(Sig.Steal, SafetyLevel.Danger, "discordptb", DiscordFolder),
            Find(Sig.Steal, SafetyLevel.Danger, "lightcord", DiscordFolder),
            Find(Sig.Steal, SafetyLevel.Danger, "os_crypt", "Unlocks the key browsers use to protect saved passwords"),
            Find(Sig.Steal, SafetyLevel.Danger, "encrypted_key", "Unlocks the key browsers use to protect saved passwords"),
            Find(Sig.Steal, SafetyLevel.Danger, "loginusers.vdf", "Reads Steam's saved logins"),
            Find(Sig.Steal, SafetyLevel.Danger, "telegram desktop/tdata", "Reads Telegram's saved login"),
            Find(Sig.Steal, SafetyLevel.Danger, "wallet.dat", Wallets),
            Find(Sig.Steal, SafetyLevel.Danger, "exodus.wallet", Wallets),
            Find(Sig.Steal, SafetyLevel.Danger, "nkbihfbeogaeaoehlefnkodbefgpgknn", Wallets),
            Find(Sig.BrowserFile, SafetyLevel.Note, "login data", "Mentions the browser's saved-passwords file"),
            Find(Sig.BrowserFile, SafetyLevel.Note, "network/cookies", "Mentions the browser's cookies file"),
            Find(Sig.BrowserFile, SafetyLevel.Note, "user data/default", "Mentions the browser's profile folder"),
            Find(Sig.BrowserFile, SafetyLevel.Note, "user data/local state", "Mentions the browser's password key file"),
            Match(Sig.BrowserName, SafetyLevel.Note, "", @"google[\\/]+chrome|microsoft[\\/]+edge|bravesoftware|opera software|yandex[\\/]+yandexbrowser|vivaldi", "Mentions a web browser's folder"),
            Find(Sig.Keylog, SafetyLevel.Danger, "getasynckeystate", "Can watch what you type, even outside Unity"),
            Find(Sig.Keylog, SafetyLevel.Danger, "setwindowshookex", "Can watch what you type, even outside Unity"),
            Find(Sig.Unprotect, SafetyLevel.Check, "cryptunprotectdata", "Unlocks passwords that Windows keeps locked"),
            Match(Sig.Unprotect, SafetyLevel.Check, "unprotect", @"protecteddata\s*\.\s*unprotect", "Unlocks passwords that Windows keeps locked"),

            // Staying on the PC and hiding
            Find(Sig.Persist, SafetyLevel.Danger, "currentversion/run", StartWithWindows),
            Find(Sig.Persist, SafetyLevel.Danger, "start menu/programs/startup", StartWithWindows),
            Find(Sig.Persist, SafetyLevel.Danger, "schtasks", "Creates a scheduled task, a way to keep running in the background"),
            Find(Sig.Defender, SafetyLevel.Danger, "add-mppreference", DefenderText),
            Find(Sig.Defender, SafetyLevel.Danger, "set-mppreference", DefenderText),
            Find(Sig.Defender, SafetyLevel.Danger, "exclusionpath", DefenderText),
            Find(Sig.Defender, SafetyLevel.Danger, "disablerealtimemonitoring", DefenderText),
            Find(Sig.Alloc, SafetyLevel.Note, "virtualalloc", "Reserves memory to run raw machine code"),
            Match(Sig.Thread, SafetyLevel.Note, "process", @"createremotethread|writeprocessmemory|ntcreatethreadex", "Writes into other programs' memory"),
            Match(Sig.Thread, SafetyLevel.Note, "thread", @"\bcreatethread\b", "Starts raw machine code"),

            // Sending data out
            Match(Sig.Send, SafetyLevel.Check, "webhooks", @"discord(app)?\.com[\\/]+api[\\/]+(v\d+[\\/]+)?webhooks", "Sends data to a Discord webhook"),
            Find(Sig.Send, SafetyLevel.Check, "api.telegram.org/bot", "Sends data to a Telegram bot"),
            Find(Sig.Send, SafetyLevel.Check, "webhook.site", CollectSite),
            Find(Sig.Send, SafetyLevel.Check, "pipedream.net", CollectSite),
            Find(Sig.Send, SafetyLevel.Check, "requestbin", CollectSite),
            Match(Sig.Send, SafetyLevel.Check, "ngrok", @"ngrok(-free)?\.(io|app|dev)", CollectSite),
            Find(Sig.Send, SafetyLevel.Check, "trycloudflare.com", CollectSite),
            Find(Sig.Fetch, SafetyLevel.Check, "pastebin.com/raw", PasteSite),
            Find(Sig.Fetch, SafetyLevel.Check, "hastebin", PasteSite),
            Find(Sig.Fetch, SafetyLevel.Check, "paste.ee", PasteSite),
            Find(Sig.Fetch, SafetyLevel.Check, "rentry.co", PasteSite),
            Find(Sig.Fetch, SafetyLevel.Check, "transfer.sh", PasteSite),
            Find(Sig.Fetch, SafetyLevel.Check, "anonfiles", PasteSite),
            Find(Sig.Fetch, SafetyLevel.Check, "gofile.io", PasteSite),
            Find(Sig.Fetch, SafetyLevel.Check, "catbox.moe", PasteSite),
            Match(Sig.Fetch, SafetyLevel.Check, "attachments", @"cdn\.discordapp\.com[\\/]+attachments", "Downloads a file someone uploaded to Discord"),

            // Running other things
            Match(Sig.Run, SafetyLevel.Note, "start", @"process\s*\.\s*start\b", "Can start other programs"),
            Find(Sig.Run, SafetyLevel.Note, "processstartinfo", "Can start other programs"),
            Find(Sig.Run, SafetyLevel.Note, "shellexecute", "Can start other programs"),
            Find(Sig.Shell, SafetyLevel.Note, "powershell", "Uses PowerShell"),
            Find(Sig.Shell, SafetyLevel.Note, "cmd.exe", "Uses the Windows command prompt"),
            Find(Sig.Hidden, SafetyLevel.Check, "-encodedcommand", "Runs a hidden, encoded command"),
            Match(Sig.Hidden, SafetyLevel.Check, "-enc", @"\s-enc\s", "Runs a hidden, encoded command"),
            Match(Sig.Hidden, SafetyLevel.Check, "hidden", @"-w(indowstyle)?\s+hidden", "Hides the window it opens"),
            Match(Sig.Hidden, SafetyLevel.Check, "bypass", @"-(executionpolicy|ep)\s+bypass", "Skips PowerShell's safety check"),
            Match(Sig.Hidden, SafetyLevel.Check, "", @"\b(mshta|regsvr32|rundll32|bitsadmin|wscript|cscript)(\.exe)?\b", OddTool),
            Match(Sig.Hidden, SafetyLevel.Check, "certutil", @"certutil.{0,40}-(urlcache|decode)", OddTool),
            Match(Sig.Hidden, SafetyLevel.Check, "", @"invoke-expression|\biex\s*[\(\$]", "Runs code it downloads or builds on the fly"),

            // Loading code while running
            // Loading by name (Assembly.Load("UnityEditor")) is normal reflection; loading raw bytes or a file isn't.
            Match(Sig.Load, SafetyLevel.Check, "load", @"assembly\s*\.\s*load\s*\(\s*(?!@?"")", LoadsCode),
            Match(Sig.Load, SafetyLevel.Check, "load", @"assembly\s*\.\s*(unsafe)?load(from|file)\s*\(", LoadsCode),
            Match(Sig.Load, SafetyLevel.Check, "load", @"appdomain\s*\.\s*currentdomain\s*\.\s*load\s*\(\s*(?!@?"")", LoadsCode),
            Find(Sig.Load, SafetyLevel.Check, "unsafeloadfrom", LoadsCode),
            Find(Sig.Decodes, SafetyLevel.Note, "frombase64string", "Decodes data hidden as text"),

            // Internet
            Match(Sig.Net, SafetyLevel.Note, "", @"\b(unitywebrequest|httpclient|webclient|httpwebrequest|tcpclient|udpclient|clientwebsocket)\b", "Uses the internet"),
            Match(Sig.Upload, SafetyLevel.Note, "", @"\b(uploadvalues|uploaddata|uploadstring|uploadfile|postasync|multipartformdatacontent)\b|unitywebrequest\s*\.\s*post\b", "Sends data over the internet"),
            Match(Sig.Download, SafetyLevel.Note, "", @"\b(downloadfile|downloaddata|downloadfiletaskasync|downloaddatataskasync|getbytearrayasync)\b", "Downloads files"),
            Match(Sig.ExeName, SafetyLevel.Note, ".", @"\.(exe|scr|msi|bat|cmd|ps1|vbs)[""']", "Mentions a program file"),

            // Running by itself, and where it looks
            Match(Sig.AutoRun, SafetyLevel.Note, "", @"initializeonload|didreloadscripts|\bassetpostprocessor\b", "Runs by itself when Unity loads or imports"),
            Match(Sig.UserDir, SafetyLevel.Note, "", @"specialfolder\s*\.\s*(applicationdata|localapplicationdata|userprofile|desktop|mydocuments)|%(local)?appdata%|getenvironmentvariable\s*\(\s*""(local)?appdata|""userprofile""", "Looks in your Windows user folders"),
            Find(Sig.Screen, SafetyLevel.Note, "copyfromscreen", "Can take screenshots of your desktop"),
            Match(Sig.Win32, SafetyLevel.Note, "dllimport", @"dllimport\s*\(\s*""(kernel32|user32|ntdll|advapi32|crypt32)", "Calls Windows directly"),

            // Scrambled or packed DLLs
            Find(Sig.Obfuscated, SafetyLevel.Check, "confusedbyattribute", Scrambled),
            Find(Sig.Obfuscated, SafetyLevel.Check, "confuserex", Scrambled),
            Find(Sig.Obfuscated, SafetyLevel.Check, "smartassembly", Scrambled),
            Find(Sig.Obfuscated, SafetyLevel.Check, "eazfuscator", Scrambled),
            Find(Sig.Obfuscated, SafetyLevel.Check, ".net reactor", Scrambled),
            Find(Sig.Obfuscated, SafetyLevel.Check, "babelobfuscator", Scrambled),
            Find(Sig.Obfuscated, SafetyLevel.Check, "obfuscar", Scrambled),
            Find(Sig.Packed, SafetyLevel.Note, "costura", "Has other DLLs packed inside it")
        };

        // ---- Scanning one file --------------------------------------------------------------------------------------

        /// <summary>
        /// Checks one file. bytes may be null when only the start of the file was read (head); then only its type is
        /// judged. meta is the .meta text when known (DLL settings). Returns null for files that can't run anything.
        /// </summary>
        internal static SafetyItem ScanFile(string path, byte[] bytes, byte[] head, long size, string meta)
        {
            string ext = System.IO.Path.GetExtension(path) ?? string.Empty;
            head = head ?? bytes;
            var item = new SafetyItem { Path = path, Size = size };

            if (ScriptExtensions.Contains(ext))
                item.Kind = KindScript;
            else if (DllExtensions.Contains(ext))
                item.Kind = IsManaged(bytes ?? head) ? KindDll : KindNative;
            else if (NativeExtensions.Contains(ext))
                item.Kind = KindNative;
            else if (CompilerExtensions.Contains(ext))
                item.Kind = KindCompiler;
            else if (ProgramExtensions.Contains(ext))
                item.Kind = KindProgram;
            else if (IsWindowsProgram(head))
                item.Kind = KindHidden;
            else
                return null;

            if (bytes != null)
                item.Hash = Sha256(bytes);
            item.Trusted = item.Hash != null && IsTrusted != null && IsTrusted(item.Hash);

            var sigs = Sig.None;
            var reasons = new Dictionary<string, SafetyReason>();

            if (item.Kind == KindScript || (item.Kind == KindProgram && TextProgramExtensions.Contains(ext)) || item.Kind == KindCompiler)
            {
                if (bytes != null)
                    sigs |= ScanText(Encoding.UTF8.GetString(bytes), item.Kind == KindScript, reasons);
            }
            else if (item.Kind == KindDll || item.Kind == KindNative || item.Kind == KindHidden || item.Kind == KindProgram)
            {
                if (bytes != null)
                    sigs |= ScanBinary(bytes, item.Kind == KindDll, reasons);
            }

            if (item.Kind == KindCompiler && bytes != null)
            {
                string options = Encoding.UTF8.GetString(bytes);
                var analyzer = Regex.Match(options, @"(^|\s)[-/](a|analyzer):\S+", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                if (analyzer.Success)
                    Add(reasons, SafetyLevel.Check, "Adds a code analyzer that runs while Unity compiles", analyzer.Value.Trim());
                var outside = Regex.Match(options, @"(^|\s)[-/](r|reference):\s*""?([A-Za-z]:|\\|/)\S*", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                if (outside.Success)
                    Add(reasons, SafetyLevel.Check, "Pulls in a DLL from outside the project", outside.Value.Trim());
            }

            if (item.Kind == KindDll || item.Kind == KindNative)
            {
                item.Managed = item.Kind == KindDll;
                item.LoadsInEditor = LoadsInEditor(meta);
                if (meta != null && meta.IndexOf("RoslynAnalyzer", StringComparison.OrdinalIgnoreCase) >= 0)
                    Add(reasons, SafetyLevel.Check, "Runs while Unity compiles scripts (a code analyzer)", null);
            }

            Judge(item, ext, sigs, reasons);
            return item;
        }

        private static void Judge(SafetyItem item, string ext, Sig s, Dictionary<string, SafetyReason> reasons)
        {
            var level = SafetyLevel.Clean;
            string summary = null;

            Action<SafetyLevel, string> raise = (l, text) =>
            {
                if (l > level || (l == level && summary == null))
                {
                    level = l;
                    summary = text;
                }
            };

            // What kind of file it is sets the floor.
            if (item.Kind == KindDll)
                raise(SafetyLevel.Check, "Compiled code (a DLL). It can't be read like a script, so only keep it if you trust where it came from");
            else if (item.Kind == KindNative)
                raise(SafetyLevel.Check, "Raw machine code (a native plugin). It can't be checked, so only keep it if you trust where it came from");
            else if (item.Kind == KindHidden)
                raise(MediaExtensions.Contains(ext) ? SafetyLevel.Danger : SafetyLevel.Check, "A Windows program pretending to be a " + ext + " file");
            else if (item.Kind == KindProgram)
            {
                if (DangerousExtensions.Contains(ext))
                    raise(SafetyLevel.Danger, "A " + ext + " file. This kind of file is almost only used to trick people");
                else if (!QuietProgramExtensions.Contains(ext))
                    raise(SafetyLevel.Check, "A program (" + ext + "). Unity never runs it, but don't open it unless you trust it");
            }
            else if (item.Kind == KindCompiler)
                raise(SafetyLevel.Note, "Changes how Unity compiles scripts");

            if (Has(s, Sig.TestFile))
                raise(SafetyLevel.Danger, "WPFMA test file. It's harmless, but a real file flagged like this would be a token logger or other malware");

            // Combinations that only malware needs.
            bool steals = Has(s, Sig.Steal) || (Has(s, Sig.BrowserFile) && Has(s, Sig.BrowserName));
            if (Has(s, Sig.BrowserFile) && Has(s, Sig.BrowserName))
                Add(reasons, SafetyLevel.Danger, "Reads saved browser passwords or cookies", null);
            if (steals)
                raise(SafetyLevel.Danger, "Tries to read your Discord token or saved passwords. This is what token loggers do");
            if (Has(s, Sig.Keylog))
                raise(SafetyLevel.Danger, "Can watch what you type");
            if (Has(s, Sig.Persist))
                raise(SafetyLevel.Danger, "Tries to make itself start with Windows");
            if (Has(s, Sig.Defender))
                raise(SafetyLevel.Danger, "Tries to get around Windows Defender");
            if (Has(s, Sig.Alloc) && Has(s, Sig.Thread))
                raise(SafetyLevel.Danger, "Runs hidden machine code in memory, a way malware hides");
            if (Has(s, Sig.HiddenExe))
                raise(SafetyLevel.Danger, "Has a Windows program hidden inside it");
            if (Has(s, Sig.Hidden) && (Has(s, Sig.Shell) || Has(s, Sig.Run)))
                raise(SafetyLevel.Danger, "Runs hidden Windows commands");
            if (Has(s, Sig.Send) && (Has(s, Sig.AutoRun) || Has(s, Sig.Run) || Has(s, Sig.Load) || Has(s, Sig.UserDir) ||
                                     Has(s, Sig.Screen) || Has(s, Sig.Obfuscated) || Has(s, Sig.Unprotect) || Has(s, Sig.Win32)))
                raise(SafetyLevel.Danger, "Collects things from your PC and sends them to a webhook");
            if (Has(s, Sig.Unprotect) && (Has(s, Sig.Send) || Has(s, Sig.Upload)))
                raise(SafetyLevel.Danger, "Unlocks Windows-protected passwords and sends data out");
            if (Has(s, Sig.Fetch) && (Has(s, Sig.Load) || Has(s, Sig.Run)))
                raise(SafetyLevel.Danger, "Downloads code from a paste or file site and runs it");
            if (Has(s, Sig.Download) && Has(s, Sig.Run) && Has(s, Sig.ExeName))
                raise(SafetyLevel.Danger, "Downloads a program and runs it");
            if (Has(s, Sig.Load) && (Has(s, Sig.Net) || Has(s, Sig.Download) || Has(s, Sig.Fetch) || Has(s, Sig.Blob) || Has(s, Sig.Obfuscated) || Has(s, Sig.Decodes)))
                raise(SafetyLevel.Danger, "Loads hidden or downloaded code while it runs");

            // Worth a look on their own.
            if (Has(s, Sig.Send))
                raise(SafetyLevel.Check, "Sends data to a webhook or a data-collecting site");
            if (Has(s, Sig.Fetch))
                raise(SafetyLevel.Check, "Downloads from a paste or file-sharing site");
            if (Has(s, Sig.Unprotect))
                raise(SafetyLevel.Check, "Unlocks passwords that Windows keeps locked");
            if (Has(s, Sig.Load))
                raise(SafetyLevel.Check, LoadsCode);
            if (Has(s, Sig.Hidden))
                raise(SafetyLevel.Check, "Uses tricks to hide what it runs");
            if (Has(s, Sig.Obfuscated))
                raise(SafetyLevel.Check, Scrambled);
            if (Has(s, Sig.Blob))
                raise(SafetyLevel.Check, "Has a big blob of encoded data");
            if (Has(s, Sig.Run) && Has(s, Sig.Shell))
                raise(SafetyLevel.Check, "Runs Windows commands");
            if (Has(s, Sig.Screen) && (Has(s, Sig.Net) || Has(s, Sig.Upload)))
                raise(SafetyLevel.Check, "Takes screenshots and uses the internet");
            if (reasons.Values.Any(r => r.Level >= SafetyLevel.Check))
                raise(SafetyLevel.Check, reasons.Values.First(r => r.Level >= SafetyLevel.Check).Text);

            if (level == SafetyLevel.Clean && reasons.Count > 0)
                raise(SafetyLevel.Note, reasons.Values.First().Text);

            if (item.IsCompiled && item.Path.IndexOf("/VRCSDK/", StringComparison.OrdinalIgnoreCase) >= 0)
                Add(reasons, SafetyLevel.Note, "Looks like part of an old VRChat SDK copied into the package. It can clash with the SDK you have", null);

            item.Level = level;
            item.Summary = summary;
            item.Reasons.AddRange(reasons.Values.OrderByDescending(r => r.Level));
        }

        private static bool Has(Sig all, Sig one)
        {
            return (all & one) != 0;
        }

        private static void Add(Dictionary<string, SafetyReason> reasons, SafetyLevel level, string text, string evidence)
        {
            SafetyReason existing;
            if (reasons.TryGetValue(text, out existing))
            {
                if (level > existing.Level)
                    existing.Level = level;
                return;
            }

            reasons[text] = new SafetyReason { Level = level, Text = text, Evidence = evidence };
        }

        // ---- Scripts and text ---------------------------------------------------------------------------------------

        private static readonly Regex Base64Literal = new Regex(@"[A-Za-z0-9+/]{60,}={0,2}", RegexOptions.CultureInvariant);
        private static readonly Regex CharCast = new Regex(@"\(\s*char\s*\)\s*(0x[0-9a-fA-F]+|\d+)", RegexOptions.CultureInvariant);
        private static readonly Regex NumberList = new Regex(@"\{\s*((0x[0-9a-fA-F]{1,2}|\d{1,3})\s*,\s*){24,}(0x[0-9a-fA-F]{1,2}|\d{1,3})\s*,?\s*\}", RegexOptions.CultureInvariant);

        private static Sig ScanText(string text, bool csharp, Dictionary<string, SafetyReason> reasons)
        {
            string code = text;
            var literals = new StringBuilder();
            if (csharp)
                code = StripComments(text, literals);
            else
                literals.Append(text);

            string joined = literals.ToString();
            var reversed = new StringBuilder();
            foreach (var piece in joined.Split('\n'))
            {
                var chars = piece.ToCharArray();
                Array.Reverse(chars);
                reversed.Append(chars).Append('\n');
            }

            var decoded = new StringBuilder();
            var sigs = Decode(code, decoded, reasons);

            sigs |= Apply(code, true, null, reasons);
            sigs |= Apply(joined.Replace("\n", string.Empty), false, "built from pieces to hide it", reasons);
            sigs |= Apply(reversed.ToString(), false, "written backwards to hide it", reasons);
            if (decoded.Length > 0)
                sigs |= Apply(decoded.ToString(), false, "hidden in encoded text", reasons);
            return sigs;
        }

        /// <summary>Blanks out comments (keeps line numbers) and collects the text inside string literals.</summary>
        private static string StripComments(string text, StringBuilder literals)
        {
            var output = text.ToCharArray();
            int i = 0;
            int n = output.Length;
            while (i < n)
            {
                char c = output[i];
                char next = i + 1 < n ? output[i + 1] : '\0';
                if (c == '/' && next == '/')
                {
                    while (i < n && output[i] != '\n')
                        output[i++] = ' ';
                }
                else if (c == '/' && next == '*')
                {
                    while (i < n && !(output[i] == '*' && i + 1 < n && output[i + 1] == '/'))
                    {
                        if (output[i] != '\n')
                            output[i] = ' ';
                        i++;
                    }
                    if (i < n)
                    {
                        output[i++] = ' ';
                        output[i++] = ' ';
                    }
                }
                else if (c == '"' || ((c == '@' || c == '$') && (next == '"' || ((next == '@' || next == '$') && i + 2 < n && output[i + 2] == '"'))))
                {
                    bool verbatim = false;
                    while (output[i] != '"')
                    {
                        if (output[i] == '@')
                            verbatim = true;
                        i++;
                    }
                    i++;
                    while (i < n)
                    {
                        if (verbatim && output[i] == '"' && i + 1 < n && output[i + 1] == '"')
                        {
                            literals.Append('"');
                            i += 2;
                            continue;
                        }
                        if (!verbatim && output[i] == '\\' && i + 1 < n)
                        {
                            literals.Append(output[i]).Append(output[i + 1]);
                            i += 2;
                            continue;
                        }
                        if (output[i] == '"' || (!verbatim && output[i] == '\n'))
                            break;
                        literals.Append(output[i]);
                        i++;
                    }
                    i++;
                }
                else if (c == '\'')
                {
                    i++;
                    while (i < n && output[i] != '\'' && output[i] != '\n')
                        i += output[i] == '\\' ? 2 : 1;
                    i++;
                }
                else
                    i++;
            }

            return new string(output);
        }

        /// <summary>Unpacks text hidden as base64, (char) casts or number lists, and notices programs hidden that way.</summary>
        private static Sig Decode(string code, StringBuilder decoded, Dictionary<string, SafetyReason> reasons)
        {
            var sigs = Sig.None;

            foreach (Match m in Base64Literal.Matches(code))
            {
                string value = m.Value;
                if (value.Length % 4 != 0 || value.Distinct().Count() < 16)
                    continue;
                byte[] data;
                try
                {
                    data = Convert.FromBase64String(value);
                }
                catch (FormatException)
                {
                    continue;
                }

                sigs |= Unpacked(data, value.Length >= 1000, decoded, reasons, "base64 text");
            }

            var casts = CharCast.Matches(code);
            if (casts.Count >= 15)
            {
                var built = new StringBuilder();
                foreach (Match m in casts)
                {
                    int value = ParseNumber(m.Groups[1].Value);
                    if (value > 0 && value < 0x10000)
                        built.Append((char)value);
                }
                decoded.Append(built).Append('\n');
                sigs |= Sig.Obfuscated;
                Add(reasons, SafetyLevel.Check, "Builds text one letter at a time to hide it", built.Length > 60 ? built.ToString(0, 60) + "…" : built.ToString());
            }

            foreach (Match m in NumberList.Matches(code))
            {
                var numbers = Regex.Matches(m.Value, @"0x[0-9a-fA-F]{1,2}|\d{1,3}");
                var data = new byte[numbers.Count];
                bool fits = true;
                for (int k = 0; k < numbers.Count && fits; k++)
                {
                    int value = ParseNumber(numbers[k].Value);
                    fits = value <= 255;
                    data[k] = (byte)value;
                }
                if (fits)
                    sigs |= Unpacked(data, false, decoded, reasons, "a list of numbers");
            }

            return sigs;
        }

        private static Sig Unpacked(byte[] data, bool big, StringBuilder decoded, Dictionary<string, SafetyReason> reasons, string how)
        {
            if (IsWindowsProgram(data) || (data.Length >= 2 && data[0] == 'M' && data[1] == 'Z'))
            {
                Add(reasons, SafetyLevel.Danger, "Has a Windows program hidden inside it as " + how, null);
                return Sig.HiddenExe;
            }

            if (IsImage(data))
                return Sig.None;

            if (LooksLikeText(data))
            {
                decoded.Append(Encoding.UTF8.GetString(data)).Append('\n');
                return Sig.None;
            }

            if (!big)
                return Sig.None;
            Add(reasons, SafetyLevel.Check, "Has a big blob of encoded data that isn't a picture", null);
            return Sig.Blob;
        }

        private static int ParseNumber(string value)
        {
            try
            {
                return value.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt32(value.Substring(2), 16) : int.Parse(value);
            }
            catch (Exception)
            {
                return -1;
            }
        }

        /// <summary>Runs every rule over one view of the file. Evidence is the line it was found on (for code).</summary>
        private static Sig Apply(string view, bool lines, string how, Dictionary<string, SafetyReason> reasons, Sig skip = Sig.None)
        {
            var sigs = Sig.None;
            if (string.IsNullOrEmpty(view))
                return sigs;

            foreach (var rule in Rules)
            {
                if ((rule.Sig & skip) != 0)
                    continue;
                if (rule.Anchor.Length > 0 && view.IndexOf(rule.Anchor, StringComparison.OrdinalIgnoreCase) < 0)
                    continue;
                var m = rule.Pattern.Match(view);
                if (!m.Success)
                    continue;

                sigs |= rule.Sig;
                string evidence = lines ? LineAt(view, m.Index) : Snippet(view, m.Index, m.Length);
                if (how != null)
                    evidence = "(" + how + ") " + evidence;
                Add(reasons, rule.Level, rule.Text, evidence);
            }

            return sigs;
        }

        private static string LineAt(string text, int index)
        {
            int start = text.LastIndexOf('\n', Math.Max(0, index - 1)) + 1;
            int end = text.IndexOf('\n', index);
            if (end < 0)
                end = text.Length;
            int line = 1;
            for (int k = 0; k < start; k++)
                if (text[k] == '\n')
                    line++;
            string content = text.Substring(start, end - start).Trim();
            if (content.Length > 140)
                content = content.Substring(0, 140) + "…";
            return "line " + line + ": " + content;
        }

        private static string Snippet(string text, int index, int length)
        {
            int start = Math.Max(0, index - 30);
            int end = Math.Min(text.Length, index + length + 50);
            var piece = new StringBuilder();
            for (int k = start; k < end; k++)
            {
                char c = text[k];
                piece.Append(c < ' ' || c > '~' ? ' ' : c);
            }
            return Regex.Replace(piece.ToString(), @"\s{2,}", " ").Trim();
        }

        // ---- DLLs and other compiled files ----------------------------------------------------------------------------

        // Every Windows program uses these; they only mean something in scripts and .NET DLLs.
        private const Sig ProgramApis = Sig.Alloc | Sig.Thread | Sig.Keylog | Sig.Unprotect | Sig.Win32 | Sig.Run | Sig.Net |
                                        Sig.Upload | Sig.Download | Sig.ExeName | Sig.AutoRun | Sig.UserDir | Sig.Screen |
                                        Sig.Load | Sig.Decodes | Sig.Shell;

        private const int StringsLimit = 64 * 1024 * 1024;

        private static Sig ScanBinary(byte[] bytes, bool managed, Dictionary<string, SafetyReason> reasons)
        {
            // Only the readable text inside: names (types, methods, Windows calls) are ASCII, string literals in
            // .NET DLLs are UTF-16.
            string strings = ExtractStrings(bytes, StringsLimit);
            Sig skip = managed ? Sig.None : ProgramApis;

            var sigs = Sig.None;
            sigs |= Apply(strings, false, null, reasons, skip);

            // Base64 hidden in its strings.
            var decoded = new StringBuilder();
            foreach (var view in new[] { strings })
            {
                foreach (Match m in Base64Literal.Matches(view))
                {
                    if (m.Value.Length < 200 || m.Value.Length % 4 != 0)
                        continue;
                    try
                    {
                        sigs |= Unpacked(Convert.FromBase64String(m.Value), m.Value.Length >= 4000, decoded, reasons, "base64 text");
                    }
                    catch (FormatException)
                    {
                    }
                }
            }
            if (decoded.Length > 0)
                sigs |= Apply(decoded.ToString(), false, "hidden in encoded text", reasons, skip);

            // Another program packed inside this one.
            int inner = IndexOf(bytes, Encoding.ASCII.GetBytes("This program cannot be run in DOS mode"), 1024);
            if (inner >= 0)
            {
                Add(reasons, SafetyLevel.Note, "Carries another program packed inside it", null);
                sigs |= Sig.Packed;
            }

            return sigs;
        }

        /// <summary>Runs of readable ASCII and UTF-16 text (5+ letters), one per line, like the "strings" tool.</summary>
        private static string ExtractStrings(byte[] bytes, int limit)
        {
            int n = Math.Min(bytes.Length, limit);
            var output = new StringBuilder(Math.Min(n / 4, 16 * 1024 * 1024));
            var run = new StringBuilder();

            int start = 0;
            for (int i = 0; i <= n; i++)
            {
                byte b = i < n ? bytes[i] : (byte)0;
                if ((b >= 0x20 && b < 0x7F) || b == '\t')
                    continue;
                if (i - start >= 5)
                    output.Append(Encoding.ASCII.GetString(bytes, start, i - start)).Append('\n');
                start = i + 1;
            }

            for (int align = 0; align < 2; align++)
            {
                run.Length = 0;
                for (int i = align; i + 1 < n; i += 2)
                {
                    byte lo = bytes[i];
                    byte hi = bytes[i + 1];
                    if (hi == 0 && ((lo >= 0x20 && lo < 0x7F) || lo == '\t'))
                    {
                        run.Append((char)lo);
                        continue;
                    }
                    if (run.Length >= 5)
                        output.Append(run).Append('\n');
                    run.Length = 0;
                }
                if (run.Length >= 5)
                    output.Append(run).Append('\n');
            }

            return output.ToString();
        }

        private static int IndexOf(byte[] haystack, byte[] needle, int from)
        {
            for (int i = from; i <= haystack.Length - needle.Length; i++)
            {
                if (haystack[i] != needle[0])
                    continue;
                int k = 1;
                while (k < needle.Length && haystack[i + k] == needle[k])
                    k++;
                if (k == needle.Length)
                    return i;
            }
            return -1;
        }

        private static bool IsWindowsProgram(byte[] head)
        {
            if (head == null || head.Length < 0x40 || head[0] != 'M' || head[1] != 'Z')
                return false;
            int pe = BitConverter.ToInt32(head, 0x3C);
            return pe > 0 && pe + 4 <= head.Length && head[pe] == 'P' && head[pe + 1] == 'E' && head[pe + 2] == 0 && head[pe + 3] == 0;
        }

        private static bool IsManaged(byte[] bytes)
        {
            // .NET metadata starts with "BSJB".
            return bytes != null && IndexOf(bytes, new byte[] { (byte)'B', (byte)'S', (byte)'J', (byte)'B' }, 0) >= 0;
        }

        private static bool IsImage(byte[] data)
        {
            if (data.Length < 4)
                return false;
            return (data[0] == 0x89 && data[1] == 'P' && data[2] == 'N' && data[3] == 'G') ||
                   (data[0] == 0xFF && data[1] == 0xD8) ||
                   (data[0] == 'G' && data[1] == 'I' && data[2] == 'F') ||
                   (data[0] == 'R' && data[1] == 'I' && data[2] == 'F' && data[3] == 'F');
        }

        private static bool LooksLikeText(byte[] data)
        {
            if (data.Length == 0)
                return false;
            int printable = 0;
            int count = Math.Min(data.Length, 4096);
            for (int i = 0; i < count; i++)
            {
                byte b = data[i];
                if (b == 0)
                    return false;
                if (b >= 32 || b == '\n' || b == '\r' || b == '\t')
                    printable++;
            }
            return printable >= count * 0.9;
        }

        /// <summary>Whether Unity loads this DLL in the editor, from its .meta (no .meta means the default: yes).</summary>
        internal static bool LoadsInEditor(string meta)
        {
            if (string.IsNullOrEmpty(meta) || meta.IndexOf("platformData", StringComparison.Ordinal) < 0)
                return true;

            bool any = false;
            bool editor = false;
            bool excludeEditor = false;
            foreach (var block in meta.Split(new[] { "- first:" }, StringSplitOptions.None).Skip(1))
            {
                var enabled = Regex.Match(block, @"enabled:\s*(\d)");
                bool on = enabled.Success && enabled.Groups[1].Value == "1";
                string first = block.TrimStart().Split('\n')[0].Trim();
                if (Regex.IsMatch(first, @"^(:\s*Any|Any:)"))
                {
                    any = on;
                    excludeEditor = Regex.IsMatch(block, @"Exclude Editor:\s*1");
                }
                else if (Regex.IsMatch(first, @"^Editor:\s*Editor"))
                    editor = on;
            }
            return editor || (any && !excludeEditor);
        }

        private static string Sha256(byte[] bytes)
        {
            using (var sha = SHA256.Create())
                return BitConverter.ToString(sha.ComputeHash(bytes)).Replace("-", string.Empty).ToLowerInvariant();
        }

        internal static string HashFile(string path)
        {
            using (var sha = SHA256.Create())
            using (var stream = File.OpenRead(path))
                return BitConverter.ToString(sha.ComputeHash(stream)).Replace("-", string.Empty).ToLowerInvariant();
        }

        // ---- .unitypackage files ------------------------------------------------------------------------------------

        private sealed class Entry
        {
            public string PathName;
            public byte[] Bytes;
            public byte[] Head;
            public long Size;
            public string Meta;
            public bool HasAsset;
        }

        /// <summary>Reads a .unitypackage without importing it. Only files that could run code are kept in memory.</summary>
        internal static SafetyReport ScanPackage(string packagePath, Action<float> progress = null)
        {
            var report = new SafetyReport { Source = packagePath, IsPackage = true };
            var entries = new Dictionary<string, Entry>(StringComparer.Ordinal);
            string current = null;

            try
            {
                using (var file = File.OpenRead(packagePath))
                using (var gzip = new GZipStream(file, CompressionMode.Decompress))
                {
                    var reader = new TarReader(gzip);
                    TarEntry tar;
                    while ((tar = reader.Next()) != null)
                    {
                        if (progress != null && file.Length > 0)
                            progress((float)file.Position / file.Length);

                        string name = tar.Name.Replace('\\', '/').TrimStart('.', '/');
                        int slash = name.IndexOf('/');
                        if (slash <= 0 || !tar.IsFile)
                        {
                            reader.Skip();
                            continue;
                        }

                        string guid = name.Substring(0, slash);
                        string part = name.Substring(slash + 1).Trim('/');
                        if (current != null && current != guid)
                            Finish(entries, current, report);
                        current = guid;

                        Entry entry;
                        if (!entries.TryGetValue(guid, out entry))
                            entries[guid] = entry = new Entry();

                        if (part.Equals("pathname", StringComparison.OrdinalIgnoreCase))
                            entry.PathName = Encoding.UTF8.GetString(reader.ReadAll(4096)).Split('\n')[0].Trim();
                        else if (part.Equals("asset.meta", StringComparison.OrdinalIgnoreCase))
                            entry.Meta = Encoding.UTF8.GetString(reader.ReadAll(1024 * 1024));
                        else if (part.Equals("asset", StringComparison.OrdinalIgnoreCase))
                        {
                            entry.HasAsset = true;
                            entry.Size = tar.Size;
                            entry.Head = reader.ReadHead(HeadBytes);
                            if (Wanted(entry.PathName, entry.Head, tar.Size))
                                entry.Bytes = reader.ReadAll(BinaryLimit);
                            else
                                reader.Skip();
                        }
                        else
                            reader.Skip();
                    }
                }

                foreach (var guid in entries.Keys.ToList())
                    Finish(entries, guid, report);
            }
            catch (Exception e)
            {
                report.Error = "Couldn't read this package (" + e.Message + "). It may be damaged, or not a real .unitypackage.";
            }

            report.Items.Sort(CompareItems);
            return report;
        }

        /// <summary>Whether to keep an asset's bytes before knowing (or once knowing) its name.</summary>
        private static bool Wanted(string pathName, byte[] head, long size)
        {
            if (pathName != null)
            {
                string ext = System.IO.Path.GetExtension(pathName) ?? string.Empty;
                bool code = ScriptExtensions.Contains(ext) || DllExtensions.Contains(ext) || NativeExtensions.Contains(ext) ||
                            CompilerExtensions.Contains(ext) || ProgramExtensions.Contains(ext);
                return code || IsWindowsProgram(head);
            }

            // Name not seen yet: keep programs and small text, which is what scripts look like.
            if (IsWindowsProgram(head) || (head.Length >= 2 && head[0] == 'M' && head[1] == 'Z') || (head.Length >= 4 && head[0] == 0x7F && head[1] == 'E'))
                return true;
            return size <= TextLimit && Array.IndexOf(head, (byte)0) < 0;
        }

        private static void Finish(Dictionary<string, Entry> entries, string guid, SafetyReport report)
        {
            Entry entry;
            if (!entries.TryGetValue(guid, out entry) || entry.PathName == null)
                return;
            entries.Remove(guid);
            if (!entry.HasAsset)
                return;

            report.Files++;
            string path = entry.PathName.Replace('\\', '/');

            if (path.Contains("../") || path.Contains("/..") || path.StartsWith("/", StringComparison.Ordinal) ||
                Regex.IsMatch(path, @"^[A-Za-z]:") ||
                !(path.StartsWith("Assets/", StringComparison.Ordinal) || path.StartsWith("Packages/", StringComparison.Ordinal)))
            {
                var bad = new SafetyItem { Path = path, Guid = guid, Kind = KindPath, Size = entry.Size, Level = SafetyLevel.Danger, Summary = "Tries to put a file outside your project folder" };
                bad.Reasons.Add(new SafetyReason { Level = SafetyLevel.Danger, Text = bad.Summary, Evidence = path });
                report.Items.Add(bad);
                return;
            }

            if (entry.Bytes == null && !Wanted(path, entry.Head ?? new byte[0], entry.Size))
                return;

            var item = ScanFile(path, entry.Bytes, entry.Head, entry.Size, entry.Meta);
            if (item == null)
                return;
            item.Guid = guid;
            if (entry.Bytes == null)
                item.Reasons.Add(new SafetyReason { Level = SafetyLevel.Note, Text = "Too big to read fully" });
            report.Items.Add(item);
        }

        private static int CompareItems(SafetyItem a, SafetyItem b)
        {
            int level = b.Shown.CompareTo(a.Shown);
            return level != 0 ? level : string.Compare(a.Path, b.Path, StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// Writes a copy of a .unitypackage without the given entries (by guid), so the rest can be imported
        /// without them.
        /// </summary>
        /// <summary>
        /// Writes some of a package's files (by guid) straight to a folder, with their .meta, without importing
        /// anything. files maps guid to the project path to use under destination.
        /// </summary>
        internal static void Extract(string packagePath, IDictionary<string, string> files, string destination)
        {
            using (var input = File.OpenRead(packagePath))
            using (var gzip = new GZipStream(input, CompressionMode.Decompress))
            {
                var reader = new TarReader(gzip);
                TarEntry tar;
                while ((tar = reader.Next()) != null)
                {
                    string name = tar.Name.Replace('\\', '/').TrimStart('.', '/');
                    int slash = name.IndexOf('/');
                    string path;
                    if (slash <= 0 || !tar.IsFile || !files.TryGetValue(name.Substring(0, slash), out path))
                    {
                        reader.Skip();
                        continue;
                    }

                    string part = name.Substring(slash + 1).Trim('/');
                    string target = System.IO.Path.Combine(destination, path);
                    if (part.Equals("asset.meta", StringComparison.OrdinalIgnoreCase))
                        target += ".meta";
                    else if (!part.Equals("asset", StringComparison.OrdinalIgnoreCase))
                    {
                        reader.Skip();
                        continue;
                    }

                    Directory.CreateDirectory(System.IO.Path.GetDirectoryName(target));
                    File.WriteAllBytes(target, reader.ReadAll(long.MaxValue));
                }
            }
        }

        internal static void WriteWithout(string packagePath, ICollection<string> leaveOut, string outputPath)
        {
            using (var input = File.OpenRead(packagePath))
            using (var gzipIn = new GZipStream(input, CompressionMode.Decompress))
            using (var output = File.Create(outputPath))
            using (var gzipOut = new GZipStream(output, CompressionLevel.Fastest))
            {
                var reader = new TarReader(gzipIn);
                TarEntry tar;
                while ((tar = reader.Next()) != null)
                {
                    string name = tar.Name.Replace('\\', '/').TrimStart('.', '/');
                    int slash = name.IndexOf('/');
                    string guid = slash > 0 ? name.Substring(0, slash) : name.TrimEnd('/');
                    if (leaveOut.Contains(guid))
                    {
                        reader.Skip();
                        continue;
                    }

                    reader.CopyTo(gzipOut);
                }

                gzipOut.Write(new byte[1024], 0, 1024);
            }
        }

        private sealed class TarEntry
        {
            public string Name;
            public long Size;
            public char Type;
            public bool IsFile { get { return Type == '0' || Type == '\0' || Type == '7'; } }
        }

        /// <summary>Just enough of tar for .unitypackage files: plain files, GNU long names and pax paths.</summary>
        private sealed class TarReader
        {
            private readonly Stream stream;
            private byte[] header;
            private readonly List<byte[]> extra = new List<byte[]>();
            private long remaining;
            private long padding;
            private byte[] headRead;

            public TarReader(Stream stream)
            {
                this.stream = stream;
            }

            public TarEntry Next()
            {
                Finish();
                extra.Clear();
                string longName = null;

                while (true)
                {
                    header = new byte[512];
                    if (!Fill(header, 512) || header.All(b => b == 0))
                        return null;

                    var entry = new TarEntry
                    {
                        Name = Encoding.UTF8.GetString(header, 0, 100).TrimEnd('\0', ' '),
                        Size = ParseOctal(header, 124, 12),
                        Type = (char)header[156]
                    };
                    string prefix = Encoding.UTF8.GetString(header, 345, 155).TrimEnd('\0', ' ');
                    // Only POSIX tar uses this field for a path prefix (GNU tar keeps other things there).
                    if (prefix.Length > 0 && Encoding.ASCII.GetString(header, 257, 6) == "ustar\0")
                        entry.Name = prefix + "/" + entry.Name;
                    remaining = entry.Size;
                    padding = (512 - entry.Size % 512) % 512;
                    headRead = null;

                    if (entry.Type == 'L' || entry.Type == 'x' || entry.Type == 'g')
                    {
                        var data = ReadAll(entry.Size);
                        var block = new byte[512 + data.Length + (512 - data.Length % 512) % 512];
                        Buffer.BlockCopy(header, 0, block, 0, 512);
                        Buffer.BlockCopy(data, 0, block, 512, data.Length);
                        extra.Add(block);
                        Finish();
                        if (entry.Type == 'L')
                            longName = Encoding.UTF8.GetString(data).TrimEnd('\0', ' ');
                        else if (entry.Type == 'x')
                        {
                            var path = Regex.Match(Encoding.UTF8.GetString(data), @"\d+ path=([^\n]*)\n");
                            if (path.Success)
                                longName = path.Groups[1].Value;
                        }
                        continue;
                    }

                    if (longName != null)
                        entry.Name = longName;
                    return entry;
                }
            }

            /// <summary>The first bytes of the entry; ReadAll afterwards still returns the whole thing.</summary>
            public byte[] ReadHead(int count)
            {
                var head = new byte[(int)Math.Min(count, remaining)];
                Fill(head, head.Length);
                remaining -= head.Length;
                headRead = head;
                return head;
            }

            public byte[] ReadAll(long limit)
            {
                long take = Math.Min(remaining, limit);
                int before = headRead != null ? headRead.Length : 0;
                var data = new byte[before + take];
                if (headRead != null)
                    Buffer.BlockCopy(headRead, 0, data, 0, before);
                Fill(data, (int)take, before);
                remaining -= take;
                headRead = null;
                return data;
            }

            public void Skip()
            {
                Finish();
            }

            /// <summary>Copies this entry, with any long-name headers before it, unchanged.</summary>
            public void CopyTo(Stream target)
            {
                foreach (var block in extra)
                    target.Write(block, 0, block.Length);
                target.Write(header, 0, 512);
                var buffer = new byte[81920];
                while (remaining > 0)
                {
                    int got = stream.Read(buffer, 0, (int)Math.Min(buffer.Length, remaining));
                    if (got <= 0)
                        throw new EndOfStreamException();
                    target.Write(buffer, 0, got);
                    remaining -= got;
                }
                if (padding > 0)
                    target.Write(new byte[padding], 0, (int)padding);
                Finish();
            }

            private void Finish()
            {
                var buffer = new byte[81920];
                long left = remaining + padding;
                while (left > 0)
                {
                    int got = stream.Read(buffer, 0, (int)Math.Min(buffer.Length, left));
                    if (got <= 0)
                        break;
                    left -= got;
                }
                remaining = 0;
                padding = 0;
                headRead = null;
            }

            private bool Fill(byte[] buffer, int count, int offset = 0)
            {
                int read = 0;
                while (read < count)
                {
                    int got = stream.Read(buffer, offset + read, count - read);
                    if (got <= 0)
                        return false;
                    read += got;
                }
                return true;
            }

            private static long ParseOctal(byte[] data, int offset, int length)
            {
                // Big files use the base-256 form.
                if ((data[offset] & 0x80) != 0)
                {
                    long big = 0;
                    for (int i = offset + 1; i < offset + length; i++)
                        big = (big << 8) | data[i];
                    return big;
                }

                long value = 0;
                for (int i = offset; i < offset + length; i++)
                {
                    byte c = data[i];
                    if (c == 0 || c == ' ')
                    {
                        if (value > 0)
                            break;
                        continue;
                    }
                    if (c < '0' || c > '7')
                        break;
                    value = value * 8 + (c - '0');
                }
                return value;
            }
        }

        // ---- Folders in the project -----------------------------------------------------------------------------------

        // Unity's and VRChat's own packages, and this SDK: not worth flagging.
        private static readonly string[] SkippedPackages = { "com.vrchat.", "com.unity.", "com.autodesk.", "com.wpfma." };

        private static readonly string[] SkippedAssets = { "Assets/WPFMA-SDK/", "Assets/WPFMA-SDK-Dev/" };

        /// <summary>Checks Assets/ and the non-Unity packages in Packages/. projectRoot is the folder holding Assets.</summary>
        internal static SafetyReport ScanProject(string projectRoot, Action<float> progress = null)
        {
            var report = new SafetyReport { Source = "This project", IsPackage = false };
            var files = new List<string>();

            Collect(System.IO.Path.Combine(projectRoot, "Assets"), files);
            string packages = System.IO.Path.Combine(projectRoot, "Packages");
            if (Directory.Exists(packages))
            {
                foreach (var dir in Directory.GetDirectories(packages))
                {
                    string name = System.IO.Path.GetFileName(dir);
                    if (!SkippedPackages.Any(p => name.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
                        Collect(dir, files);
                }
            }

            for (int i = 0; i < files.Count; i++)
            {
                if (progress != null && i % 50 == 0)
                    progress((float)i / Math.Max(1, files.Count));

                string full = files[i];
                string path = full.Substring(projectRoot.Length).Replace('\\', '/').TrimStart('/');
                if (SkippedAssets.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase)))
                    continue;

                report.Files++;
                var item = ScanDiskFile(full, path);
                if (item != null)
                    report.Items.Add(item);
            }

            report.Items.Sort(CompareItems);
            return report;
        }

        private static void Collect(string dir, List<string> files)
        {
            if (!Directory.Exists(dir))
                return;
            var stack = new Stack<string>();
            stack.Push(dir);
            while (stack.Count > 0)
            {
                string folder = stack.Pop();
                // Unity ignores folders starting with "." or ending with "~".
                string name = System.IO.Path.GetFileName(folder);
                if (folder != dir && (name.EndsWith("~", StringComparison.Ordinal) || name.StartsWith(".", StringComparison.Ordinal)))
                    continue;
                try
                {
                    foreach (var sub in Directory.GetDirectories(folder))
                        stack.Push(sub);
                    foreach (var file in Directory.GetFiles(folder))
                    {
                        if (!file.EndsWith(".meta", StringComparison.OrdinalIgnoreCase))
                            files.Add(file);
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        /// <summary>Checks one file on disk (path is the project path shown to the user). Null if it can't run code.</summary>
        internal static SafetyItem ScanDiskFile(string fullPath, string path)
        {
            try
            {
                var info = new FileInfo(fullPath);
                if (!info.Exists)
                    return null;

                var head = new byte[(int)Math.Min(HeadBytes, info.Length)];
                using (var stream = File.OpenRead(fullPath))
                {
                    int read = 0;
                    while (read < head.Length)
                    {
                        int got = stream.Read(head, read, head.Length - read);
                        if (got <= 0)
                            break;
                        read += got;
                    }
                }

                if (!Wanted(path, head, info.Length))
                    return null;

                byte[] bytes = info.Length <= BinaryLimit ? File.ReadAllBytes(fullPath) : null;
                string metaPath = fullPath + ".meta";
                string meta = File.Exists(metaPath) ? File.ReadAllText(metaPath) : null;
                return ScanFile(path, bytes, head, info.Length, meta);
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>Whether a project path is a kind of file Unity runs, or might hide a program (worth checking).</summary>
        internal static bool WorthChecking(string path)
        {
            string ext = System.IO.Path.GetExtension(path) ?? string.Empty;
            return ScriptExtensions.Contains(ext) || DllExtensions.Contains(ext) || NativeExtensions.Contains(ext) ||
                   CompilerExtensions.Contains(ext) || ProgramExtensions.Contains(ext);
        }
    }
}
#endif
