public IActionResult GetWindowsData()
    {
        string[][] result =
        {
            _ctx.OperatingSystems.Where(o => o.Name == PlatformID.Win32NT.ToString()).OrderByDescending(o => o.Count).
            Take(10).
            Select(x =>
                   $"{DetectOS.GetPlatformName(PlatformID.Win32NT, x.Version)}{(string.IsNullOrEmpty(x.Version) ? "" : " ")}{x.Version}").
            ToArray(),
            _ctx.OperatingSystems.Where(o => o.Name == PlatformID.Win32NT.ToString()).OrderByDescending(o => o.Count).
            Take(10).Select(x => x.Count.ToString()).ToArray()
        };

        if (result[0].Length < 10)
        {
            return(Json(result));
        }

        result[0][9] = "Other";

        result[1][9] = (_ctx.OperatingSystems.Where(o => o.Name == PlatformID.Win32NT.ToString()).Sum(o => o.Count) -
                        result[1].Take(9).Sum(long.Parse)).ToString();

        return(Json(result));
    }
Exemple #2
0
 /// <summary>
 ///     Gets XML software type for the running version
 /// </summary>
 /// <returns>XML software type</returns>
 public static SoftwareType GetSoftwareType() =>
 new SoftwareType
 {
     Name            = "DiscImageChef",
     OperatingSystem = DetectOS.GetRealPlatformID().ToString(),
     Version         = typeof(Version).Assembly.GetName().Version.ToString()
 };
Exemple #3
0
        public static DeviceInfo[] ListDevices(string dicRemote = null)
        {
            if (dicRemote is null)
            {
                switch (DetectOS.GetRealPlatformID())
                {
                case PlatformID.Win32NT: return(Windows.ListDevices.GetList());

                case PlatformID.Linux: return(Linux.ListDevices.GetList());

                case PlatformID.FreeBSD: return(FreeBSD.ListDevices.GetList());

                default:
                    throw new InvalidOperationException(
                              $"Platform {DetectOS.GetRealPlatformID()} not yet supported.");
                }
            }

            try
            {
                using (var remote = new Remote.Remote(dicRemote))
                {
                    return(remote.ListDevices());
                }
            }
            catch (Exception)
            {
                DicConsole.ErrorWriteLine("Error connecting to host.");
                return(new DeviceInfo[0]);
            }
        }
Exemple #4
0
        /// <summary>Sends a SCSI command</summary>
        /// <returns>0 if no error occurred, otherwise, errno</returns>
        /// <param name="fd">File handle</param>
        /// <param name="cdb">SCSI CDB</param>
        /// <param name="buffer">Buffer for SCSI command response</param>
        /// <param name="senseBuffer">Buffer with the SCSI sense</param>
        /// <param name="timeout">Timeout in seconds</param>
        /// <param name="direction">SCSI command transfer direction</param>
        /// <param name="duration">Time it took to execute the command in milliseconds</param>
        /// <param name="sense">
        ///     <c>True</c> if SCSI error returned non-OK status and <paramref name="senseBuffer" /> contains SCSI
        ///     sense
        /// </param>
        /// <exception cref="InvalidOperationException">If the specified platform is not supported</exception>
        internal static int SendScsiCommand(object fd, byte[] cdb, ref byte[] buffer, out byte[] senseBuffer,
                                            uint timeout, ScsiDirection direction, out double duration, out bool sense)
        {
            PlatformID ptId = DetectOS.GetRealPlatformID();

            return(SendScsiCommand(ptId, fd, cdb, ref buffer, out senseBuffer, timeout, direction, out duration,
                                   out sense));
        }
Exemple #5
0
        public static DeviceInfo[] ListDevices(out bool isRemote, out string serverApplication,
                                               out string serverVersion, out string serverOperatingSystem,
                                               out string serverOperatingSystemVersion, out string serverArchitecture,
                                               string aaruRemote = null)
        {
            isRemote                     = false;
            serverApplication            = null;
            serverVersion                = null;
            serverOperatingSystem        = null;
            serverOperatingSystemVersion = null;
            serverArchitecture           = null;

            if (aaruRemote is null)
            {
                switch (DetectOS.GetRealPlatformID())
                {
                case PlatformID.Win32NT: return(Windows.ListDevices.GetList());

                case PlatformID.Linux:   return(Linux.ListDevices.GetList());

                case PlatformID.FreeBSD: return(FreeBSD.ListDevices.GetList());

                default:
                    throw new
                          InvalidOperationException($"Platform {DetectOS.GetRealPlatformID()} not yet supported.");
                }
            }

            try
            {
                var aaruUri = new Uri(aaruRemote);

                if (aaruUri.Scheme != "aaru" &&
                    aaruUri.Scheme != "dic")
                {
                    AaruConsole.ErrorWriteLine("Invalid remote URI.");

                    return(new DeviceInfo[0]);
                }

                using var remote = new Remote.Remote(aaruUri);

                isRemote                     = true;
                serverApplication            = remote.ServerApplication;
                serverVersion                = remote.ServerVersion;
                serverOperatingSystem        = remote.ServerOperatingSystem;
                serverOperatingSystemVersion = remote.ServerOperatingSystemVersion;
                serverArchitecture           = remote.ServerArchitecture;

                return(remote.ListDevices());
            }
            catch (Exception)
            {
                AaruConsole.ErrorWriteLine("Error connecting to host.");

                return(new DeviceInfo[0]);
            }
        }
Exemple #6
0
 /// <summary>
 ///     Loads saved statistics from disk
 /// </summary>
 public static void LoadStats()
 {
     if (File.Exists(Path.Combine(Settings.Settings.StatsPath, "Statistics.xml")))
     {
         AllStats     = new Stats();
         CurrentStats = new Stats
         {
             OperatingSystems =
                 new List <OsStats>
             {
                 new OsStats
                 {
                     name    = DetectOS.GetRealPlatformID().ToString(),
                     Value   = 1,
                     version = DetectOS.GetVersion()
                 }
             },
             Versions = new List <NameValueStats> {
                 new NameValueStats {
                     name = Version.GetVersion(), Value = 1
                 }
             }
         };
         XmlSerializer xs = new XmlSerializer(AllStats.GetType());
         StreamReader  sr = new StreamReader(Path.Combine(Settings.Settings.StatsPath, "Statistics.xml"));
         AllStats = (Stats)xs.Deserialize(sr);
         sr.Close();
     }
     else if (Settings.Settings.Current.Stats != null)
     {
         AllStats     = new Stats();
         CurrentStats = new Stats
         {
             OperatingSystems =
                 new List <OsStats>
             {
                 new OsStats
                 {
                     name    = DetectOS.GetRealPlatformID().ToString(),
                     Value   = 1,
                     version = DetectOS.GetVersion()
                 }
             },
             Versions = new List <NameValueStats> {
                 new NameValueStats {
                     name = Version.GetVersion(), Value = 1
                 }
             }
         };
     }
     else
     {
         AllStats     = null;
         CurrentStats = null;
     }
 }
Exemple #7
0
        /// <summary>Sends an ATA command in 48-bit LBA format</summary>
        /// <returns>0 if no error occurred, otherwise, errno</returns>
        /// <param name="fd">File handle</param>
        /// <param name="buffer">Buffer for SCSI command response</param>
        /// <param name="timeout">Timeout in seconds</param>
        /// <param name="duration">Time it took to execute the command in milliseconds</param>
        /// <param name="sense"><c>True</c> if ATA returned non-OK status</param>
        /// <param name="registers">Registers to send to the device</param>
        /// <param name="errorRegisters">Registers returned by the device</param>
        /// <param name="protocol">ATA protocol to use</param>
        /// <param name="transferRegister">What register contains the transfer length</param>
        /// <param name="transferBlocks">Set to <c>true</c> if the transfer length is in block, otherwise it is in bytes</param>
        /// <exception cref="InvalidOperationException">If the specified platform is not supported</exception>
        internal static int SendAtaCommand(object fd, AtaRegistersLba48 registers,
                                           out AtaErrorRegistersLba48 errorRegisters, AtaProtocol protocol,
                                           AtaTransferRegister transferRegister, ref byte[] buffer, uint timeout,
                                           bool transferBlocks, out double duration, out bool sense)
        {
            PlatformID ptId = DetectOS.GetRealPlatformID();

            return(SendAtaCommand(ptId, fd, registers, out errorRegisters, protocol, transferRegister, ref buffer,
                                  timeout, transferBlocks, out duration, out sense));
        }
Exemple #8
0
        /// <summary>Sends a MMC/SD command</summary>
        /// <returns>The result of the command.</returns>
        /// <param name="fd">File handle</param>
        /// <param name="command">MMC/SD opcode</param>
        /// <param name="buffer">Buffer for MMC/SD command response</param>
        /// <param name="timeout">Timeout in seconds</param>
        /// <param name="duration">Time it took to execute the command in milliseconds</param>
        /// <param name="sense"><c>True</c> if MMC/SD returned non-OK status</param>
        /// <param name="write"><c>True</c> if data is sent from host to card</param>
        /// <param name="isApplication"><c>True</c> if command should be preceded with CMD55</param>
        /// <param name="flags">Flags indicating kind and place of response</param>
        /// <param name="blocks">How many blocks to transfer</param>
        /// <param name="argument">Command argument</param>
        /// <param name="response">Response registers</param>
        /// <param name="blockSize">Size of block in bytes</param>
        /// <exception cref="InvalidOperationException">If the specified platform is not supported</exception>
        internal static int SendMmcCommand(object fd, MmcCommands command, bool write, bool isApplication,
                                           MmcFlags flags, uint argument, uint blockSize, uint blocks,
                                           ref byte[] buffer, out uint[] response, out double duration, out bool sense,
                                           uint timeout = 0)
        {
            PlatformID ptId = DetectOS.GetRealPlatformID();

            return(SendMmcCommand(ptId, (int)fd, command, write, isApplication, flags, argument, blockSize, blocks,
                                  ref buffer, out response, out duration, out sense, timeout));
        }
Exemple #9
0
        public static string Print(int errno)
        {
            switch (DetectOS.GetRealPlatformID())
            {
            case PlatformID.Win32S:
            case PlatformID.Win32Windows:
            case PlatformID.Win32NT:
            case PlatformID.WinCE:
            case PlatformID.WindowsPhone:
            case PlatformID.Xbox: return(PrintWin32Error(errno));

            case PlatformID.Unix:
            case PlatformID.MacOSX:
            case PlatformID.iOS:
            case PlatformID.Linux:
            case PlatformID.Solaris:
            case PlatformID.NetBSD:
            case PlatformID.OpenBSD:
            case PlatformID.FreeBSD:
            case PlatformID.DragonFly:
            case PlatformID.Android:
            case PlatformID.Tizen:
            case PlatformID.Hurd:
            case PlatformID.Haiku:
            case PlatformID.HPUX:
            case PlatformID.AIX:
            case PlatformID.OS400:
            case PlatformID.IRIX:
            case PlatformID.Minix:
            case PlatformID.QNX:
            case PlatformID.SINIX:
            case PlatformID.Tru64:
            case PlatformID.Ultrix:
            case PlatformID.OpenServer:
            case PlatformID.UnixWare:
            case PlatformID.zOS: return(PrintUnixError(errno));

            case PlatformID.Wii:          return($"Unknown error code {errno}");

            case PlatformID.WiiU:         return($"Unknown error code {errno}");

            case PlatformID.PlayStation3: return($"Unknown error code {errno}");

            case PlatformID.PlayStation4: return($"Unknown error code {errno}");

            case PlatformID.NonStop:      return($"Unknown error code {errno}");

            case PlatformID.Unknown:      return($"Unknown error code {errno}");

            default:                      return($"Unknown error code {errno}");
            }

            throw new Exception("Arrived an unexpected place");
        }
Exemple #10
0
        public static DeviceInfo[] ListDevices(out bool isRemote, out string serverApplication,
                                               out string serverVersion, out string serverOperatingSystem,
                                               out string serverOperatingSystemVersion, out string serverArchitecture,
                                               string aaruRemote = null)
        {
            isRemote                     = false;
            serverApplication            = null;
            serverVersion                = null;
            serverOperatingSystem        = null;
            serverOperatingSystemVersion = null;
            serverArchitecture           = null;

            if (aaruRemote is null)
            {
                switch (DetectOS.GetRealPlatformID())
                {
                case PlatformID.Win32NT: return(Windows.ListDevices.GetList());

                case PlatformID.Linux:   return(Linux.ListDevices.GetList());

                case PlatformID.FreeBSD: return(FreeBSD.ListDevices.GetList());

                default:
                    throw new
                          InvalidOperationException($"Platform {DetectOS.GetRealPlatformID()} not yet supported.");
                }
            }

            try
            {
                if (aaruRemote.ToLowerInvariant().StartsWith("aaru://"))
                {
                    aaruRemote = aaruRemote.Substring(7);
                }

                using (var remote = new Remote.Remote(aaruRemote))
                {
                    isRemote                     = true;
                    serverApplication            = remote.ServerApplication;
                    serverVersion                = remote.ServerVersion;
                    serverOperatingSystem        = remote.ServerOperatingSystem;
                    serverOperatingSystemVersion = remote.ServerOperatingSystemVersion;
                    serverArchitecture           = remote.ServerArchitecture;

                    return(remote.ListDevices());
                }
            }
            catch (Exception)
            {
                AaruConsole.ErrorWriteLine("Error connecting to host.");

                return(new DeviceInfo[0]);
            }
        }
Exemple #11
0
        public static DeviceInfo[] ListDevices()
        {
            switch (DetectOS.GetRealPlatformID())
            {
            case PlatformID.Win32NT: return(Windows.ListDevices.GetList());

            case PlatformID.Linux: return(Linux.ListDevices.GetList());

            case PlatformID.FreeBSD: return(FreeBSD.ListDevices.GetList());

            default:
                throw new InvalidOperationException($"Platform {DetectOS.GetRealPlatformID()} not yet supported.");
            }
        }
Exemple #12
0
        public DumpMediaCommand() : base("dump-media", "Dumps the media inserted on a device to a media image.")
        {
            Options = new OptionSet
            {
                $"{MainClass.AssemblyTitle} {MainClass.AssemblyVersion?.InformationalVersion}",
                $"{MainClass.AssemblyCopyright}", "", $"usage: DiscImageChef {Name} [OPTIONS] devicepath outputimage",
                "", Help,
                {
                    "cicm-xml|x=", "Take metadata from existing CICM XML sidecar.", s => cicmXml = s
                },
                {
                    "encoding|e=", "Name of character encoding to use.", s => encodingName = s
                }
            };

            if (DetectOS.GetRealPlatformID() != PlatformID.FreeBSD)
            {
                Options.Add("first-pregap", "Try to read first track pregap. Only applicable to CD/DDCD/GD.",
                            b => firstTrackPregap = b != null);
            }

            Options.Add("force|f", "Continue dump whatever happens.", b => force = b != null);

            Options.Add("format|t=",
                        "Format of the output image, as plugin name or plugin id. If not present, will try to detect it from output image extension.",
                        s => wantedOutputFormat = s);

            Options.Add("no-metadata", "Disables creating CICM XML sidecar.", b => noMetadata     = b != null);
            Options.Add("no-trim", "Disables trimming errored from skipped sectors.", b => noTrim = b != null);

            Options.Add("options|O=", "Comma separated name=value pairs of options to pass to output image plugin.",
                        s => outputOptions = s);

            Options.Add("persistent", "Try to recover partial or incorrect data.", b => persistent = b != null);

            /* TODO: Disabled temporarily
             * Options.Add("raw|r", "Dump sectors with tags included. For optical media, dump scrambled sectors.", (b) => raw = b != null);*/
            Options.Add("resume|r", "Create/use resume mapfile.",
                        b => doResume = b != null);

            Options.Add("retry-passes|p=", "How many retry passes to do.", (ushort us) => retryPasses            = us);
            Options.Add("skip|k=", "When an unreadable sector is found skip this many sectors.", (int i) => skip = i);

            Options.Add("stop-on-error|s", "Stop media dump on first error.",
                        b => stopOnError = b != null);

            Options.Add("help|h|?", "Show this message and exit.",
                        v => showHelp = v != null);
        }
        public static TargetOS GetTargetOS(string os)
        {
            if (os.IsNullOrEmpty())
            {
                return(DetectOS.GetCurrentOS());
            }

            try
            {
                return(Enum.Parse <TargetOS>(os, true));
            }
            catch (Exception e)
            {
                throw new OperatingSystemNotFoundException(e.Message);
            }
        }
        public IActionResult GetOsData()
        {
            var query = ctx.OperatingSystems.GroupBy(x => new
            {
                x.Name
            }, x => x.Count).Select(g => new
            {
                g.Key.Name, Count = g.Sum()
            });

            string[][] result = new string[2][];
            result[0] = query.Select(x => x.Name).ToArray();
            result[1] = query.Select(x => x.Count.ToString()).ToArray();

            for (int i = 0; i < result[0].Length; i++)
            {
                result[0][i] = DetectOS.GetPlatformName((PlatformID)Enum.Parse(typeof(PlatformID), result[0][i]));
            }

            return(Json(result));
        }
Exemple #15
0
        public static void SaveSettings()
        {
            try
            {
                PlatformID ptId = DetectOS.GetRealPlatformID();

                switch (ptId)
                {
                // In case of macOS or iOS settings will be saved in ~/Library/Preferences/com.claunia.discimagechef.plist
                case PlatformID.MacOSX:
                case PlatformID.iOS:
                {
                    NSDictionary root = new NSDictionary
                    {
                        { "SaveReportsGlobally", Current.SaveReportsGlobally },
                        { "ShareReports", Current.ShareReports },
                        { "GdprCompliance", Current.GdprCompliance }
                    };
                    if (Current.Stats != null)
                    {
                        NSDictionary stats = new NSDictionary
                        {
                            { "ShareStats", Current.Stats.ShareStats },
                            { "BenchmarkStats", Current.Stats.BenchmarkStats },
                            { "CommandStats", Current.Stats.CommandStats },
                            { "DeviceStats", Current.Stats.DeviceStats },
                            { "FilesystemStats", Current.Stats.FilesystemStats },
                            { "FilterStats", Current.Stats.FilterStats },
                            { "MediaImageStats", Current.Stats.MediaImageStats },
                            { "MediaScanStats", Current.Stats.MediaScanStats },
                            { "PartitionStats", Current.Stats.PartitionStats },
                            { "MediaStats", Current.Stats.MediaStats },
                            { "VerifyStats", Current.Stats.VerifyStats }
                        };
                        root.Add("Stats", stats);
                    }

                    string preferencesPath =
                        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library",
                                     "Preferences");
                    string preferencesFilePath = Path.Combine(preferencesPath, "com.claunia.discimagechef.plist");

                    FileStream fs = new FileStream(preferencesFilePath, FileMode.Create);
                    BinaryPropertyListWriter.Write(fs, root);
                    fs.Close();
                }
                break;

#if !NETSTANDARD2_0
                // In case of Windows settings will be saved in the registry: HKLM/SOFTWARE/Claunia.com/DiscImageChef
                case PlatformID.Win32NT:
                case PlatformID.Win32S:
                case PlatformID.Win32Windows:
                case PlatformID.WinCE:
                case PlatformID.WindowsPhone:
                {
                    RegistryKey parentKey =
                        Registry.CurrentUser.OpenSubKey("SOFTWARE", true)?.CreateSubKey("Claunia.com");
                    RegistryKey key = parentKey?.CreateSubKey("DiscImageChef");

                    if (key != null)
                    {
                        key.SetValue("SaveReportsGlobally", Current.SaveReportsGlobally);
                        key.SetValue("ShareReports", Current.ShareReports);
                        key.SetValue("GdprCompliance", Current.GdprCompliance);

                        if (Current.Stats != null)
                        {
                            key.SetValue("Statistics", true);
                            key.SetValue("ShareStats", Current.Stats.ShareStats);
                            key.SetValue("BenchmarkStats", Current.Stats.BenchmarkStats);
                            key.SetValue("CommandStats", Current.Stats.CommandStats);
                            key.SetValue("DeviceStats", Current.Stats.DeviceStats);
                            key.SetValue("FilesystemStats", Current.Stats.FilesystemStats);
                            key.SetValue("FilterStats", Current.Stats.FilterStats);
                            key.SetValue("MediaImageStats", Current.Stats.MediaImageStats);
                            key.SetValue("MediaScanStats", Current.Stats.MediaScanStats);
                            key.SetValue("PartitionStats", Current.Stats.PartitionStats);
                            key.SetValue("MediaStats", Current.Stats.MediaStats);
                            key.SetValue("VerifyStats", Current.Stats.VerifyStats);
                        }
                        else
                        {
                            key.SetValue("Statistics", true);
                            key.DeleteValue("ShareStats", false);
                            key.DeleteValue("BenchmarkStats", false);
                            key.DeleteValue("CommandStats", false);
                            key.DeleteValue("DeviceStats", false);
                            key.DeleteValue("FilesystemStats", false);
                            key.DeleteValue("MediaImageStats", false);
                            key.DeleteValue("MediaScanStats", false);
                            key.DeleteValue("PartitionStats", false);
                            key.DeleteValue("MediaStats", false);
                            key.DeleteValue("VerifyStats", false);
                        }
                    }
                }
                break;
#endif
                // Otherwise, settings will be saved in ~/.config/DiscImageChef.xml
                default:
                {
                    string homePath      = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
                    string xdgConfigPath =
                        Path.Combine(homePath,
                                     Environment.GetEnvironmentVariable(XDG_CONFIG_HOME) ??
                                     XDG_CONFIG_HOME_RESOLVED);
                    string settingsPath = Path.Combine(xdgConfigPath, "DiscImageChef.xml");

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

                    FileStream    fs = new FileStream(settingsPath, FileMode.Create);
                    XmlSerializer xs = new XmlSerializer(Current.GetType());
                    xs.Serialize(fs, Current);
                    fs.Close();
                }
                break;
                }
            }
            #pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body
            catch
            {
                // ignored
            }
            #pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body
        }
Exemple #16
0
        public Remote(string host)
        {
            _host = host;
            IPHostEntry ipHostEntry = Dns.GetHostEntry(host);

            IPAddress ipAddress =
                ipHostEntry.AddressList.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);

            if (ipAddress is null)
            {
                AaruConsole.ErrorWriteLine("Host not found");

                throw new SocketException(11001);
            }

            var ipEndPoint = new IPEndPoint(ipAddress, 6666);

            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            _socket.Connect(ipEndPoint);

            AaruConsole.WriteLine("Connected to {0}", host);

            byte[] hdrBuf = new byte[Marshal.SizeOf <AaruPacketHeader>()];

            int len = Receive(_socket, hdrBuf, hdrBuf.Length, SocketFlags.Peek);

            if (len < hdrBuf.Length)
            {
                AaruConsole.ErrorWriteLine("Could not read from the network...");

                throw new IOException();
            }

            AaruPacketHeader hdr = Marshal.ByteArrayToStructureLittleEndian <AaruPacketHeader>(hdrBuf);

            if (hdr.remote_id != Consts.RemoteId ||
                hdr.packet_id != Consts.PacketId)
            {
                AaruConsole.ErrorWriteLine("Received data is not an Aaru Remote Packet...");

                throw new ArgumentException();
            }

            byte[] buf;

            if (hdr.packetType != AaruPacketType.Hello)
            {
                if (hdr.packetType != AaruPacketType.Nop)
                {
                    AaruConsole.ErrorWriteLine("Expected Hello Packet, got packet type {0}...", hdr.packetType);

                    throw new ArgumentException();
                }

                buf = new byte[hdr.len];
                len = Receive(_socket, buf, buf.Length, SocketFlags.None);

                if (len < buf.Length)
                {
                    AaruConsole.ErrorWriteLine("Could not read from the network...");

                    throw new IOException();
                }

                AaruPacketNop nop = Marshal.ByteArrayToStructureLittleEndian <AaruPacketNop>(buf);

                AaruConsole.ErrorWriteLine($"{nop.reason}");

                throw new ArgumentException();
            }

            if (hdr.version != Consts.PacketVersion)
            {
                AaruConsole.ErrorWriteLine("Unrecognized packet version...");

                throw new ArgumentException();
            }

            buf = new byte[hdr.len];
            len = Receive(_socket, buf, buf.Length, SocketFlags.None);

            if (len < buf.Length)
            {
                AaruConsole.ErrorWriteLine("Could not read from the network...");

                throw new IOException();
            }

            AaruPacketHello serverHello = Marshal.ByteArrayToStructureLittleEndian <AaruPacketHello>(buf);

            ServerApplication            = serverHello.application;
            ServerVersion                = serverHello.version;
            ServerOperatingSystem        = serverHello.sysname;
            ServerOperatingSystemVersion = serverHello.release;
            ServerArchitecture           = serverHello.machine;
            ServerProtocolVersion        = serverHello.maxProtocol;

            var clientHello = new AaruPacketHello
            {
                application = "Aaru", version = Version.GetVersion(), maxProtocol = Consts.MaxProtocol,
                sysname     = DetectOS.GetPlatformName(DetectOS.GetRealPlatformID(), DetectOS.GetVersion()),
                release     = DetectOS.GetVersion(), machine = RuntimeInformation.ProcessArchitecture.ToString(), hdr =
                    new AaruPacketHeader
                {
                    remote_id  = Consts.RemoteId, packet_id = Consts.PacketId,
                    len        = (uint)Marshal.SizeOf <AaruPacketHello>(), version = Consts.PacketVersion,
                    packetType = AaruPacketType.Hello
                }
            };

            buf = Marshal.StructureToByteArrayLittleEndian(clientHello);

            len = _socket.Send(buf, SocketFlags.None);

            if (len >= buf.Length)
            {
                return;
            }

            AaruConsole.ErrorWriteLine("Could not write to the network...");

            throw new IOException();
        }
Exemple #17
0
        public static void Main(string[] args)
        {
            Console.Clear();

            Console.Write(
                "\u001b[32m                             .                ,,\n" +
                "\u001b[32m                          ;,.                  '0d.\n" +
                "\u001b[32m                        oc                       oWd                      \u001b[31m" +
                @"________/\\\\\\\\\___/\\\\\\\\\\\_________/\\\\\\\\\___/\\\\____________/\\\\_" +
                "\n\u001b[0m" +
                "\u001b[32m                      ;X.                         'WN'                    \u001b[31m" +
                @" _____/\\\////////___\/////\\\///_______/\\\////////___\/\\\\\\________/\\\\\\_" +
                "\n\u001b[0m" +
                "\u001b[32m                     oMo                           cMM:                   \u001b[31m" +
                @"  ___/\\\/________________\/\\\________/\\\/____________\/\\\//\\\____/\\\//\\\_" +
                "\n\u001b[0m" +
                "\u001b[32m                    ;MM.                           .MMM;                  \u001b[31m" +
                @"   __/\\\__________________\/\\\_______/\\\______________\/\\\\///\\\/\\\/_\/\\\_" +
                "\n\u001b[0m" +
                "\u001b[32m                    NMM                             WMMW                  \u001b[31m" +
                @"    _\/\\\__________________\/\\\______\/\\\______________\/\\\__\///\\\/___\/\\\_" +
                "\n\u001b[0m" +
                "\u001b[32m                   'MMM                             MMMM;                 \u001b[31m" +
                @"     _\//\\\_________________\/\\\______\//\\\_____________\/\\\____\///_____\/\\\_" +
                "\n\u001b[0m" +
                "\u001b[32m                   ,MMM:                           dMMMM:                 \u001b[31m" +
                @"      __\///\\\_______________\/\\\_______\///\\\___________\/\\\_____________\/\\\_" +
                "\n\u001b[0m" +
                "\u001b[32m                   .MMMW.                         :MMMMM.                 \u001b[31m" +
                @"       ____\////\\\\\\\\\___/\\\\\\\\\\\_____\////\\\\\\\\\__\/\\\_____________\/\\\_" +
                "\n\u001b[0m" +
                "\u001b[32m                    XMMMW:    .:xKNMMMMMMN0d,    lMMMMMd                  \u001b[31m" +
                @"        _______\/////////___\///////////_________\/////////___\///______________\///__" +
                "\n\u001b[0m" +
                "\u001b[32m                    :MMMMMK; cWMNkl:;;;:lxKMXc .0MMMMMO                   \u001b[37;1m          MARECHAI\u001b[0m\n" +
                "\u001b[32m                   ..KMMMMMMNo,.             ,OMMMMMMW:,.                 \u001b[37;1m          Master repository of computing history artifacts information\u001b[0m\n" +
                "\u001b[32m            .;d0NMMMMMMMMMMMMMMW0d:'    .;lOWMMMMMMMMMMMMMXkl.            \u001b[37;1m          Version \u001b[0m\u001b[33m{0}\u001b[37;1m-\u001b[0m\u001b[31m{1}\u001b[0m\n" +
                "\u001b[32m          :KMMMMMMMMMMMMMMMMMMMMMMMMc  WMMMMMMMMMMMMMMMMMMMMMMWk'\u001b[0m\n" +
                "\u001b[32m        ;NMMMMWX0kkkkO0XMMMMMMMMMMM0'  dNMMMMMMMMMMW0xl:;,;:oOWMMX;       \u001b[37;1m          Running under \u001b[35;1m{2}\u001b[37;1m, \u001b[35m{3}-bit\u001b[37;1m in \u001b[35m{4}-bit\u001b[37;1m mode.\u001b[0m\n" +
                "\u001b[32m       xMMWk:.           .c0MMMMMW'      OMMMMMM0c'..          .oNMO      \u001b[37;1m          Using \u001b[33;1m{5}\u001b[37;1m version \u001b[31;1m{6}\u001b[0m\n" +
                "\u001b[32m      OMNc            .MNc   oWMMk       'WMMNl. .MMK             ;KX.\u001b[0m\n" +
                "\u001b[32m     xMO               WMN     ;  .,    ,  ':    ,MMx               lK\u001b[0m\n" +
                "\u001b[32m    ,Md                cMMl     .XMMMWWMMMO      XMW.                :\u001b[0m\n" +
                "\u001b[32m    Ok                  xMMl     XMMMMMMMMc     0MW,\u001b[0m\n" +
                "\u001b[32m    0                    oMM0'   lMMMMMMMM.   :NMN'\u001b[0m\n" +
                "\u001b[32m    .                     .0MMKl ;MMMMMMMM  oNMWd\u001b[0m\n" +
                "\u001b[32m                            .dNW cMMMMMMMM, XKl\u001b[0m\n" +
                "\u001b[32m                                 0MMMMMMMMK\u001b[0m\n" +
                "\u001b[32m                                ;MMMMMMMMMMO                              \u001b[37;1m          Proudly presented to you by:\u001b[0m\n" +
                "\u001b[32m                               'WMMMMKxMMMMM0                             \u001b[34;1m          Natalia Portillo\u001b[0m\n" +
                "\u001b[32m                              oMMMMNc  :WMMMMN:\u001b[0m\n" +
                "\u001b[32m                           .dWMMM0;      dWMMMMXl.                        \u001b[37;1m          Thanks to all contributors, collaborators, translators, donators and friends.\u001b[0m\n" +
                "\u001b[32m               .......,cd0WMMNk:           c0MMMMMWKkolc:clodc'\u001b[0m\n" +
                "\u001b[32m                 .';loddol:'.                 ':oxkkOkkxoc,.\u001b[0m\n" +
                "\u001b[0m\n", Version.GetVersion(),
                      #if DEBUG
                "DEBUG"
                      #else
                "RELEASE"
                      #endif
                , DetectOS.GetPlatformName(DetectOS.GetRealPlatformID()),
                Environment.Is64BitOperatingSystem ? 64 : 32, Environment.Is64BitProcess ? 64 : 32,
                DetectOS.IsMono ? "Mono" : ".NET Core",
                DetectOS.IsMono ? Version.GetMonoVersion() : Version.GetNetCoreVersion());

            Console.WriteLine("\u001b[31;1mUpdating MySQL database without Entity Framework if it exists...\u001b[0m");
            Database = new Mysql();

            IConfigurationBuilder builder       = new ConfigurationBuilder().AddJsonFile("appsettings.json");
            IConfigurationRoot    configuration = builder.Build();
            string connectionString             = configuration.GetConnectionString("DefaultConnection");

            if (connectionString is null)
            {
                Console.WriteLine("\u001b[31;1mCould not find a correct connection string...\u001b[0m");
            }
            else
            {
                string   server = null, user = null, database = null, password = null;
                ushort   port   = 0;
                string[] pieces = connectionString.Split(";");

                foreach (string piece in pieces)
                {
                    if (piece.StartsWith("server=", StringComparison.Ordinal))
                    {
                        server = piece.Substring(7);
                    }
                    else if (piece.StartsWith("user="******"password="******"database=", StringComparison.Ordinal))
                    {
                        database = piece.Substring(9);
                    }
                    else if (piece.StartsWith("port=", StringComparison.Ordinal))
                    {
                        string portString = piece.Substring(5);

                        ushort.TryParse(portString, out port);
                    }
                }

                if (server is null ||
                    user is null ||
                    database is null ||
                    password is null ||
                    port == 0)
                {
                    Console.WriteLine("\u001b[31;1mCould not find a correct connection string...\u001b[0m");
                }
Exemple #18
0
        /// <summary>Initializes the dump log</summary>
        /// <param name="outputFile">Output log file</param>
        /// <param name="dev">Device</param>
        /// <param name="private">Disable saving paths or serial numbers in log</param>
        public DumpLog(string outputFile, Device dev, bool @private)
        {
            if (string.IsNullOrEmpty(outputFile))
            {
                return;
            }

            _logSw = new StreamWriter(outputFile, true);

            _logSw.WriteLine("Start logging at {0}", DateTime.Now);

            PlatformID platId  = DetectOS.GetRealPlatformID();
            string     platVer = DetectOS.GetVersion();

            var assemblyVersion =
                Attribute.GetCustomAttribute(typeof(DumpLog).Assembly, typeof(AssemblyInformationalVersionAttribute)) as
                AssemblyInformationalVersionAttribute;

            _logSw.WriteLine("################# System information #################");

            _logSw.WriteLine("{0} {1} ({2}-bit)", DetectOS.GetPlatformName(platId, platVer), platVer,
                             Environment.Is64BitOperatingSystem ? 64 : 32);

            if (DetectOS.IsMono)
            {
                _logSw.WriteLine("Mono {0}", Version.GetMonoVersion());
            }
            else if (DetectOS.IsNetCore)
            {
                _logSw.WriteLine(".NET Core {0}", Version.GetNetCoreVersion());
            }
            else
            {
                _logSw.WriteLine(RuntimeInformation.FrameworkDescription);
            }

            _logSw.WriteLine();

            _logSw.WriteLine("################# Program information ################");
            _logSw.WriteLine("Aaru {0}", assemblyVersion?.InformationalVersion);
            _logSw.WriteLine("Running in {0}-bit", Environment.Is64BitProcess ? 64 : 32);
            _logSw.WriteLine("Running as superuser: {0}", DetectOS.IsAdmin ? "Yes" : "No");
        #if DEBUG
            _logSw.WriteLine("DEBUG version");
        #endif
            if (@private)
            {
                string[] args = Environment.GetCommandLineArgs();

                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i].StartsWith("/dev", StringComparison.OrdinalIgnoreCase) ||
                        args[i].StartsWith("aaru://", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    try
                    {
                        args[i] = Path.GetFileName(args[i]);
                    }
                    catch
                    {
                        // Do nothing
                    }
                }

                _logSw.WriteLine("Command line: {0}", string.Join(" ", args));
            }
            else
            {
                _logSw.WriteLine("Command line: {0}", Environment.CommandLine);
            }

            _logSw.WriteLine();

            if (dev.IsRemote)
            {
                _logSw.WriteLine("################# Remote information #################");
                _logSw.WriteLine("Server: {0}", dev.RemoteApplication);
                _logSw.WriteLine("Version: {0}", dev.RemoteVersion);

                _logSw.WriteLine("Operating system: {0} {1}", dev.RemoteOperatingSystem,
                                 dev.RemoteOperatingSystemVersion);

                _logSw.WriteLine("Architecture: {0}", dev.RemoteArchitecture);
                _logSw.WriteLine("Protocol version: {0}", dev.RemoteProtocolVersion);
                _logSw.WriteLine("Running as superuser: {0}", dev.IsRemoteAdmin ? "Yes" : "No");
                _logSw.WriteLine("######################################################");
            }

            _logSw.WriteLine("################# Device information #################");
            _logSw.WriteLine("Manufacturer: {0}", dev.Manufacturer);
            _logSw.WriteLine("Model: {0}", dev.Model);
            _logSw.WriteLine("Firmware revision: {0}", dev.FirmwareRevision);

            if (!@private)
            {
                _logSw.WriteLine("Serial number: {0}", dev.Serial);
            }

            _logSw.WriteLine("Removable device: {0}", dev.IsRemovable);
            _logSw.WriteLine("Device type: {0}", dev.Type);
            _logSw.WriteLine("CompactFlash device: {0}", dev.IsCompactFlash);
            _logSw.WriteLine("PCMCIA device: {0}", dev.IsPcmcia);
            _logSw.WriteLine("USB device: {0}", dev.IsUsb);

            if (dev.IsUsb)
            {
                _logSw.WriteLine("USB manufacturer: {0}", dev.UsbManufacturerString);
                _logSw.WriteLine("USB product: {0}", dev.UsbProductString);

                if (!@private)
                {
                    _logSw.WriteLine("USB serial: {0}", dev.UsbSerialString);
                }

                _logSw.WriteLine("USB vendor ID: {0:X4}h", dev.UsbVendorId);
                _logSw.WriteLine("USB product ID: {0:X4}h", dev.UsbProductId);
            }

            _logSw.WriteLine("FireWire device: {0}", dev.IsFireWire);

            if (dev.IsFireWire)
            {
                _logSw.WriteLine("FireWire vendor: {0}", dev.FireWireVendorName);
                _logSw.WriteLine("FireWire model: {0}", dev.FireWireModelName);

                if (!@private)
                {
                    _logSw.WriteLine("FireWire GUID: 0x{0:X16}", dev.FireWireGuid);
                }

                _logSw.WriteLine("FireWire vendor ID: 0x{0:X8}", dev.FireWireVendor);
                _logSw.WriteLine("FireWire product ID: 0x{0:X8}", dev.FireWireModel);
            }

            _logSw.WriteLine("######################################################");

            _logSw.WriteLine();
            _logSw.WriteLine("################ Dumping progress log ################");
            _logSw.Flush();
        }
Exemple #19
0
        public MainWindowViewModel(MainWindow view)
        {
            AboutCommand                = ReactiveCommand.Create(ExecuteAboutCommand);
            EncodingsCommand            = ReactiveCommand.Create(ExecuteEncodingsCommand);
            PluginsCommand              = ReactiveCommand.Create(ExecutePluginsCommand);
            StatisticsCommand           = ReactiveCommand.Create(ExecuteStatisticsCommand);
            ExitCommand                 = ReactiveCommand.Create(ExecuteExitCommand);
            SettingsCommand             = ReactiveCommand.Create(ExecuteSettingsCommand);
            ConsoleCommand              = ReactiveCommand.Create(ExecuteConsoleCommand);
            OpenCommand                 = ReactiveCommand.Create(ExecuteOpenCommand);
            CalculateEntropyCommand     = ReactiveCommand.Create(ExecuteCalculateEntropyCommand);
            VerifyImageCommand          = ReactiveCommand.Create(ExecuteVerifyImageCommand);
            ChecksumImageCommand        = ReactiveCommand.Create(ExecuteChecksumImageCommand);
            ConvertImageCommand         = ReactiveCommand.Create(ExecuteConvertImageCommand);
            CreateSidecarCommand        = ReactiveCommand.Create(ExecuteCreateSidecarCommand);
            ViewImageSectorsCommand     = ReactiveCommand.Create(ExecuteViewImageSectorsCommand);
            DecodeImageMediaTagsCommand = ReactiveCommand.Create(ExecuteDecodeImageMediaTagsCommand);
            RefreshDevicesCommand       = ReactiveCommand.Create(ExecuteRefreshDevicesCommand);
            _view        = view;
            TreeRoot     = new ObservableCollection <RootModel>();
            _assets      = AvaloniaLocator.Current.GetService <IAssetLoader>();
            ContentPanel = Greeting;

            _imagesRoot = new ImagesRootModel
            {
                Name = "Images"
            };

            TreeRoot.Add(_imagesRoot);

            switch (DetectOS.GetRealPlatformID())
            {
            case PlatformID.Win32NT:
            case PlatformID.Linux:
            case PlatformID.FreeBSD:
                _devicesRoot = new DevicesRootModel
                {
                    Name = "Devices"
                };

                TreeRoot.Add(_devicesRoot);
                DevicesSupported = true;

                break;
            }

            _genericHddIcon =
                new Bitmap(_assets.Open(new Uri("avares://Aaru.Gui/Assets/Icons/oxygen/32x32/drive-harddisk.png")));

            _genericOpticalIcon =
                new Bitmap(_assets.Open(new Uri("avares://Aaru.Gui/Assets/Icons/oxygen/32x32/drive-optical.png")));

            _genericTapeIcon =
                new Bitmap(_assets.Open(new Uri("avares://Aaru.Gui/Assets/Icons/oxygen/32x32/media-tape.png")));

            _genericFolderIcon =
                new Bitmap(_assets.Open(new Uri("avares://Aaru.Gui/Assets/Icons/oxygen/32x32/inode-directory.png")));

            _usbIcon =
                new
                Bitmap(_assets.Open(new
                                    Uri("avares://Aaru.Gui/Assets/Icons/oxygen/32x32/drive-removable-media-usb.png")));

            _removableIcon =
                new
                Bitmap(_assets.Open(new Uri("avares://Aaru.Gui/Assets/Icons/oxygen/32x32/drive-removable-media.png")));

            _sdIcon =
                new Bitmap(_assets.Open(new Uri("avares://Aaru.Gui/Assets/Icons/oxygen/32x32/media-flash-sd-mmc.png")));

            _ejectIcon =
                new Bitmap(_assets.Open(new Uri("avares://Aaru.Gui/Assets/Icons/oxygen/32x32/media-eject.png")));
        }
    public ActionResult Index()
    {
        ViewBag.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

        try
        {
            if (System.IO.File.Exists(Path.Combine(_env.ContentRootPath ?? throw new InvalidOperationException(),
                                                   "Statistics", "Statistics.xml")))
            {
                try
                {
                    var statistics = new Stats();

                    var xs = new XmlSerializer(statistics.GetType());

                    FileStream fs =
                        WaitForFile(Path.Combine(_env.ContentRootPath ?? throw new InvalidOperationException(), "Statistics", "Statistics.xml"),
                                    FileMode.Open, FileAccess.Read, FileShare.Read);

                    statistics = (Stats)xs.Deserialize(fs);
                    fs.Close();

                    StatsConverter.Convert(statistics);

                    System.IO.File.Delete(Path.Combine(_env.ContentRootPath ?? throw new InvalidOperationException(),
                                                       "Statistics", "Statistics.xml"));
                }
                catch (XmlException)
                {
                    // Do nothing
                }
            }

            if (_ctx.OperatingSystems.Any())
            {
                List <NameValueStats> operatingSystems = new();

                foreach (OperatingSystem nvs in _ctx.OperatingSystems)
                {
                    operatingSystems.Add(new NameValueStats
                    {
                        name =
                            $"{DetectOS.GetPlatformName((PlatformID)Enum.Parse(typeof(PlatformID), nvs.Name), nvs.Version)}{(string.IsNullOrEmpty(nvs.Version) ? "" : " ")}{nvs.Version}",
                        Value = nvs.Count
                    });
                }

                ViewBag.repOperatingSystems = operatingSystems.OrderBy(os => os.name).ToList();
            }

            if (_ctx.Versions.Any())
            {
                List <NameValueStats> versions = new();

                foreach (Version nvs in _ctx.Versions)
                {
                    versions.Add(new NameValueStats
                    {
                        name  = nvs.Name == "previous" ? "Previous than 3.4.99.0" : nvs.Name,
                        Value = nvs.Count
                    });
                }

                ViewBag.repVersions = versions.OrderBy(ver => ver.name).ToList();
            }

            if (_ctx.Commands.Any())
            {
                ViewBag.repCommands = _ctx.Commands.OrderBy(c => c.Name).ToList();
            }

            if (_ctx.Filters.Any())
            {
                ViewBag.repFilters = _ctx.Filters.OrderBy(filter => filter.Name).ToList();
            }

            if (_ctx.MediaFormats.Any())
            {
                ViewBag.repMediaImages = _ctx.MediaFormats.OrderBy(filter => filter.Name).ToList();
            }

            if (_ctx.Partitions.Any())
            {
                ViewBag.repPartitions = _ctx.Partitions.OrderBy(filter => filter.Name).ToList();
            }

            if (_ctx.Filesystems.Any())
            {
                ViewBag.repFilesystems = _ctx.Filesystems.OrderBy(filter => filter.Name).ToList();
            }

            if (_ctx.Medias.Any())
            {
                List <MediaItem> realMedia    = new();
                List <MediaItem> virtualMedia = new();

                foreach (Media nvs in _ctx.Medias)
                {
                    try
                    {
                        (string type, string subType)mediaType =
                            MediaType.MediaTypeToString((CommonTypes.MediaType)Enum.Parse(typeof(CommonTypes.MediaType),
                                                                                          nvs.Type));

                        if (nvs.Real)
                        {
                            realMedia.Add(new MediaItem
                            {
                                Type    = mediaType.type,
                                SubType = mediaType.subType,
                                Count   = nvs.Count
                            });
                        }
                        else
                        {
                            virtualMedia.Add(new MediaItem
                            {
                                Type    = mediaType.type,
                                SubType = mediaType.subType,
                                Count   = nvs.Count
                            });
                        }
                    }
                    catch
                    {
                        if (nvs.Real)
                        {
                            realMedia.Add(new MediaItem
                            {
                                Type    = nvs.Type,
                                SubType = null,
                                Count   = nvs.Count
                            });
                        }
                        else
                        {
                            virtualMedia.Add(new MediaItem
                            {
                                Type    = nvs.Type,
                                SubType = null,
                                Count   = nvs.Count
                            });
                        }
                    }
                }

                if (realMedia.Count > 0)
                {
                    ViewBag.repRealMedia = realMedia.OrderBy(media => media.Type).ThenBy(media => media.SubType).
                                           ToList();
                }

                if (virtualMedia.Count > 0)
                {
                    ViewBag.repVirtualMedia = virtualMedia.OrderBy(media => media.Type).ThenBy(media => media.SubType).
                                              ToList();
                }
            }

            if (_ctx.DeviceStats.Any())
            {
                List <DeviceItem> devices = new();

                foreach (DeviceStat device in _ctx.DeviceStats.ToList())
                {
                    string xmlFile;

                    if (!string.IsNullOrWhiteSpace(device.Manufacturer) &&
                        !string.IsNullOrWhiteSpace(device.Model) &&
                        !string.IsNullOrWhiteSpace(device.Revision))
                    {
                        xmlFile = device.Manufacturer + "_" + device.Model + "_" + device.Revision + ".xml";
                    }
                    else if (!string.IsNullOrWhiteSpace(device.Manufacturer) &&
                             !string.IsNullOrWhiteSpace(device.Model))
                    {
                        xmlFile = device.Manufacturer + "_" + device.Model + ".xml";
                    }
                    else if (!string.IsNullOrWhiteSpace(device.Model) &&
                             !string.IsNullOrWhiteSpace(device.Revision))
                    {
                        xmlFile = device.Model + "_" + device.Revision + ".xml";
                    }
                    else
                    {
                        xmlFile = device.Model + ".xml";
                    }

                    xmlFile = xmlFile.Replace('/', '_').Replace('\\', '_').Replace('?', '_');

                    if (System.IO.File.Exists(Path.Combine(_env.ContentRootPath, "Reports", xmlFile)))
                    {
                        var deviceReport = new DeviceReport();

                        var xs = new XmlSerializer(deviceReport.GetType());

                        FileStream fs =
                            WaitForFile(Path.Combine(_env.ContentRootPath ?? throw new InvalidOperationException(), "Reports", xmlFile),
                                        FileMode.Open, FileAccess.Read, FileShare.Read);

                        deviceReport = (DeviceReport)xs.Deserialize(fs);
                        fs.Close();

                        var deviceReportV2 = new DeviceReportV2(deviceReport);

                        device.Report = _ctx.Devices.Add(new Device(deviceReportV2)).Entity;
                        _ctx.SaveChanges();

                        System.IO.File.
                        Delete(Path.Combine(_env.ContentRootPath ?? throw new InvalidOperationException(),
                                            "Reports", xmlFile));
                    }

                    devices.Add(new DeviceItem
                    {
                        Manufacturer = device.Manufacturer,
                        Model        = device.Model,
                        Revision     = device.Revision,
                        Bus          = device.Bus,
                        ReportId     = device.Report != null && device.Report.Id != 0 ? device.Report.Id : 0
                    });
                }

                ViewBag.repDevices = devices.OrderBy(device => device.Manufacturer).ThenBy(device => device.Model).
                                     ThenBy(device => device.Revision).ThenBy(device => device.Bus).ToList();
            }
        }
        catch (Exception)
        {
        #if DEBUG
            throw;
        #endif
            return(Content("Could not read statistics"));
        }

        return(View());
    }
        public static void Main(string[] args)
        {
            DateTime start;
            DateTime end;

            System.Console.Clear();

            System.Console.Write(
                "\u001b[32m                             .                ,,\n" +
                "\u001b[32m                          ;,.                  '0d.\n" +
                "\u001b[32m                        oc                       oWd                      \u001b[31m" +
                @"__/\\\\\\\\\\\\_____/\\\\\\\\\\\________/\\\\\\\\\_        " +
                "\n\u001b[0m" +
                "\u001b[32m                      ;X.                         'WN'                    \u001b[31m" +
                @" _\/\\\////////\\\__\/////\\\///______/\\\////////__       " +
                "\n\u001b[0m" +
                "\u001b[32m                     oMo                           cMM:                   \u001b[31m" +
                @"  _\/\\\______\//\\\_____\/\\\_______/\\\/___________      " +
                "\n\u001b[0m" +
                "\u001b[32m                    ;MM.                           .MMM;                  \u001b[31m" +
                @"   _\/\\\_______\/\\\_____\/\\\______/\\\_____________     " +
                "\n\u001b[0m" +
                "\u001b[32m                    NMM                             WMMW                  \u001b[31m" +
                @"    _\/\\\_______\/\\\_____\/\\\_____\/\\\_____________    " +
                "\n\u001b[0m" +
                "\u001b[32m                   'MMM                             MMMM;                 \u001b[31m" +
                @"     _\/\\\_______\/\\\_____\/\\\_____\//\\\____________   " +
                "\n\u001b[0m" +
                "\u001b[32m                   ,MMM:                           dMMMM:                 \u001b[31m" +
                @"      _\/\\\_______/\\\______\/\\\______\///\\\__________  " +
                "\n\u001b[0m" +
                "\u001b[32m                   .MMMW.                         :MMMMM.                 \u001b[31m" +
                @"       _\/\\\\\\\\\\\\/____/\\\\\\\\\\\____\////\\\\\\\\\_ " +
                "\n\u001b[0m" +
                "\u001b[32m                    XMMMW:    .:xKNMMMMMMN0d,    lMMMMMd                  \u001b[31m" +
                @"        _\////////////_____\///////////________\/////////__" +
                "\n\u001b[0m" +
                "\u001b[32m                    :MMMMMK; cWMNkl:;;;:lxKMXc .0MMMMMO\u001b[0m\n" +
                "\u001b[32m                   ..KMMMMMMNo,.             ,OMMMMMMW:,.                 \u001b[37;1m          DiscImageChef Website\u001b[0m\n" +
                "\u001b[32m            .;d0NMMMMMMMMMMMMMMW0d:'    .;lOWMMMMMMMMMMMMMXkl.            \u001b[37;1m          Version \u001b[0m\u001b[33m{0}\u001b[37;1m-\u001b[0m\u001b[31m{1}\u001b[0m\n" +
                "\u001b[32m          :KMMMMMMMMMMMMMMMMMMMMMMMMc  WMMMMMMMMMMMMMMMMMMMMMMWk'\u001b[0m\n" +
                "\u001b[32m        ;NMMMMWX0kkkkO0XMMMMMMMMMMM0'  dNMMMMMMMMMMW0xl:;,;:oOWMMX;       \u001b[37;1m          Running under \u001b[35;1m{2}\u001b[37;1m, \u001b[35m{3}-bit\u001b[37;1m in \u001b[35m{4}-bit\u001b[37;1m mode.\u001b[0m\n" +
                "\u001b[32m       xMMWk:.           .c0MMMMMW'      OMMMMMM0c'..          .oNMO      \u001b[37;1m          Using \u001b[33;1m{5}\u001b[37;1m version \u001b[31;1m{6}\u001b[0m\n" +
                "\u001b[32m      OMNc            .MNc   oWMMk       'WMMNl. .MMK             ;KX.\u001b[0m\n" +
                "\u001b[32m     xMO               WMN     ;  .,    ,  ':    ,MMx               lK\u001b[0m\n" +
                "\u001b[32m    ,Md                cMMl     .XMMMWWMMMO      XMW.                :\u001b[0m\n" +
                "\u001b[32m    Ok                  xMMl     XMMMMMMMMc     0MW,\u001b[0m\n" +
                "\u001b[32m    0                    oMM0'   lMMMMMMMM.   :NMN'\u001b[0m\n" +
                "\u001b[32m    .                     .0MMKl ;MMMMMMMM  oNMWd\u001b[0m\n" +
                "\u001b[32m                            .dNW cMMMMMMMM, XKl\u001b[0m\n" +
                "\u001b[32m                                 0MMMMMMMMK\u001b[0m\n" +
                "\u001b[32m                                ;MMMMMMMMMMO                              \u001b[37;1m          Proudly presented to you by:\u001b[0m\n" +
                "\u001b[32m                               'WMMMMKxMMMMM0                             \u001b[34;1m          Natalia Portillo\u001b[0m\n" +
                "\u001b[32m                              oMMMMNc  :WMMMMN:\u001b[0m\n" +
                "\u001b[32m                           .dWMMM0;      dWMMMMXl.                        \u001b[37;1m          Thanks to all contributors, collaborators, translators, donators and friends.\u001b[0m\n" +
                "\u001b[32m               .......,cd0WMMNk:           c0MMMMMWKkolc:clodc'\u001b[0m\n" +
                "\u001b[32m                 .';loddol:'.                 ':oxkkOkkxoc,.\u001b[0m\n" +
                "\u001b[0m\n", Version.GetVersion(),
                             #if DEBUG
                "DEBUG"
                             #else
                "RELEASE"
                             #endif
                , DetectOS.GetPlatformName(DetectOS.GetRealPlatformID()),
                Environment.Is64BitOperatingSystem ? 64 : 32, Environment.Is64BitProcess ? 64 : 32,
                DetectOS.IsMono ? "Mono" : ".NET Core",
                DetectOS.IsMono ? Version.GetMonoVersion() : Version.GetNetCoreVersion());

            IHost host = CreateHostBuilder(args).Build();

            using (IServiceScope scope = host.Services.CreateScope())
            {
                IServiceProvider services = scope.ServiceProvider;

                try
                {
                    start = DateTime.Now;
                    System.Console.WriteLine("\u001b[31;1mUpdating database with Entity Framework...\u001b[0m");
                    var context = services.GetRequiredService <DicServerContext>();
                    context.Database.Migrate();
                    end = DateTime.Now;

                    System.Console.WriteLine("\u001b[31;1mTook \u001b[32;1m{0} seconds\u001b[31;1m...\u001b[0m",
                                             (end - start).TotalSeconds);
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine("\u001b[31;1mCould not open database...\u001b[0m");
                #if DEBUG
                    System.Console.WriteLine("\u001b[31;1mException: {0}\u001b[0m", ex.Message);
                #endif
                    return;
                }
            }

            System.Console.WriteLine("\u001b[31;1mStarting web server...\u001b[0m");
            host.Run();
        }
Exemple #22
0
        /// <summary>Opens the device for sending direct commands</summary>
        /// <param name="devicePath">Device path</param>
        public Device(string devicePath)
        {
            PlatformId  = DetectOS.GetRealPlatformID();
            Timeout     = 15;
            Error       = false;
            IsRemovable = false;

            if (devicePath.StartsWith("dic://") ||
                devicePath.StartsWith("aaru://"))
            {
                if (devicePath.StartsWith("dic://"))
                {
                    devicePath = devicePath.Substring(6);
                }
                else
                {
                    devicePath = devicePath.Substring(7);
                }

                string[] pieces = devicePath.Split('/');
                string   host   = pieces[0];
                devicePath = devicePath.Substring(host.Length);

                _remote = new Remote.Remote(host);

                Error     = !_remote.Open(devicePath, out int errno);
                LastError = errno;
            }
            else
            {
                switch (PlatformId)
                {
                case PlatformID.Win32NT:
                {
                    FileHandle = Extern.CreateFile(devicePath, FileAccess.GenericRead | FileAccess.GenericWrite,
                                                   FileShare.Read | FileShare.Write, IntPtr.Zero,
                                                   FileMode.OpenExisting, FileAttributes.Normal, IntPtr.Zero);

                    if (((SafeFileHandle)FileHandle).IsInvalid)
                    {
                        Error     = true;
                        LastError = Marshal.GetLastWin32Error();
                    }

                    break;
                }

                case PlatformID.Linux:
                {
                    FileHandle =
                        Linux.Extern.open(devicePath,
                                          FileFlags.ReadWrite | FileFlags.NonBlocking | FileFlags.CreateNew);

                    if ((int)FileHandle < 0)
                    {
                        LastError = Marshal.GetLastWin32Error();

                        if (LastError == 13 ||
                            LastError == 30)    // EACCES or EROFS
                        {
                            FileHandle = Linux.Extern.open(devicePath, FileFlags.Readonly | FileFlags.NonBlocking);

                            if ((int)FileHandle < 0)
                            {
                                Error     = true;
                                LastError = Marshal.GetLastWin32Error();
                            }
                        }
                        else
                        {
                            Error = true;
                        }

                        LastError = Marshal.GetLastWin32Error();
                    }

                    break;
                }

                case PlatformID.FreeBSD:
                {
                    FileHandle = FreeBSD.Extern.cam_open_device(devicePath, FreeBSD.FileFlags.ReadWrite);

                    if (((IntPtr)FileHandle).ToInt64() == 0)
                    {
                        Error     = true;
                        LastError = Marshal.GetLastWin32Error();
                    }

                    var camDevice = (CamDevice)Marshal.PtrToStructure((IntPtr)FileHandle, typeof(CamDevice));

                    if (StringHandlers.CToString(camDevice.SimName) == "ata")
                    {
                        throw new
                              DeviceException("Parallel ATA devices are not supported on FreeBSD due to upstream bug #224250.");
                    }

                    break;
                }

                default: throw new DeviceException($"Platform {PlatformId} not yet supported.");
                }
            }

            if (Error)
            {
                throw new DeviceException(LastError);
            }

            Type     = DeviceType.Unknown;
            ScsiType = PeripheralDeviceTypes.UnknownDevice;

            byte[] ataBuf;
            byte[] inqBuf = null;

            if (Error)
            {
                throw new DeviceException(LastError);
            }

            bool scsiSense = true;

            if (_remote is null)
            {
                // Windows is answering SCSI INQUIRY for all device types so it needs to be detected first
                switch (PlatformId)
                {
                case PlatformID.Win32NT:
                    var query = new StoragePropertyQuery();
                    query.PropertyId           = StoragePropertyId.Device;
                    query.QueryType            = StorageQueryType.Standard;
                    query.AdditionalParameters = new byte[1];

                    IntPtr descriptorPtr = Marshal.AllocHGlobal(1000);
                    byte[] descriptorB   = new byte[1000];

                    uint returned = 0;
                    int  error    = 0;

                    bool hasError = !Extern.DeviceIoControlStorageQuery((SafeFileHandle)FileHandle,
                                                                        WindowsIoctl.IoctlStorageQueryProperty,
                                                                        ref query, (uint)Marshal.SizeOf(query),
                                                                        descriptorPtr, 1000, ref returned,
                                                                        IntPtr.Zero);

                    if (hasError)
                    {
                        error = Marshal.GetLastWin32Error();
                    }

                    Marshal.Copy(descriptorPtr, descriptorB, 0, 1000);

                    if (!hasError &&
                        error == 0)
                    {
                        var descriptor = new StorageDeviceDescriptor
                        {
                            Version               = BitConverter.ToUInt32(descriptorB, 0),
                            Size                  = BitConverter.ToUInt32(descriptorB, 4), DeviceType = descriptorB[8],
                            DeviceTypeModifier    = descriptorB[9], RemovableMedia = descriptorB[10] > 0,
                            CommandQueueing       = descriptorB[11] > 0,
                            VendorIdOffset        = BitConverter.ToInt32(descriptorB, 12),
                            ProductIdOffset       = BitConverter.ToInt32(descriptorB, 16),
                            ProductRevisionOffset = BitConverter.ToInt32(descriptorB, 20),
                            SerialNumberOffset    = BitConverter.ToInt32(descriptorB, 24),
                            BusType               = (StorageBusType)BitConverter.ToUInt32(descriptorB, 28),
                            RawPropertiesLength   = BitConverter.ToUInt32(descriptorB, 32)
                        };

                        descriptor.RawDeviceProperties = new byte[descriptor.RawPropertiesLength];

                        Array.Copy(descriptorB, 36, descriptor.RawDeviceProperties, 0,
                                   descriptor.RawPropertiesLength);

                        switch (descriptor.BusType)
                        {
                        case StorageBusType.SCSI:
                        case StorageBusType.SSA:
                        case StorageBusType.Fibre:
                        case StorageBusType.iSCSI:
                        case StorageBusType.SAS:
                            Type = DeviceType.SCSI;

                            break;

                        case StorageBusType.FireWire:
                            IsFireWire = true;
                            Type       = DeviceType.SCSI;

                            break;

                        case StorageBusType.USB:
                            IsUsb = true;
                            Type  = DeviceType.SCSI;

                            break;

                        case StorageBusType.ATAPI:
                            Type = DeviceType.ATAPI;

                            break;

                        case StorageBusType.ATA:
                        case StorageBusType.SATA:
                            Type = DeviceType.ATA;

                            break;

                        case StorageBusType.MultiMediaCard:
                            Type = DeviceType.MMC;

                            break;

                        case StorageBusType.SecureDigital:
                            Type = DeviceType.SecureDigital;

                            break;

                        case StorageBusType.NVMe:
                            Type = DeviceType.NVMe;

                            break;
                        }

                        switch (Type)
                        {
                        case DeviceType.SCSI:
                        case DeviceType.ATAPI:
                            scsiSense = ScsiInquiry(out inqBuf, out _);

                            break;

                        case DeviceType.ATA:
                            bool atapiSense = AtapiIdentify(out ataBuf, out _);

                            if (!atapiSense)
                            {
                                Type = DeviceType.ATAPI;
                                Identify.IdentifyDevice?ataid = Identify.Decode(ataBuf);

                                if (ataid.HasValue)
                                {
                                    scsiSense = ScsiInquiry(out inqBuf, out _);
                                }
                            }
                            else
                            {
                                Manufacturer = "ATA";
                            }

                            break;
                        }
                    }

                    Marshal.FreeHGlobal(descriptorPtr);

                    if (Windows.Command.IsSdhci((SafeFileHandle)FileHandle))
                    {
                        byte[] sdBuffer = new byte[16];

                        LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle, MmcCommands.SendCsd,
                                                                   false, false,
                                                                   MmcFlags.ResponseSpiR2 | MmcFlags.ResponseR2 |
                                                                   MmcFlags.CommandAc, 0, 16, 1, ref sdBuffer,
                                                                   out _, out _, out bool sense);

                        if (!sense)
                        {
                            cachedCsd = new byte[16];
                            Array.Copy(sdBuffer, 0, cachedCsd, 0, 16);
                        }

                        sdBuffer = new byte[16];

                        LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle, MmcCommands.SendCid,
                                                                   false, false,
                                                                   MmcFlags.ResponseSpiR2 | MmcFlags.ResponseR2 |
                                                                   MmcFlags.CommandAc, 0, 16, 1, ref sdBuffer,
                                                                   out _, out _, out sense);

                        if (!sense)
                        {
                            cachedCid = new byte[16];
                            Array.Copy(sdBuffer, 0, cachedCid, 0, 16);
                        }

                        sdBuffer = new byte[8];

                        LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle,
                                                                   (MmcCommands)SecureDigitalCommands.SendScr,
                                                                   false, true,
                                                                   MmcFlags.ResponseSpiR1 | MmcFlags.ResponseR1 |
                                                                   MmcFlags.CommandAdtc, 0, 8, 1, ref sdBuffer,
                                                                   out _, out _, out sense);

                        if (!sense)
                        {
                            cachedScr = new byte[8];
                            Array.Copy(sdBuffer, 0, cachedScr, 0, 8);
                        }

                        sdBuffer = new byte[4];

                        LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle,
                                                                   cachedScr != null
                                                                           ? (MmcCommands)SecureDigitalCommands.
                                                                   SendOperatingCondition
                                                                           : MmcCommands.SendOpCond, false, true,
                                                                   MmcFlags.ResponseSpiR3 | MmcFlags.ResponseR3 |
                                                                   MmcFlags.CommandBcr, 0, 4, 1, ref sdBuffer,
                                                                   out _, out _, out sense);

                        if (!sense)
                        {
                            cachedScr = new byte[4];
                            Array.Copy(sdBuffer, 0, cachedScr, 0, 4);
                        }
                    }

                    break;

                case PlatformID.Linux:
                    if (devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
                        devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
                        devicePath.StartsWith("/dev/st", StringComparison.Ordinal) ||
                        devicePath.StartsWith("/dev/sg", StringComparison.Ordinal))
                    {
                        scsiSense = ScsiInquiry(out inqBuf, out _);
                    }

                    // MultiMediaCard and SecureDigital go here
                    else if (devicePath.StartsWith("/dev/mmcblk", StringComparison.Ordinal))
                    {
                        string devPath = devicePath.Substring(5);

                        if (File.Exists("/sys/block/" + devPath + "/device/csd"))
                        {
                            int len = ConvertFromHexAscii("/sys/block/" + devPath + "/device/csd", out cachedCsd);

                            if (len == 0)
                            {
                                cachedCsd = null;
                            }
                        }

                        if (File.Exists("/sys/block/" + devPath + "/device/cid"))
                        {
                            int len = ConvertFromHexAscii("/sys/block/" + devPath + "/device/cid", out cachedCid);

                            if (len == 0)
                            {
                                cachedCid = null;
                            }
                        }

                        if (File.Exists("/sys/block/" + devPath + "/device/scr"))
                        {
                            int len = ConvertFromHexAscii("/sys/block/" + devPath + "/device/scr", out cachedScr);

                            if (len == 0)
                            {
                                cachedScr = null;
                            }
                        }

                        if (File.Exists("/sys/block/" + devPath + "/device/ocr"))
                        {
                            int len = ConvertFromHexAscii("/sys/block/" + devPath + "/device/ocr", out cachedOcr);

                            if (len == 0)
                            {
                                cachedOcr = null;
                            }
                        }
                    }

                    break;

                default:
                    scsiSense = ScsiInquiry(out inqBuf, out _);

                    break;
                }
            }
            else
            {
                Type = _remote.GetDeviceType();

                switch (Type)
                {
                case DeviceType.ATAPI:
                case DeviceType.SCSI:
                    scsiSense = ScsiInquiry(out inqBuf, out _);

                    break;

                case DeviceType.SecureDigital:
                case DeviceType.MMC:
                    if (!_remote.GetSdhciRegisters(out cachedCsd, out cachedCid, out cachedOcr, out cachedScr))
                    {
                        Type     = DeviceType.SCSI;
                        ScsiType = PeripheralDeviceTypes.DirectAccess;
                    }

                    break;
                }
            }

            #region SecureDigital / MultiMediaCard
            if (cachedCid != null)
            {
                ScsiType    = PeripheralDeviceTypes.DirectAccess;
                IsRemovable = false;

                if (cachedScr != null)
                {
                    Type = DeviceType.SecureDigital;
                    CID decoded = Decoders.SecureDigital.Decoders.DecodeCID(cachedCid);
                    Manufacturer = VendorString.Prettify(decoded.Manufacturer);
                    Model        = decoded.ProductName;

                    FirmwareRevision =
                        $"{(decoded.ProductRevision & 0xF0) >> 4:X2}.{decoded.ProductRevision & 0x0F:X2}";

                    Serial = $"{decoded.ProductSerialNumber}";
                }
                else
                {
                    Type = DeviceType.MMC;
                    Decoders.MMC.CID decoded = Decoders.MMC.Decoders.DecodeCID(cachedCid);
                    Manufacturer = Decoders.MMC.VendorString.Prettify(decoded.Manufacturer);
                    Model        = decoded.ProductName;

                    FirmwareRevision =
                        $"{(decoded.ProductRevision & 0xF0) >> 4:X2}.{decoded.ProductRevision & 0x0F:X2}";

                    Serial = $"{decoded.ProductSerialNumber}";
                }

                return;
            }
            #endregion SecureDigital / MultiMediaCard

            #region USB
            if (_remote is null)
            {
                switch (PlatformId)
                {
                case PlatformID.Linux:
                    if (devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
                        devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
                        devicePath.StartsWith("/dev/st", StringComparison.Ordinal))
                    {
                        string devPath = devicePath.Substring(5);

                        if (Directory.Exists("/sys/block/" + devPath))
                        {
                            string resolvedLink = Linux.Command.ReadLink("/sys/block/" + devPath);

                            if (!string.IsNullOrEmpty(resolvedLink))
                            {
                                resolvedLink = "/sys" + resolvedLink.Substring(2);

                                while (resolvedLink.Contains("usb"))
                                {
                                    resolvedLink = Path.GetDirectoryName(resolvedLink);

                                    if (!File.Exists(resolvedLink + "/descriptors") ||
                                        !File.Exists(resolvedLink + "/idProduct") ||
                                        !File.Exists(resolvedLink + "/idVendor"))
                                    {
                                        continue;
                                    }

                                    var usbFs = new FileStream(resolvedLink + "/descriptors",
                                                               System.IO.FileMode.Open, System.IO.FileAccess.Read);

                                    byte[] usbBuf   = new byte[65536];
                                    int    usbCount = usbFs.Read(usbBuf, 0, 65536);
                                    UsbDescriptors = new byte[usbCount];
                                    Array.Copy(usbBuf, 0, UsbDescriptors, 0, usbCount);
                                    usbFs.Close();

                                    var    usbSr   = new StreamReader(resolvedLink + "/idProduct");
                                    string usbTemp = usbSr.ReadToEnd();

                                    ushort.TryParse(usbTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
                                                    out usbProduct);

                                    usbSr.Close();

                                    usbSr   = new StreamReader(resolvedLink + "/idVendor");
                                    usbTemp = usbSr.ReadToEnd();

                                    ushort.TryParse(usbTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
                                                    out usbVendor);

                                    usbSr.Close();

                                    if (File.Exists(resolvedLink + "/manufacturer"))
                                    {
                                        usbSr = new StreamReader(resolvedLink + "/manufacturer");
                                        UsbManufacturerString = usbSr.ReadToEnd().Trim();
                                        usbSr.Close();
                                    }

                                    if (File.Exists(resolvedLink + "/product"))
                                    {
                                        usbSr            = new StreamReader(resolvedLink + "/product");
                                        UsbProductString = usbSr.ReadToEnd().Trim();
                                        usbSr.Close();
                                    }

                                    if (File.Exists(resolvedLink + "/serial"))
                                    {
                                        usbSr           = new StreamReader(resolvedLink + "/serial");
                                        UsbSerialString = usbSr.ReadToEnd().Trim();
                                        usbSr.Close();
                                    }

                                    IsUsb = true;

                                    break;
                                }
                            }
                        }
                    }

                    break;

                case PlatformID.Win32NT:
                    Usb.UsbDevice usbDevice = null;

                    // I have to search for USB disks, floppies and CD-ROMs as separate device types
                    foreach (string devGuid in new[]
                    {
                        Usb.GuidDevinterfaceFloppy, Usb.GuidDevinterfaceCdrom, Usb.GuidDevinterfaceDisk,
                        Usb.GuidDevinterfaceTape
                    })
                    {
                        usbDevice = Usb.FindDrivePath(devicePath, devGuid);

                        if (usbDevice != null)
                        {
                            break;
                        }
                    }

                    if (usbDevice != null)
                    {
                        UsbDescriptors        = usbDevice.BinaryDescriptors;
                        usbVendor             = (ushort)usbDevice.DeviceDescriptor.idVendor;
                        usbProduct            = (ushort)usbDevice.DeviceDescriptor.idProduct;
                        UsbManufacturerString = usbDevice.Manufacturer;
                        UsbProductString      = usbDevice.Product;

                        UsbSerialString =
                            usbDevice.
                            SerialNumber;         // This is incorrect filled by Windows with SCSI/ATA serial number
                    }

                    break;

                default:
                    IsUsb = false;

                    break;
                }
            }
            else
            {
                if (_remote.GetUsbData(out byte[] remoteUsbDescriptors, out ushort remoteUsbVendor,
                                       out ushort remoteUsbProduct, out string remoteUsbManufacturer,
                                       out string remoteUsbProductString, out string remoteUsbSerial))
                {
                    IsUsb                 = true;
                    UsbDescriptors        = remoteUsbDescriptors;
                    usbVendor             = remoteUsbVendor;
                    usbProduct            = remoteUsbProduct;
                    UsbManufacturerString = remoteUsbManufacturer;
                    UsbProductString      = remoteUsbProductString;
                    UsbSerialString       = remoteUsbSerial;
                }
            }
            #endregion USB

            #region FireWire
            if (!(_remote is null))
            {
                if (_remote.GetFireWireData(out firewireVendor, out firewireModel, out firewireGuid,
                                            out string remoteFireWireVendorName, out string remoteFireWireModelName))
                {
                    IsFireWire         = true;
                    FireWireVendorName = remoteFireWireVendorName;
                    FireWireModelName  = remoteFireWireModelName;
                }
            }
Exemple #23
0
        public static void SaveSettings()
        {
            try
            {
                PlatformID ptId = DetectOS.GetRealPlatformID();

                switch (ptId)
                {
                case PlatformID.MacOSX:
                case PlatformID.iOS:
                {
                    var root = new NSDictionary
                    {
                        {
                            "TemporaryFolder", Current.TemporaryFolder
                        },
                        {
                            "DatabasePath", Current.DatabasePath
                        },
                        {
                            "RepositoryPath", Current.RepositoryPath
                        },
                        {
                            "UnArchiverPath", Current.UnArchiverPath
                        },
                        {
                            "CompressionAlgorithm", Current.CompressionAlgorithm.ToString()
                        },
                        {
                            "UseAntivirus", Current.UseAntivirus
                        },
                        {
                            "UseClamd", Current.UseClamd
                        },
                        {
                            "ClamdHost", Current.ClamdHost
                        },
                        {
                            "ClamdPort", Current.ClamdPort
                        },
                        {
                            "ClamdIsLocal", Current.ClamdIsLocal
                        },
                        {
                            "UseVirusTotal", Current.UseVirusTotal
                        },
                        {
                            "VirusTotalKey", Current.VirusTotalKey
                        }
                    };

                    string preferencesPath =
                        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library",
                                     "Preferences");

                    string preferencesFilePath =
                        Path.Combine(preferencesPath, "com.claunia.museum.apprepodbmgr.plist");

                    var fs = new FileStream(preferencesFilePath, FileMode.Create);
                    BinaryPropertyListWriter.Write(fs, root);
                    fs.Close();
                }

                break;

                case PlatformID.Win32NT:
                case PlatformID.Win32S:
                case PlatformID.Win32Windows:
                case PlatformID.WinCE:
                case PlatformID.WindowsPhone:
                {
                    RegistryKey parentKey = Registry.CurrentUser.OpenSubKey("SOFTWARE", true)?.
                                            CreateSubKey("Canary Islands Computer Museum");

                    RegistryKey key = parentKey?.CreateSubKey("AppRepoDBMgr");

                    if (key != null)
                    {
                        key.SetValue("TemporaryFolder", Current.TemporaryFolder);
                        key.SetValue("DatabasePath", Current.DatabasePath);
                        key.SetValue("RepositoryPath", Current.RepositoryPath);

                        if (Current.UnArchiverPath != null)
                        {
                            key.SetValue("UnArchiverPath", Current.UnArchiverPath);
                        }

                        key.SetValue("CompressionAlgorithm", Current.CompressionAlgorithm);
                        key.SetValue("UseAntivirus", Current.UseAntivirus);
                        key.SetValue("UseClamd", Current.UseClamd);
                        key.SetValue("ClamdHost", Current.ClamdHost == null ? "" : Current.ClamdHost);
                        key.SetValue("ClamdPort", Current.ClamdPort);
                        key.SetValue("ClamdIsLocal", Current.ClamdIsLocal);
                        key.SetValue("UseVirusTotal", Current.UseVirusTotal);
                        key.SetValue("VirusTotalKey", Current.VirusTotalKey == null ? "" : Current.VirusTotalKey);
                    }
                }

                break;

                default:
                {
                    string configPath =
                        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config");

                    string settingsPath = Path.Combine(configPath, "AppRepoDBMgr.xml");

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

                    var fs = new FileStream(settingsPath, FileMode.Create);
                    var xs = new XmlSerializer(Current.GetType());
                    xs.Serialize(fs, Current);
                    fs.Close();
                }

                break;
                }
            }
            #pragma warning disable RECS0022     // A catch clause that catches System.Exception and has an empty body
            catch
                #pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body
            {
                if (Debugger.IsAttached)
                {
                    throw;
                }
            }
        }
Exemple #24
0
    public static void Main(string[] args)
    {
        DateTime start;
        DateTime end;

        System.Console.Clear();

        System.Console.Write(
            "\u001b[32m                             .                ,,\n" +
            "\u001b[32m                          ;,.                  '0d.\n" +
            "\u001b[32m                        oc                       oWd                      \u001b[31m" +
            @"__/\\\\\\\\\\\\_____/\\\\\\\\\\\________/\\\\\\\\\_        " + "\n\u001b[0m" +
            "\u001b[32m                      ;X.                         'WN'                    \u001b[31m" +
            @" _\/\\\////////\\\__\/////\\\///______/\\\////////__       " + "\n\u001b[0m" +
            "\u001b[32m                     oMo                           cMM:                   \u001b[31m" +
            @"  _\/\\\______\//\\\_____\/\\\_______/\\\/___________      " + "\n\u001b[0m" +
            "\u001b[32m                    ;MM.                           .MMM;                  \u001b[31m" +
            @"   _\/\\\_______\/\\\_____\/\\\______/\\\_____________     " + "\n\u001b[0m" +
            "\u001b[32m                    NMM                             WMMW                  \u001b[31m" +
            @"    _\/\\\_______\/\\\_____\/\\\_____\/\\\_____________    " + "\n\u001b[0m" +
            "\u001b[32m                   'MMM                             MMMM;                 \u001b[31m" +
            @"     _\/\\\_______\/\\\_____\/\\\_____\//\\\____________   " + "\n\u001b[0m" +
            "\u001b[32m                   ,MMM:                           dMMMM:                 \u001b[31m" +
            @"      _\/\\\_______/\\\______\/\\\______\///\\\__________  " + "\n\u001b[0m" +
            "\u001b[32m                   .MMMW.                         :MMMMM.                 \u001b[31m" +
            @"       _\/\\\\\\\\\\\\/____/\\\\\\\\\\\____\////\\\\\\\\\_ " + "\n\u001b[0m" +
            "\u001b[32m                    XMMMW:    .:xKNMMMMMMN0d,    lMMMMMd                  \u001b[31m" +
            @"        _\////////////_____\///////////________\/////////__" + "\n\u001b[0m" +
            "\u001b[32m                    :MMMMMK; cWMNkl:;;;:lxKMXc .0MMMMMO\u001b[0m\n" +
            "\u001b[32m                   ..KMMMMMMNo,.             ,OMMMMMMW:,.                 \u001b[37;1m          Aaru Website\u001b[0m\n" +
            "\u001b[32m            .;d0NMMMMMMMMMMMMMMW0d:'    .;lOWMMMMMMMMMMMMMXkl.            \u001b[37;1m          Version \u001b[0m\u001b[33m{0}\u001b[37;1m-\u001b[0m\u001b[31m{1}\u001b[0m\n" +
            "\u001b[32m          :KMMMMMMMMMMMMMMMMMMMMMMMMc  WMMMMMMMMMMMMMMMMMMMMMMWk'\u001b[0m\n" +
            "\u001b[32m        ;NMMMMWX0kkkkO0XMMMMMMMMMMM0'  dNMMMMMMMMMMW0xl:;,;:oOWMMX;       \u001b[37;1m          Running under \u001b[35;1m{2}\u001b[37;1m, \u001b[35m{3}-bit\u001b[37;1m in \u001b[35m{4}-bit\u001b[37;1m mode.\u001b[0m\n" +
            "\u001b[32m       xMMWk:.           .c0MMMMMW'      OMMMMMM0c'..          .oNMO      \u001b[37;1m          Using \u001b[33;1m{5}\u001b[37;1m version \u001b[31;1m{6}\u001b[0m\n" +
            "\u001b[32m      OMNc            .MNc   oWMMk       'WMMNl. .MMK             ;KX.\u001b[0m\n" +
            "\u001b[32m     xMO               WMN     ;  .,    ,  ':    ,MMx               lK\u001b[0m\n" +
            "\u001b[32m    ,Md                cMMl     .XMMMWWMMMO      XMW.                :\u001b[0m\n" +
            "\u001b[32m    Ok                  xMMl     XMMMMMMMMc     0MW,\u001b[0m\n" +
            "\u001b[32m    0                    oMM0'   lMMMMMMMM.   :NMN'\u001b[0m\n" +
            "\u001b[32m    .                     .0MMKl ;MMMMMMMM  oNMWd\u001b[0m\n" +
            "\u001b[32m                            .dNW cMMMMMMMM, XKl\u001b[0m\n" +
            "\u001b[32m                                 0MMMMMMMMK\u001b[0m\n" +
            "\u001b[32m                                ;MMMMMMMMMMO                              \u001b[37;1m          Proudly presented to you by:\u001b[0m\n" +
            "\u001b[32m                               'WMMMMKxMMMMM0                             \u001b[34;1m          Natalia Portillo\u001b[0m\n" +
            "\u001b[32m                              oMMMMNc  :WMMMMN:\u001b[0m\n" +
            "\u001b[32m                           .dWMMM0;      dWMMMMXl.                        \u001b[37;1m          Thanks to all contributors, collaborators, translators, donators and friends.\u001b[0m\n" +
            "\u001b[32m               .......,cd0WMMNk:           c0MMMMMWKkolc:clodc'\u001b[0m\n" +
            "\u001b[32m                 .';loddol:'.                 ':oxkkOkkxoc,.\u001b[0m\n" +
            "\u001b[0m\n", Version.GetVersion(),
                         #if DEBUG
            "DEBUG"
                         #else
            "RELEASE"
                         #endif
            , DetectOS.GetPlatformName(DetectOS.GetRealPlatformID()),
            Environment.Is64BitOperatingSystem ? 64 : 32, Environment.Is64BitProcess ? 64 : 32,
            DetectOS.IsMono ? "Mono" : ".NET Core",
            DetectOS.IsMono ? Version.GetMonoVersion() : Version.GetNetCoreVersion());

        System.Console.WriteLine("\u001b[31;1mBuilding web application...\u001b[0m");

        WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

        builder.Services.AddDbContext <AaruServerContext>(options => options.
                                                          UseMySql(builder.Configuration.GetConnectionString("DefaultConnection"),
                                                                   new
                                                                   MariaDbServerVersion(new System.
                                                                                        Version(10, 4, 0))).
                                                          UseLazyLoadingProxies());

        builder.Services.AddDefaultIdentity <IdentityUser>(options =>
        {
            options.SignIn.RequireConfirmedAccount = true;
            options.User.RequireUniqueEmail        = true;
        }).AddEntityFrameworkStores <AaruServerContext>();

        builder.Services.AddApplicationInsightsTelemetry();

        builder.Services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

        WebApplication app = builder.Build();

        app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
        });

        app.UseHttpMetrics();

        if (builder.Environment.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");

            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseDefaultFiles();
        app.UseStaticFiles();

        // Add other security headers
        app.UseMiddleware <SecurityHeadersMiddleware>();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute("areas", "{area}/{controller=Home}/{action=Index}/{id?}");
            endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });

        app.Map("/metrics", metricsApp =>
        {
            metricsApp.UseMiddleware <BasicAuthMiddleware>("Aaru");

            // We already specified URL prefix in .Map() above, no need to specify it again here.
            metricsApp.UseMetricServer("");
        });

        using (IServiceScope scope = app.Services.CreateScope())
        {
            IServiceProvider services = scope.ServiceProvider;

            try
            {
                start = DateTime.Now;
                System.Console.WriteLine("\u001b[31;1mUpdating database with Entity Framework...\u001b[0m");
                AaruServerContext context = services.GetRequiredService <AaruServerContext>();
                context.Database.Migrate();
                end = DateTime.Now;

                System.Console.WriteLine("\u001b[31;1mTook \u001b[32;1m{0} seconds\u001b[31;1m...\u001b[0m",
                                         (end - start).TotalSeconds);

                start = DateTime.Now;
                System.Console.WriteLine("\u001b[31;1mSeeding Identity...\u001b[0m");
                Seeder.Seed(context, services);
                context.Database.Migrate();
                end = DateTime.Now;

                System.Console.WriteLine("\u001b[31;1mTook \u001b[32;1m{0} seconds\u001b[31;1m...\u001b[0m",
                                         (end - start).TotalSeconds);
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("\u001b[31;1mCould not open database...\u001b[0m");
            #if DEBUG
                System.Console.WriteLine("\u001b[31;1mException: {0}\u001b[0m", ex.Message);
            #endif
                return;
            }
        }

        System.Console.WriteLine("\u001b[31;1mStarting web server...\u001b[0m");

        app.Run();
    }
Exemple #25
0
        public static int Main(string[] args)
        {
            var attributes = typeof(MainClass).Assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false);

            AssemblyTitle   = ((AssemblyTitleAttribute)attributes[0]).Title;
            attributes      = typeof(MainClass).Assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
            AssemblyVersion =
                Attribute.GetCustomAttribute(typeof(MainClass).Assembly, typeof(AssemblyInformationalVersionAttribute))
                as AssemblyInformationalVersionAttribute;
            AssemblyCopyright = ((AssemblyCopyrightAttribute)attributes[0]).Copyright;

            DicConsole.WriteLineEvent      += System.Console.WriteLine;
            DicConsole.WriteEvent          += System.Console.Write;
            DicConsole.ErrorWriteLineEvent += System.Console.Error.WriteLine;

            Settings.Settings.LoadSettings();

            var ctx = DicContext.Create(Settings.Settings.LocalDbPath);

            ctx.Database.Migrate();
            ctx.SaveChanges();

            var masterDbUpdate = false;

            if (!File.Exists(Settings.Settings.MasterDbPath))
            {
                masterDbUpdate = true;
                UpdateCommand.DoUpdate(true);
            }

            var mctx = DicContext.Create(Settings.Settings.MasterDbPath);

            mctx.Database.Migrate();
            mctx.SaveChanges();

            if ((args.Length < 1 || args[0].ToLowerInvariant() != "gui") &&
                Settings.Settings.Current.GdprCompliance < DicSettings.GdprLevel)
            {
                new ConfigureCommand(true, true).Invoke(args);
            }
            Statistics.LoadStats();
            if (Settings.Settings.Current.Stats != null && Settings.Settings.Current.Stats.ShareStats)
            {
                Task.Run(() => { Statistics.SubmitStats(); });
            }

            var currentPlatform = DetectOS.GetRealPlatformID();

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            var commands = new CommandSet("DiscImageChef")
            {
                $"{AssemblyTitle} {AssemblyVersion?.InformationalVersion}",
                $"{AssemblyCopyright}",
                "",
                "usage: DiscImageChef COMMAND [OPTIONS]",
                "",
                "Global options:",
                { "verbose|v", "Shows verbose output.", b => Verbose = b != null },
                { "debug|d", "Shows debug output from plugins.", b => Debug = b != null },
                "",
                "Available commands:",
                new AnalyzeCommand(),
                new BenchmarkCommand(),
                new ChecksumCommand(),
                new CompareCommand(),
                new ConfigureCommand(false, false),
                new ConvertImageCommand(),
                new CreateSidecarCommand(),
                new DecodeCommand()
            };

            if (currentPlatform == PlatformID.FreeBSD || currentPlatform == PlatformID.Linux ||
                currentPlatform == PlatformID.Win32NT)
            {
                commands.Add(new DeviceInfoCommand());
                commands.Add(new DeviceReportCommand());
                commands.Add(new DumpMediaCommand());
            }

            commands.Add(new EntropyCommand());
            commands.Add(new ExtractFilesCommand());
            commands.Add(new FormatsCommand());
            commands.Add(new ImageInfoCommand());

            if (currentPlatform == PlatformID.FreeBSD || currentPlatform == PlatformID.Linux ||
                currentPlatform == PlatformID.Win32NT)
            {
                commands.Add(new ListDevicesCommand());
            }

            commands.Add(new ListEncodingsCommand());
            commands.Add(new ListNamespacesCommand());
            commands.Add(new ListOptionsCommand());
            commands.Add(new LsCommand());

            if (currentPlatform == PlatformID.FreeBSD || currentPlatform == PlatformID.Linux ||
                currentPlatform == PlatformID.Win32NT)
            {
                commands.Add(new MediaInfoCommand());
                commands.Add(new MediaScanCommand());
            }

            commands.Add(new PrintHexCommand());
            commands.Add(new StatisticsCommand());
            commands.Add(new UpdateCommand(masterDbUpdate));
            commands.Add(new VerifyCommand());
            commands.Add(new RemoteCommand());

            var ret = commands.Run(args);

            Statistics.SaveStats();

            return(ret);
        }
Exemple #26
0
        public ActionResult Index()
        {
            ViewBag.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            try
            {
                if (
                    System.IO.File
                    .Exists(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(),
                                         "Statistics", "Statistics.xml")))
                {
                    try
                    {
                        Stats statistics = new Stats();

                        XmlSerializer xs = new XmlSerializer(statistics.GetType());
                        FileStream    fs =
                            WaitForFile(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(), "Statistics", "Statistics.xml"),
                                        FileMode.Open, FileAccess.Read, FileShare.Read);
                        statistics = (Stats)xs.Deserialize(fs);
                        fs.Close();

                        StatsConverter.Convert(statistics);

                        System.IO.File
                        .Delete(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(),
                                             "Statistics", "Statistics.xml"));
                    }
                    catch (XmlException)
                    {
                        // Do nothing
                    }
                }

                if (ctx.OperatingSystems.Any())
                {
                    operatingSystems = new List <NameValueStats>();
                    foreach (OperatingSystem nvs in ctx.OperatingSystems)
                    {
                        operatingSystems.Add(new NameValueStats
                        {
                            name =
                                $"{DetectOS.GetPlatformName((PlatformID)Enum.Parse(typeof(PlatformID), nvs.Name), nvs.Version)}{(string.IsNullOrEmpty(nvs.Version) ? "" : " ")}{nvs.Version}",
                            Value = nvs.Count
                        });
                    }

                    ViewBag.repOperatingSystems = operatingSystems.OrderBy(os => os.name).ToList();

                    List <PieSeriesData> osPieData = new List <PieSeriesData>();

                    decimal totalOsCount = ctx.OperatingSystems.Sum(o => o.Count);
                    foreach (string os in ctx.OperatingSystems.Select(o => o.Name).Distinct().ToList())
                    {
                        decimal osCount = ctx.OperatingSystems.Where(o => o.Name == os).Sum(o => o.Count);

                        osPieData.Add(new PieSeriesData
                        {
                            Name =
                                DetectOS.GetPlatformName((PlatformID)Enum.Parse(typeof(PlatformID),
                                                                                os)),
                            Y        = (double?)(osCount / totalOsCount),
                            Sliced   = os == "Linux",
                            Selected = os == "Linux"
                        });
                    }

                    ViewData["osPieData"] = osPieData;

                    List <PieSeriesData> linuxPieData = new List <PieSeriesData>();

                    decimal linuxCount = ctx.OperatingSystems.Where(o => o.Name == PlatformID.Linux.ToString())
                                         .Sum(o => o.Count);
                    foreach (OperatingSystem version in
                             ctx.OperatingSystems.Where(o => o.Name == PlatformID.Linux.ToString()))
                    {
                        linuxPieData.Add(new PieSeriesData
                        {
                            Name =
                                $"{DetectOS.GetPlatformName(PlatformID.Linux, version.Version)}{(string.IsNullOrEmpty(version.Version) ? "" : " ")}{version.Version}",
                            Y = (double?)(version.Count / linuxCount)
                        });
                    }

                    ViewData["linuxPieData"] = linuxPieData;

                    List <PieSeriesData> macosPieData = new List <PieSeriesData>();

                    decimal macosCount = ctx.OperatingSystems.Where(o => o.Name == PlatformID.MacOSX.ToString())
                                         .Sum(o => o.Count);
                    foreach (OperatingSystem version in
                             ctx.OperatingSystems.Where(o => o.Name == PlatformID.MacOSX.ToString()))
                    {
                        macosPieData.Add(new PieSeriesData
                        {
                            Name =
                                $"{DetectOS.GetPlatformName(PlatformID.MacOSX, version.Version)}{(string.IsNullOrEmpty(version.Version) ? "" : " ")}{version.Version}",
                            Y = (double?)(version.Count / macosCount)
                        });
                    }

                    ViewData["macosPieData"] = macosPieData;

                    List <PieSeriesData> windowsPieData = new List <PieSeriesData>();

                    decimal windowsCount = ctx.OperatingSystems.Where(o => o.Name == PlatformID.Win32NT.ToString())
                                           .Sum(o => o.Count);
                    foreach (OperatingSystem version in
                             ctx.OperatingSystems.Where(o => o.Name == PlatformID.Win32NT.ToString()))
                    {
                        windowsPieData.Add(new PieSeriesData
                        {
                            Name =
                                $"{DetectOS.GetPlatformName(PlatformID.Win32NT, version.Version)}{(string.IsNullOrEmpty(version.Version) ? "" : " ")}{version.Version}",
                            Y = (double?)(version.Count / windowsCount)
                        });
                    }

                    ViewData["windowsPieData"] = windowsPieData;
                }

                if (ctx.Versions.Any())
                {
                    versions = new List <NameValueStats>();
                    foreach (Version nvs in ctx.Versions)
                    {
                        versions.Add(new NameValueStats
                        {
                            name  = nvs.Value == "previous" ? "Previous than 3.4.99.0" : nvs.Value,
                            Value = nvs.Count
                        });
                    }

                    ViewBag.repVersions = versions.OrderBy(ver => ver.name).ToList();

                    decimal totalVersionCount = ctx.Versions.Sum(o => o.Count);

                    ViewData["versionsPieData"] = ctx.Versions.Select(version => new PieSeriesData
                    {
                        Name =
                            version.Value == "previous"
                                ? "Previous than 3.4.99.0"
                                : version.Value,
                        Y = (double?)(version.Count /
                                      totalVersionCount),
                        Sliced   = version.Value == "previous",
                        Selected = version.Value == "previous"
                    }).ToList();
                }

                if (ctx.Commands.Any())
                {
                    ViewBag.repCommands = ctx.Commands.OrderBy(c => c.Name).ToList();

                    decimal totalCommandCount = ctx.Commands.Sum(o => o.Count);

                    ViewData["commandsPieData"] = ctx
                                                  .Commands.Select(command => new PieSeriesData
                    {
                        Name = command.Name,
                        Y    = (double?)(command.Count /
                                         totalCommandCount),
                        Sliced   = command.Name == "analyze",
                        Selected = command.Name == "analyze"
                    }).ToList();
                }

                if (ctx.Filters.Any())
                {
                    ViewBag.repFilters = ctx.Filters.OrderBy(filter => filter.Name).ToList();

                    List <PieSeriesData> filtersPieData = new List <PieSeriesData>();

                    decimal totalFiltersCount = ctx.Filters.Sum(o => o.Count);
                    foreach (Filter filter in ctx.Filters.ToList())
                    {
                        filtersPieData.Add(new PieSeriesData
                        {
                            Name     = filter.Name,
                            Y        = (double?)(filter.Count / totalFiltersCount),
                            Sliced   = filter.Name == "No filter",
                            Selected = filter.Name == "No filter"
                        });
                    }

                    ViewData["filtersPieData"] = filtersPieData;
                }

                if (ctx.MediaFormats.Any())
                {
                    ViewBag.repMediaImages = ctx.MediaFormats.OrderBy(filter => filter.Name).ToList();

                    List <PieSeriesData> formatsPieData = new List <PieSeriesData>();

                    decimal totalFormatsCount = ctx.MediaFormats.Sum(o => o.Count);
                    decimal top10FormatCount  = 0;

                    foreach (MediaFormat format in ctx.MediaFormats.OrderByDescending(o => o.Count).Take(10))
                    {
                        top10FormatCount += format.Count;

                        formatsPieData.Add(new PieSeriesData
                        {
                            Name = format.Name, Y = (double?)(format.Count / totalFormatsCount)
                        });
                    }

                    formatsPieData.Add(new PieSeriesData
                    {
                        Name = "Other",
                        Y    = (double?)((totalFormatsCount - top10FormatCount) /
                                         totalFormatsCount),
                        Sliced   = true,
                        Selected = true
                    });

                    ViewData["formatsPieData"] = formatsPieData;
                }

                if (ctx.Partitions.Any())
                {
                    ViewBag.repPartitions = ctx.Partitions.OrderBy(filter => filter.Name).ToList();

                    List <PieSeriesData> partitionsPieData = new List <PieSeriesData>();

                    decimal totalPartitionsCount = ctx.Partitions.Sum(o => o.Count);
                    decimal top10PartitionCount  = 0;

                    foreach (Partition partition in ctx.Partitions.OrderByDescending(o => o.Count).Take(10))
                    {
                        top10PartitionCount += partition.Count;

                        partitionsPieData.Add(new PieSeriesData
                        {
                            Name = partition.Name,
                            Y    = (double?)(partition.Count / totalPartitionsCount)
                        });
                    }

                    partitionsPieData.Add(new PieSeriesData
                    {
                        Name = "Other",
                        Y    = (double?)((totalPartitionsCount - top10PartitionCount) /
                                         totalPartitionsCount),
                        Sliced   = true,
                        Selected = true
                    });

                    ViewData["partitionsPieData"] = partitionsPieData;
                }

                if (ctx.Filesystems.Any())
                {
                    ViewBag.repFilesystems = ctx.Filesystems.OrderBy(filter => filter.Name).ToList();

                    List <PieSeriesData> filesystemsPieData = new List <PieSeriesData>();

                    decimal totalFilesystemsCount = ctx.Filesystems.Sum(o => o.Count);
                    decimal top10FilesystemCount  = 0;

                    foreach (Filesystem filesystem in ctx.Filesystems.OrderByDescending(o => o.Count).Take(10))
                    {
                        top10FilesystemCount += filesystem.Count;

                        filesystemsPieData.Add(new PieSeriesData
                        {
                            Name = filesystem.Name,
                            Y    = (double?)(filesystem.Count / totalFilesystemsCount)
                        });
                    }

                    filesystemsPieData.Add(new PieSeriesData
                    {
                        Name = "Other",
                        Y    = (double?)((totalFilesystemsCount - top10FilesystemCount) /
                                         totalFilesystemsCount),
                        Sliced   = true,
                        Selected = true
                    });

                    ViewData["filesystemsPieData"] = filesystemsPieData;
                }

                if (ctx.Medias.Any())
                {
                    realMedia    = new List <MediaItem>();
                    virtualMedia = new List <MediaItem>();
                    foreach (Media nvs in ctx.Medias)
                    {
                        try
                        {
                            MediaType
                            .MediaTypeToString((CommonTypes.MediaType)Enum.Parse(typeof(CommonTypes.MediaType), nvs.Type),
                                               out string type, out string subtype);

                            if (nvs.Real)
                            {
                                realMedia.Add(new MediaItem {
                                    Type = type, SubType = subtype, Count = nvs.Count
                                });
                            }
                            else
                            {
                                virtualMedia.Add(new MediaItem {
                                    Type = type, SubType = subtype, Count = nvs.Count
                                });
                            }
                        }
                        catch
                        {
                            if (nvs.Real)
                            {
                                realMedia.Add(new MediaItem {
                                    Type = nvs.Type, SubType = null, Count = nvs.Count
                                });
                            }
                            else
                            {
                                virtualMedia.Add(new MediaItem {
                                    Type = nvs.Type, SubType = null, Count = nvs.Count
                                });
                            }
                        }
                    }

                    if (realMedia.Count > 0)
                    {
                        ViewBag.repRealMedia =
                            realMedia.OrderBy(media => media.Type).ThenBy(media => media.SubType).ToList();

                        List <PieSeriesData> realMediaPieData = new List <PieSeriesData>();

                        decimal totalRealMediaCount = realMedia.Sum(o => o.Count);
                        decimal top10RealMediaCount = 0;

                        foreach (MediaItem realMediaItem in realMedia.OrderByDescending(o => o.Count).Take(10))
                        {
                            top10RealMediaCount += realMediaItem.Count;

                            realMediaPieData.Add(new PieSeriesData
                            {
                                Name = $"{realMediaItem.Type} ({realMediaItem.SubType})",
                                Y    = (double?)(realMediaItem.Count / totalRealMediaCount)
                            });
                        }

                        realMediaPieData.Add(new PieSeriesData
                        {
                            Name = "Other",
                            Y    = (double?)((totalRealMediaCount - top10RealMediaCount) /
                                             totalRealMediaCount),
                            Sliced   = true,
                            Selected = true
                        });

                        ViewData["realMediaPieData"] = realMediaPieData;
                    }

                    if (virtualMedia.Count > 0)
                    {
                        ViewBag.repVirtualMedia =
                            virtualMedia.OrderBy(media => media.Type).ThenBy(media => media.SubType).ToList();

                        List <PieSeriesData> virtualMediaPieData = new List <PieSeriesData>();

                        decimal totalVirtualMediaCount = virtualMedia.Sum(o => o.Count);
                        decimal top10VirtualMediaCount = 0;

                        foreach (MediaItem virtualMediaItem in virtualMedia.OrderByDescending(o => o.Count).Take(10))
                        {
                            top10VirtualMediaCount += virtualMediaItem.Count;

                            virtualMediaPieData.Add(new PieSeriesData
                            {
                                Name =
                                    $"{virtualMediaItem.Type} ({virtualMediaItem.SubType})",
                                Y = (double?)(virtualMediaItem.Count /
                                              totalVirtualMediaCount)
                            });
                        }

                        virtualMediaPieData.Add(new PieSeriesData
                        {
                            Name = "Other",
                            Y    = (double?)
                                   ((totalVirtualMediaCount - top10VirtualMediaCount) /
                                    totalVirtualMediaCount),
                            Sliced   = true,
                            Selected = true
                        });

                        ViewData["virtualMediaPieData"] = virtualMediaPieData;
                    }
                }

                if (ctx.DeviceStats.Any())
                {
                    devices = new List <DeviceItem>();
                    foreach (DeviceStat device in ctx.DeviceStats.ToList())
                    {
                        string xmlFile;
                        if (!string.IsNullOrWhiteSpace(device.Manufacturer) &&
                            !string.IsNullOrWhiteSpace(device.Model) &&
                            !string.IsNullOrWhiteSpace(device.Revision))
                        {
                            xmlFile = device.Manufacturer + "_" + device.Model + "_" + device.Revision + ".xml";
                        }
                        else if (!string.IsNullOrWhiteSpace(device.Manufacturer) &&
                                 !string.IsNullOrWhiteSpace(device.Model))
                        {
                            xmlFile = device.Manufacturer + "_" + device.Model + ".xml";
                        }
                        else if (!string.IsNullOrWhiteSpace(device.Model) && !string.IsNullOrWhiteSpace(device.Revision))
                        {
                            xmlFile = device.Model + "_" + device.Revision + ".xml";
                        }
                        else
                        {
                            xmlFile = device.Model + ".xml";
                        }

                        xmlFile = xmlFile.Replace('/', '_').Replace('\\', '_').Replace('?', '_');

                        if (System.IO.File.Exists(Path.Combine(HostingEnvironment.MapPath("~"), "Reports", xmlFile)))
                        {
                            DeviceReport deviceReport = new DeviceReport();

                            XmlSerializer xs = new XmlSerializer(deviceReport.GetType());
                            FileStream    fs =
                                WaitForFile(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(), "Reports", xmlFile),
                                            FileMode.Open, FileAccess.Read, FileShare.Read);
                            deviceReport = (DeviceReport)xs.Deserialize(fs);
                            fs.Close();

                            DeviceReportV2 deviceReportV2 = new DeviceReportV2(deviceReport);

                            device.Report = ctx.Devices.Add(new Device(deviceReportV2));
                            ctx.SaveChanges();

                            System.IO.File
                            .Delete(Path.Combine(HostingEnvironment.MapPath("~") ?? throw new InvalidOperationException(),
                                                 "Reports", xmlFile));
                        }

                        devices.Add(new DeviceItem
                        {
                            Manufacturer = device.Manufacturer,
                            Model        = device.Model,
                            Revision     = device.Revision,
                            Bus          = device.Bus,
                            ReportId     = device.Report != null && device.Report.Id != 0
                                           ? device.Report.Id
                                           : 0
                        });
                    }

                    ViewBag.repDevices = devices.OrderBy(device => device.Manufacturer).ThenBy(device => device.Model)
                                         .ThenBy(device => device.Revision).ThenBy(device => device.Bus)
                                         .ToList();

                    ViewData["devicesBusPieData"] = (from deviceBus in devices.Select(d => d.Bus).Distinct()
                                                     let deviceBusCount = devices.Count(d => d.Bus == deviceBus)
                                                                          select new PieSeriesData
                    {
                        Name = deviceBus,
                        Y = deviceBusCount / (double)devices.Count
                    }).ToList();

                    ViewData["devicesManufacturerPieData"] =
                        (from manufacturer in
                         devices.Where(d => d.Manufacturer != null).Select(d => d.Manufacturer.ToLowerInvariant())
                         .Distinct()
                         let manufacturerCount = devices.Count(d => d.Manufacturer?.ToLowerInvariant() == manufacturer)
                                                 select new PieSeriesData {
                        Name = manufacturer, Y = manufacturerCount / (double)devices.Count
                    })
                        .ToList();
                }
            }
            catch (Exception)
            {
                #if DEBUG
                throw;
                #endif
                return(Content("Could not read statistics"));
            }

            return(View());
        }
Exemple #27
0
        public bool Close()
        {
            if (!IsWriting)
            {
                ErrorMessage = "Image is not opened for writing";

                return(false);
            }

            Version thisVersion = GetType().Assembly.GetName().Version;

            if (_imageInfo.Cylinders == 0)
            {
                _imageInfo.Cylinders       = (uint)(_imageInfo.Sectors / 16 / 63);
                _imageInfo.Heads           = 16;
                _imageInfo.SectorsPerTrack = 63;

                while (_imageInfo.Cylinders == 0)
                {
                    _imageInfo.Heads--;

                    if (_imageInfo.Heads == 0)
                    {
                        _imageInfo.SectorsPerTrack--;
                        _imageInfo.Heads = 16;
                    }

                    _imageInfo.Cylinders = (uint)(_imageInfo.Sectors / _imageInfo.Heads / _imageInfo.SectorsPerTrack);

                    if (_imageInfo.Cylinders == 0 &&
                        _imageInfo.Heads == 0 &&
                        _imageInfo.SectorsPerTrack == 0)
                    {
                        break;
                    }
                }
            }

            var footer = new HardDiskFooter
            {
                Cookie             = IMAGE_COOKIE,
                Features           = FEATURES_RESERVED,
                Version            = VERSION1,
                Timestamp          = (uint)(DateTime.Now - new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds,
                CreatorApplication = CREATOR_AARU,
                CreatorVersion     = (uint)(((thisVersion.Major & 0xFF) << 24) + ((thisVersion.Minor & 0xFF) << 16) +
                                            ((thisVersion.Build & 0xFF) << 8) + (thisVersion.Revision & 0xFF)),
                CreatorHostOs = DetectOS.GetRealPlatformID() == PlatformID.MacOSX ? CREATOR_MACINTOSH : CREATOR_WINDOWS,
                DiskType      = TYPE_FIXED,
                UniqueId      = Guid.NewGuid(),
                DiskGeometry  = ((_imageInfo.Cylinders & 0xFFFF) << 16) + ((_imageInfo.Heads & 0xFF) << 8) +
                                (_imageInfo.SectorsPerTrack & 0xFF),
                OriginalSize = _imageInfo.Sectors * 512,
                CurrentSize  = _imageInfo.Sectors * 512
            };

            footer.Offset = footer.DiskType == TYPE_FIXED ? ulong.MaxValue : 512;

            byte[] footerBytes = new byte[512];
            Array.Copy(BigEndianBitConverter.GetBytes(footer.Cookie), 0, footerBytes, 0x00, 8);
            Array.Copy(BigEndianBitConverter.GetBytes(footer.Features), 0, footerBytes, 0x08, 4);
            Array.Copy(BigEndianBitConverter.GetBytes(footer.Version), 0, footerBytes, 0x0C, 4);
            Array.Copy(BigEndianBitConverter.GetBytes(footer.Offset), 0, footerBytes, 0x10, 8);
            Array.Copy(BigEndianBitConverter.GetBytes(footer.Timestamp), 0, footerBytes, 0x18, 4);
            Array.Copy(BigEndianBitConverter.GetBytes(footer.CreatorApplication), 0, footerBytes, 0x1C, 4);
            Array.Copy(BigEndianBitConverter.GetBytes(footer.CreatorVersion), 0, footerBytes, 0x20, 4);
            Array.Copy(BigEndianBitConverter.GetBytes(footer.CreatorHostOs), 0, footerBytes, 0x24, 4);
            Array.Copy(BigEndianBitConverter.GetBytes(footer.OriginalSize), 0, footerBytes, 0x28, 8);
            Array.Copy(BigEndianBitConverter.GetBytes(footer.CurrentSize), 0, footerBytes, 0x30, 8);
            Array.Copy(BigEndianBitConverter.GetBytes(footer.DiskGeometry), 0, footerBytes, 0x38, 4);
            Array.Copy(BigEndianBitConverter.GetBytes(footer.DiskType), 0, footerBytes, 0x3C, 4);
            Array.Copy(footer.UniqueId.ToByteArray(), 0, footerBytes, 0x44, 4);

            footer.Checksum = VhdChecksum(footerBytes);
            Array.Copy(BigEndianBitConverter.GetBytes(footer.Checksum), 0, footerBytes, 0x40, 4);

            _writingStream.Seek((long)(footer.DiskType == TYPE_FIXED ? footer.OriginalSize : 0), SeekOrigin.Begin);
            _writingStream.Write(footerBytes, 0, 512);

            _writingStream.Flush();
            _writingStream.Close();

            IsWriting    = false;
            ErrorMessage = "";

            return(true);
        }
        /// <summary>
        ///     Opens the device for sending direct commands
        /// </summary>
        /// <param name="devicePath">Device path</param>
        public Device(string devicePath)
        {
            PlatformId  = DetectOS.GetRealPlatformID();
            Timeout     = 15;
            Error       = false;
            IsRemovable = false;

            switch (PlatformId)
            {
            case PlatformID.Win32NT:
            {
                FileHandle = Extern.CreateFile(devicePath, FileAccess.GenericRead | FileAccess.GenericWrite,
                                               FileShare.Read | FileShare.Write, IntPtr.Zero,
                                               FileMode.OpenExisting,
                                               FileAttributes.Normal, IntPtr.Zero);

                if (((SafeFileHandle)FileHandle).IsInvalid)
                {
                    Error     = true;
                    LastError = Marshal.GetLastWin32Error();
                }

                break;
            }

            case PlatformID.Linux:
            {
                FileHandle =
                    Linux.Extern.open(devicePath,
                                      FileFlags.ReadWrite | FileFlags.NonBlocking | FileFlags.CreateNew);

                if ((int)FileHandle < 0)
                {
                    LastError = Marshal.GetLastWin32Error();

                    if (LastError == 13 || LastError == 30)    // EACCES or EROFS
                    {
                        FileHandle = Linux.Extern.open(devicePath, FileFlags.Readonly | FileFlags.NonBlocking);
                        if ((int)FileHandle < 0)
                        {
                            Error     = true;
                            LastError = Marshal.GetLastWin32Error();
                        }
                    }
                    else
                    {
                        Error = true;
                    }

                    LastError = Marshal.GetLastWin32Error();
                }

                break;
            }

            case PlatformID.FreeBSD:
            {
                FileHandle = FreeBSD.Extern.cam_open_device(devicePath, FreeBSD.FileFlags.ReadWrite);

                if (((IntPtr)FileHandle).ToInt64() == 0)
                {
                    Error     = true;
                    LastError = Marshal.GetLastWin32Error();
                }

                CamDevice camDevice = (CamDevice)Marshal.PtrToStructure((IntPtr)FileHandle, typeof(CamDevice));

                if (StringHandlers.CToString(camDevice.SimName) == "ata")
                {
                    throw new
                          InvalidOperationException("Parallel ATA devices are not supported on FreeBSD due to upstream bug #224250.");
                }

                break;
            }

            default: throw new InvalidOperationException($"Platform {PlatformId} not yet supported.");
            }

            if (Error)
            {
                throw new SystemException($"Error {LastError} opening device.");
            }

            Type     = DeviceType.Unknown;
            ScsiType = PeripheralDeviceTypes.UnknownDevice;

            byte[] ataBuf;
            byte[] inqBuf = null;

            if (Error)
            {
                throw new SystemException($"Error {LastError} trying device.");
            }

            bool scsiSense = true;

            // Windows is answering SCSI INQUIRY for all device types so it needs to be detected first
            switch (PlatformId)
            {
            case PlatformID.Win32NT:
                StoragePropertyQuery query = new StoragePropertyQuery();
                query.PropertyId           = StoragePropertyId.Device;
                query.QueryType            = StorageQueryType.Standard;
                query.AdditionalParameters = new byte[1];

                IntPtr descriptorPtr = Marshal.AllocHGlobal(1000);
                byte[] descriptorB   = new byte[1000];

                uint returned = 0;
                int  error    = 0;

                bool hasError = !Extern.DeviceIoControlStorageQuery((SafeFileHandle)FileHandle,
                                                                    WindowsIoctl.IoctlStorageQueryProperty,
                                                                    ref query, (uint)Marshal.SizeOf(query),
                                                                    descriptorPtr, 1000, ref returned, IntPtr.Zero);

                if (hasError)
                {
                    error = Marshal.GetLastWin32Error();
                }

                Marshal.Copy(descriptorPtr, descriptorB, 0, 1000);

                if (!hasError && error == 0)
                {
                    StorageDeviceDescriptor descriptor = new StorageDeviceDescriptor
                    {
                        Version               = BitConverter.ToUInt32(descriptorB, 0),
                        Size                  = BitConverter.ToUInt32(descriptorB, 4),
                        DeviceType            = descriptorB[8],
                        DeviceTypeModifier    = descriptorB[9],
                        RemovableMedia        = descriptorB[10] > 0,
                        CommandQueueing       = descriptorB[11] > 0,
                        VendorIdOffset        = BitConverter.ToInt32(descriptorB, 12),
                        ProductIdOffset       = BitConverter.ToInt32(descriptorB, 16),
                        ProductRevisionOffset = BitConverter.ToInt32(descriptorB, 20),
                        SerialNumberOffset    = BitConverter.ToInt32(descriptorB, 24),
                        BusType               = (StorageBusType)BitConverter.ToUInt32(descriptorB, 28),
                        RawPropertiesLength   = BitConverter.ToUInt32(descriptorB, 32)
                    };
                    descriptor.RawDeviceProperties = new byte[descriptor.RawPropertiesLength];
                    Array.Copy(descriptorB, 36, descriptor.RawDeviceProperties, 0, descriptor.RawPropertiesLength);

                    switch (descriptor.BusType)
                    {
                    case StorageBusType.SCSI:
                    case StorageBusType.SSA:
                    case StorageBusType.Fibre:
                    case StorageBusType.iSCSI:
                    case StorageBusType.SAS:
                        Type = DeviceType.SCSI;
                        break;

                    case StorageBusType.FireWire:
                        IsFireWire = true;
                        Type       = DeviceType.SCSI;
                        break;

                    case StorageBusType.USB:
                        IsUsb = true;
                        Type  = DeviceType.SCSI;
                        break;

                    case StorageBusType.ATAPI:
                        Type = DeviceType.ATAPI;
                        break;

                    case StorageBusType.ATA:
                    case StorageBusType.SATA:
                        Type = DeviceType.ATA;
                        break;

                    case StorageBusType.MultiMediaCard:
                        Type = DeviceType.MMC;
                        break;

                    case StorageBusType.SecureDigital:
                        Type = DeviceType.SecureDigital;
                        break;

                    case StorageBusType.NVMe:
                        Type = DeviceType.NVMe;
                        break;
                    }

                    switch (Type)
                    {
                    case DeviceType.SCSI:
                    case DeviceType.ATAPI:
                        scsiSense = ScsiInquiry(out inqBuf, out _);
                        break;

                    case DeviceType.ATA:
                        bool atapiSense = AtapiIdentify(out ataBuf, out _);

                        if (!atapiSense)
                        {
                            Type = DeviceType.ATAPI;
                            Identify.IdentifyDevice?ataid = Identify.Decode(ataBuf);

                            if (ataid.HasValue)
                            {
                                scsiSense = ScsiInquiry(out inqBuf, out _);
                            }
                        }
                        else
                        {
                            Manufacturer = "ATA";
                        }

                        break;
                    }
                }

                Marshal.FreeHGlobal(descriptorPtr);

                if (Windows.Command.IsSdhci((SafeFileHandle)FileHandle))
                {
                    byte[] sdBuffer = new byte[16];

                    LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle, MmcCommands.SendCsd,
                                                               false, false,
                                                               MmcFlags.ResponseSpiR2 | MmcFlags.ResponseR2 |
                                                               MmcFlags.CommandAc, 0, 16, 1, ref sdBuffer, out _,
                                                               out _, out bool sense);

                    if (!sense)
                    {
                        cachedCsd = new byte[16];
                        Array.Copy(sdBuffer, 0, cachedCsd, 0, 16);
                    }

                    sdBuffer = new byte[16];

                    LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle, MmcCommands.SendCid,
                                                               false, false,
                                                               MmcFlags.ResponseSpiR2 | MmcFlags.ResponseR2 |
                                                               MmcFlags.CommandAc, 0, 16, 1, ref sdBuffer, out _,
                                                               out _, out sense);

                    if (!sense)
                    {
                        cachedCid = new byte[16];
                        Array.Copy(sdBuffer, 0, cachedCid, 0, 16);
                    }

                    sdBuffer = new byte[8];

                    LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle,
                                                               (MmcCommands)SecureDigitalCommands.SendScr, false,
                                                               true,
                                                               MmcFlags.ResponseSpiR1 | MmcFlags.ResponseR1 |
                                                               MmcFlags.CommandAdtc, 0, 8, 1, ref sdBuffer, out _,
                                                               out _, out sense);

                    if (!sense)
                    {
                        cachedScr = new byte[8];
                        Array.Copy(sdBuffer, 0, cachedScr, 0, 8);
                    }

                    if (cachedScr != null)
                    {
                        sdBuffer = new byte[4];

                        LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle,
                                                                   (MmcCommands)SecureDigitalCommands
                                                                   .SendOperatingCondition, false, true,
                                                                   MmcFlags.ResponseSpiR3 | MmcFlags.ResponseR3 |
                                                                   MmcFlags.CommandBcr, 0, 4, 1, ref sdBuffer,
                                                                   out _, out _, out sense);

                        if (!sense)
                        {
                            cachedScr = new byte[4];
                            Array.Copy(sdBuffer, 0, cachedScr, 0, 4);
                        }
                    }
                    else
                    {
                        sdBuffer = new byte[4];

                        LastError = Windows.Command.SendMmcCommand((SafeFileHandle)FileHandle,
                                                                   MmcCommands.SendOpCond, false, true,
                                                                   MmcFlags.ResponseSpiR3 | MmcFlags.ResponseR3 |
                                                                   MmcFlags.CommandBcr, 0, 4, 1, ref sdBuffer,
                                                                   out _, out _, out sense);

                        if (!sense)
                        {
                            cachedScr = new byte[4];
                            Array.Copy(sdBuffer, 0, cachedScr, 0, 4);
                        }
                    }
                }

                break;

            case PlatformID.Linux:
                if (devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
                    devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
                    devicePath.StartsWith("/dev/st", StringComparison.Ordinal))
                {
                    scsiSense = ScsiInquiry(out inqBuf, out _);
                }
                // MultiMediaCard and SecureDigital go here
                else if (devicePath.StartsWith("/dev/mmcblk", StringComparison.Ordinal))
                {
                    string devPath = devicePath.Substring(5);
                    if (File.Exists("/sys/block/" + devPath + "/device/csd"))
                    {
                        int len =
                            ConvertFromHexAscii("/sys/block/" + devPath + "/device/csd", out cachedCsd);
                        if (len == 0)
                        {
                            cachedCsd = null;
                        }
                    }

                    if (File.Exists("/sys/block/" + devPath + "/device/cid"))
                    {
                        int len =
                            ConvertFromHexAscii("/sys/block/" + devPath + "/device/cid", out cachedCid);
                        if (len == 0)
                        {
                            cachedCid = null;
                        }
                    }

                    if (File.Exists("/sys/block/" + devPath + "/device/scr"))
                    {
                        int len =
                            ConvertFromHexAscii("/sys/block/" + devPath + "/device/scr", out cachedScr);
                        if (len == 0)
                        {
                            cachedScr = null;
                        }
                    }

                    if (File.Exists("/sys/block/" + devPath + "/device/ocr"))
                    {
                        int len =
                            ConvertFromHexAscii("/sys/block/" + devPath + "/device/ocr", out cachedOcr);
                        if (len == 0)
                        {
                            cachedOcr = null;
                        }
                    }
                }

                break;

            default:
                scsiSense = ScsiInquiry(out inqBuf, out _);
                break;
            }

            #region SecureDigital / MultiMediaCard
            if (cachedCid != null)
            {
                ScsiType    = PeripheralDeviceTypes.DirectAccess;
                IsRemovable = false;

                if (cachedScr != null)
                {
                    Type = DeviceType.SecureDigital;
                    CID decoded = Decoders.SecureDigital.Decoders.DecodeCID(cachedCid);
                    Manufacturer = VendorString.Prettify(decoded.Manufacturer);
                    Model        = decoded.ProductName;
                    Revision     = $"{(decoded.ProductRevision & 0xF0) >> 4:X2}.{decoded.ProductRevision & 0x0F:X2}";
                    Serial       = $"{decoded.ProductSerialNumber}";
                }
                else
                {
                    Type = DeviceType.MMC;
                    Decoders.MMC.CID decoded = Decoders.MMC.Decoders.DecodeCID(cachedCid);
                    Manufacturer = Decoders.MMC.VendorString.Prettify(decoded.Manufacturer);
                    Model        = decoded.ProductName;
                    Revision     = $"{(decoded.ProductRevision & 0xF0) >> 4:X2}.{decoded.ProductRevision & 0x0F:X2}";
                    Serial       = $"{decoded.ProductSerialNumber}";
                }
            }
            #endregion SecureDigital / MultiMediaCard

            #region USB
            switch (PlatformId)
            {
            case PlatformID.Linux:
                if (devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
                    devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
                    devicePath.StartsWith("/dev/st", StringComparison.Ordinal))
                {
                    string devPath = devicePath.Substring(5);
                    if (Directory.Exists("/sys/block/" + devPath))
                    {
                        string resolvedLink = Linux.Command.ReadLink("/sys/block/" + devPath);
                        resolvedLink = "/sys" + resolvedLink.Substring(2);
                        if (!string.IsNullOrEmpty(resolvedLink))
                        {
                            while (resolvedLink.Contains("usb"))
                            {
                                resolvedLink = Path.GetDirectoryName(resolvedLink);
                                if (!File.Exists(resolvedLink + "/descriptors") ||
                                    !File.Exists(resolvedLink + "/idProduct") ||
                                    !File.Exists(resolvedLink + "/idVendor"))
                                {
                                    continue;
                                }

                                FileStream usbFs = new FileStream(resolvedLink + "/descriptors",
                                                                  System.IO.FileMode.Open,
                                                                  System.IO.FileAccess.Read);
                                byte[] usbBuf   = new byte[65536];
                                int    usbCount = usbFs.Read(usbBuf, 0, 65536);
                                UsbDescriptors = new byte[usbCount];
                                Array.Copy(usbBuf, 0, UsbDescriptors, 0, usbCount);
                                usbFs.Close();

                                StreamReader usbSr   = new StreamReader(resolvedLink + "/idProduct");
                                string       usbTemp = usbSr.ReadToEnd();
                                ushort.TryParse(usbTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
                                                out usbProduct);
                                usbSr.Close();

                                usbSr   = new StreamReader(resolvedLink + "/idVendor");
                                usbTemp = usbSr.ReadToEnd();
                                ushort.TryParse(usbTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
                                                out usbVendor);
                                usbSr.Close();

                                if (File.Exists(resolvedLink + "/manufacturer"))
                                {
                                    usbSr = new StreamReader(resolvedLink + "/manufacturer");
                                    UsbManufacturerString = usbSr.ReadToEnd().Trim();
                                    usbSr.Close();
                                }

                                if (File.Exists(resolvedLink + "/product"))
                                {
                                    usbSr            = new StreamReader(resolvedLink + "/product");
                                    UsbProductString = usbSr.ReadToEnd().Trim();
                                    usbSr.Close();
                                }

                                if (File.Exists(resolvedLink + "/serial"))
                                {
                                    usbSr           = new StreamReader(resolvedLink + "/serial");
                                    UsbSerialString = usbSr.ReadToEnd().Trim();
                                    usbSr.Close();
                                }

                                IsUsb = true;
                                break;
                            }
                        }
                    }
                }

                break;

            case PlatformID.Win32NT:
                Usb.UsbDevice usbDevice = null;

                // I have to search for USB disks, floppies and CD-ROMs as separate device types
                foreach (string devGuid in new[]
                {
                    Usb.GuidDevinterfaceFloppy, Usb.GuidDevinterfaceCdrom, Usb.GuidDevinterfaceDisk
                })
                {
                    usbDevice = Usb.FindDrivePath(devicePath, devGuid);
                    if (usbDevice != null)
                    {
                        break;
                    }
                }

                if (usbDevice != null)
                {
                    UsbDescriptors        = usbDevice.BinaryDescriptors;
                    usbVendor             = (ushort)usbDevice.DeviceDescriptor.idVendor;
                    usbProduct            = (ushort)usbDevice.DeviceDescriptor.idProduct;
                    UsbManufacturerString = usbDevice.Manufacturer;
                    UsbProductString      = usbDevice.Product;
                    UsbSerialString       =
                        usbDevice.SerialNumber;     // This is incorrect filled by Windows with SCSI/ATA serial number
                }

                break;

            default:
                IsUsb = false;
                break;
            }
            #endregion USB

            #region FireWire
            if (PlatformId == PlatformID.Linux)
            {
                if (devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
                    devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
                    devicePath.StartsWith("/dev/st", StringComparison.Ordinal))
                {
                    string devPath = devicePath.Substring(5);
                    if (Directory.Exists("/sys/block/" + devPath))
                    {
                        string resolvedLink = Linux.Command.ReadLink("/sys/block/" + devPath);
                        resolvedLink = "/sys" + resolvedLink.Substring(2);
                        if (!string.IsNullOrEmpty(resolvedLink))
                        {
                            while (resolvedLink.Contains("firewire"))
                            {
                                resolvedLink = Path.GetDirectoryName(resolvedLink);
                                if (!File.Exists(resolvedLink + "/model") || !File.Exists(resolvedLink + "/vendor") ||
                                    !File.Exists(resolvedLink + "/guid"))
                                {
                                    continue;
                                }

                                StreamReader fwSr   = new StreamReader(resolvedLink + "/model");
                                string       fwTemp = fwSr.ReadToEnd();
                                uint.TryParse(fwTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
                                              out firewireModel);
                                fwSr.Close();

                                fwSr   = new StreamReader(resolvedLink + "/vendor");
                                fwTemp = fwSr.ReadToEnd();
                                uint.TryParse(fwTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
                                              out firewireVendor);
                                fwSr.Close();

                                fwSr   = new StreamReader(resolvedLink + "/guid");
                                fwTemp = fwSr.ReadToEnd();
                                ulong.TryParse(fwTemp, NumberStyles.HexNumber, CultureInfo.InvariantCulture,
                                               out firewireGuid);
                                fwSr.Close();

                                if (File.Exists(resolvedLink + "/model_name"))
                                {
                                    fwSr = new StreamReader(resolvedLink + "/model_name");
                                    FireWireModelName = fwSr.ReadToEnd().Trim();
                                    fwSr.Close();
                                }

                                if (File.Exists(resolvedLink + "/vendor_name"))
                                {
                                    fwSr = new StreamReader(resolvedLink + "/vendor_name");
                                    FireWireVendorName = fwSr.ReadToEnd().Trim();
                                    fwSr.Close();
                                }

                                IsFireWire = true;
                                break;
                            }
                        }
                    }
                }
            }
            // TODO: Implement for other operating systems
            else
            {
                IsFireWire = false;
            }
            #endregion FireWire

            #region PCMCIA
            if (PlatformId == PlatformID.Linux)
            {
                if (devicePath.StartsWith("/dev/sd", StringComparison.Ordinal) ||
                    devicePath.StartsWith("/dev/sr", StringComparison.Ordinal) ||
                    devicePath.StartsWith("/dev/st", StringComparison.Ordinal))
                {
                    string devPath = devicePath.Substring(5);
                    if (Directory.Exists("/sys/block/" + devPath))
                    {
                        string resolvedLink = Linux.Command.ReadLink("/sys/block/" + devPath);
                        resolvedLink = "/sys" + resolvedLink.Substring(2);
                        if (!string.IsNullOrEmpty(resolvedLink))
                        {
                            while (resolvedLink.Contains("/sys/devices"))
                            {
                                resolvedLink = Path.GetDirectoryName(resolvedLink);
                                if (!Directory.Exists(resolvedLink + "/pcmcia_socket"))
                                {
                                    continue;
                                }

                                string[] subdirs = Directory.GetDirectories(resolvedLink + "/pcmcia_socket",
                                                                            "pcmcia_socket*",
                                                                            SearchOption.TopDirectoryOnly);

                                if (subdirs.Length <= 0)
                                {
                                    continue;
                                }

                                string possibleDir = Path.Combine(resolvedLink, "pcmcia_socket", subdirs[0]);
                                if (!File.Exists(possibleDir + "/card_type") || !File.Exists(possibleDir + "/cis"))
                                {
                                    continue;
                                }

                                FileStream cisFs = new FileStream(possibleDir + "/cis", System.IO.FileMode.Open,
                                                                  System.IO.FileAccess.Read);
                                byte[] cisBuf   = new byte[65536];
                                int    cisCount = cisFs.Read(cisBuf, 0, 65536);
                                Cis = new byte[cisCount];
                                Array.Copy(cisBuf, 0, Cis, 0, cisCount);
                                cisFs.Close();

                                IsPcmcia = true;
                                break;
                            }
                        }
                    }
                }
            }
            // TODO: Implement for other operating systems
            else
            {
                IsPcmcia = false;
            }
            #endregion PCMCIA

            if (!scsiSense)
            {
                Inquiry.SCSIInquiry?inquiry = Inquiry.Decode(inqBuf);

                Type = DeviceType.SCSI;
                bool serialSense = ScsiInquiry(out inqBuf, out _, 0x80);
                if (!serialSense)
                {
                    Serial = EVPD.DecodePage80(inqBuf);
                }

                if (inquiry.HasValue)
                {
                    string tmp = StringHandlers.CToString(inquiry.Value.ProductRevisionLevel);
                    if (tmp != null)
                    {
                        Revision = tmp.Trim();
                    }
                    tmp = StringHandlers.CToString(inquiry.Value.ProductIdentification);
                    if (tmp != null)
                    {
                        Model = tmp.Trim();
                    }
                    tmp = StringHandlers.CToString(inquiry.Value.VendorIdentification);
                    if (tmp != null)
                    {
                        Manufacturer = tmp.Trim();
                    }
                    IsRemovable = inquiry.Value.RMB;

                    ScsiType = (PeripheralDeviceTypes)inquiry.Value.PeripheralDeviceType;
                }

                bool atapiSense = AtapiIdentify(out ataBuf, out _);

                if (!atapiSense)
                {
                    Type = DeviceType.ATAPI;
                    Identify.IdentifyDevice?ataId = Identify.Decode(ataBuf);

                    if (ataId.HasValue)
                    {
                        Serial = ataId.Value.SerialNumber;
                    }
                }

                LastError = 0;
                Error     = false;
            }

            if (scsiSense && (IsUsb || IsFireWire) || Manufacturer == "ATA")
            {
                bool ataSense = AtaIdentify(out ataBuf, out _);
                if (!ataSense)
                {
                    Type = DeviceType.ATA;
                    Identify.IdentifyDevice?ataid = Identify.Decode(ataBuf);

                    if (ataid.HasValue)
                    {
                        string[] separated = ataid.Value.Model.Split(' ');

                        if (separated.Length == 1)
                        {
                            Model = separated[0];
                        }
                        else
                        {
                            Manufacturer = separated[0];
                            Model        = separated[separated.Length - 1];
                        }

                        Revision = ataid.Value.FirmwareRevision;
                        Serial   = ataid.Value.SerialNumber;

                        ScsiType = PeripheralDeviceTypes.DirectAccess;

                        if ((ushort)ataid.Value.GeneralConfiguration != 0x848A)
                        {
                            IsRemovable |=
                                (ataid.Value.GeneralConfiguration & Identify.GeneralConfigurationBit.Removable) ==
                                Identify.GeneralConfigurationBit.Removable;
                        }
                        else
                        {
                            IsCompactFlash = true;
                        }
                    }
                }
            }

            if (Type == DeviceType.Unknown)
            {
                Manufacturer = null;
                Model        = null;
                Revision     = null;
                Serial       = null;
            }

            if (IsUsb)
            {
                if (string.IsNullOrEmpty(Manufacturer))
                {
                    Manufacturer = UsbManufacturerString;
                }
                if (string.IsNullOrEmpty(Model))
                {
                    Model = UsbProductString;
                }
                if (string.IsNullOrEmpty(Serial))
                {
                    Serial = UsbSerialString;
                }
                else
                {
                    foreach (char c in Serial.Where(char.IsControl))
                    {
                        Serial = UsbSerialString;
                    }
                }
            }

            if (IsFireWire)
            {
                if (string.IsNullOrEmpty(Manufacturer))
                {
                    Manufacturer = FireWireVendorName;
                }
                if (string.IsNullOrEmpty(Model))
                {
                    Model = FireWireModelName;
                }
                if (string.IsNullOrEmpty(Serial))
                {
                    Serial = $"{firewireGuid:X16}";
                }
                else
                {
                    foreach (char c in Serial.Where(char.IsControl))
                    {
                        Serial = $"{firewireGuid:X16}";
                    }
                }
            }

            // Some optical drives are not getting the correct serial, and IDENTIFY PACKET DEVICE is blocked without
            // administrator privileges
            if (ScsiType != PeripheralDeviceTypes.MultiMediaDevice)
            {
                return;
            }

            bool featureSense = GetConfiguration(out byte[] featureBuffer, out _, 0x0108, MmcGetConfigurationRt.Single,
                                                 Timeout, out _);

            if (featureSense)
            {
                return;
            }

            Features.SeparatedFeatures features = Features.Separate(featureBuffer);
            if (features.Descriptors?.Length != 1 || features.Descriptors[0].Code != 0x0108)
            {
                return;
            }

            Feature_0108?serialFeature = Features.Decode_0108(features.Descriptors[0].Data);

            if (serialFeature is null)
            {
                return;
            }

            Serial = serialFeature.Value.Serial;
        }
Exemple #29
0
        /// <summary>Initializes the dump log</summary>
        /// <param name="outputFile">Output log file</param>
        /// <param name="dev">Device</param>
        public DumpLog(string outputFile, Device dev)
        {
            if (string.IsNullOrEmpty(outputFile))
            {
                return;
            }

            logSw = new StreamWriter(outputFile, true);

            logSw.WriteLine("Start logging at {0}", DateTime.Now);

            PlatformID platId  = DetectOS.GetRealPlatformID();
            string     platVer = DetectOS.GetVersion();

            var assemblyVersion =
                Attribute.GetCustomAttribute(typeof(DumpLog).Assembly, typeof(AssemblyInformationalVersionAttribute)) as
                AssemblyInformationalVersionAttribute;

            logSw.WriteLine("################# System information #################");

            logSw.WriteLine("{0} {1} ({2}-bit)", DetectOS.GetPlatformName(platId, platVer), platVer,
                            Environment.Is64BitOperatingSystem ? 64 : 32);

            if (DetectOS.IsMono)
            {
                logSw.WriteLine("Mono {0}", Version.GetMonoVersion());
            }
            else if (DetectOS.IsNetCore)
            {
                logSw.WriteLine(".NET Core {0}", Version.GetNetCoreVersion());
            }
            else
            {
                logSw.WriteLine(RuntimeInformation.FrameworkDescription);
            }

            logSw.WriteLine();

            logSw.WriteLine("################# Program information ################");
            logSw.WriteLine("DiscImageChef {0}", assemblyVersion?.InformationalVersion);
            logSw.WriteLine("Running in {0}-bit", Environment.Is64BitProcess ? 64 : 32);
        #if DEBUG
            logSw.WriteLine("DEBUG version");
        #endif
            logSw.WriteLine("Command line: {0}", Environment.CommandLine);
            logSw.WriteLine();

            if (dev.IsRemote)
            {
                logSw.WriteLine("################# Remote information #################");
                logSw.WriteLine("Server: {0}", dev.RemoteApplication);
                logSw.WriteLine("Version: {0}", dev.RemoteVersion);

                logSw.WriteLine("Operating system: {0} {1}", dev.RemoteOperatingSystem,
                                dev.RemoteOperatingSystemVersion);

                logSw.WriteLine("Architecture: {0}", dev.RemoteArchitecture);
                logSw.WriteLine("Protocol version: {0}", dev.RemoteProtocolVersion);
                logSw.WriteLine("######################################################");
            }

            logSw.WriteLine("################# Device information #################");
            logSw.WriteLine("Manufacturer: {0}", dev.Manufacturer);
            logSw.WriteLine("Model: {0}", dev.Model);
            logSw.WriteLine("Firmware revision: {0}", dev.FirmwareRevision);
            logSw.WriteLine("Serial number: {0}", dev.Serial);
            logSw.WriteLine("Removable device: {0}", dev.IsRemovable);
            logSw.WriteLine("Device type: {0}", dev.Type);
            logSw.WriteLine("CompactFlash device: {0}", dev.IsCompactFlash);
            logSw.WriteLine("PCMCIA device: {0}", dev.IsPcmcia);
            logSw.WriteLine("USB device: {0}", dev.IsUsb);

            if (dev.IsUsb)
            {
                logSw.WriteLine("USB manufacturer: {0}", dev.UsbManufacturerString);
                logSw.WriteLine("USB product: {0}", dev.UsbProductString);
                logSw.WriteLine("USB serial: {0}", dev.UsbSerialString);
                logSw.WriteLine("USB vendor ID: {0:X4}h", dev.UsbVendorId);
                logSw.WriteLine("USB product ID: {0:X4}h", dev.UsbProductId);
            }

            logSw.WriteLine("FireWire device: {0}", dev.IsFireWire);

            if (dev.IsFireWire)
            {
                logSw.WriteLine("FireWire vendor: {0}", dev.FireWireVendorName);
                logSw.WriteLine("FireWire model: {0}", dev.FireWireModelName);
                logSw.WriteLine("FireWire GUID: 0x{0:X16}", dev.FireWireGuid);
                logSw.WriteLine("FireWire vendor ID: 0x{0:X8}", dev.FireWireVendor);
                logSw.WriteLine("FireWire product ID: 0x{0:X8}", dev.FireWireModel);
            }

            logSw.WriteLine("######################################################");

            logSw.WriteLine();
            logSw.WriteLine("################ Dumping progress log ################");
            logSw.Flush();
        }
Exemple #30
0
        public static void LoadSettings()
        {
            Current = new SetSettings();
            PlatformID ptId = DetectOS.GetRealPlatformID();

            FileStream   prefsFs = null;
            StreamReader prefsSr = null;

            try
            {
                switch (ptId)
                {
                case PlatformID.MacOSX:
                case PlatformID.iOS:
                {
                    string preferencesPath =
                        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library",
                                     "Preferences");

                    string preferencesFilePath =
                        Path.Combine(preferencesPath, "com.claunia.museum.apprepodbmgr.plist");

                    if (!File.Exists(preferencesFilePath))
                    {
                        SetDefaultSettings();
                        SaveSettings();
                    }

                    prefsFs = new FileStream(preferencesFilePath, FileMode.Open);
                    var parsedPreferences = (NSDictionary)BinaryPropertyListParser.Parse(prefsFs);

                    if (parsedPreferences != null)
                    {
                        Current.TemporaryFolder = parsedPreferences.TryGetValue("TemporaryFolder", out NSObject obj)
                                                          ? ((NSString)obj).ToString() : Path.GetTempPath();

                        Current.DatabasePath = parsedPreferences.TryGetValue("DatabasePath", out obj)
                                                       ? ((NSString)obj).ToString()
                                                       : Path.
                                               Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                                                       "apprepodbmgr.db");

                        Current.RepositoryPath = parsedPreferences.TryGetValue("RepositoryPath", out obj)
                                                         ? ((NSString)obj).ToString()
                                                         : Path.
                                                 Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                                                         "apprepo");

                        Current.UnArchiverPath = parsedPreferences.TryGetValue("UnArchiverPath", out obj)
                                                         ? ((NSString)obj).ToString() : null;

                        if (parsedPreferences.TryGetValue("CompressionAlgorithm", out obj))
                        {
                            if (!Enum.TryParse(((NSString)obj).ToString(), true, out Current.CompressionAlgorithm))
                            {
                                Current.CompressionAlgorithm = AlgoEnum.GZip;
                            }
                        }
                        else
                        {
                            Current.CompressionAlgorithm = AlgoEnum.GZip;
                        }

                        Current.UseAntivirus = parsedPreferences.TryGetValue("UseAntivirus", out obj) &&
                                               ((NSNumber)obj).ToBool();

                        Current.UseClamd = parsedPreferences.TryGetValue("UseClamd", out obj) &&
                                           ((NSNumber)obj).ToBool();

                        Current.ClamdHost = parsedPreferences.TryGetValue("ClamdHost", out obj)
                                                    ? ((NSString)obj).ToString() : null;

                        if (parsedPreferences.TryGetValue("ClamdPort", out obj))
                        {
                            Current.ClamdPort = (ushort)((NSNumber)obj).ToLong();
                        }
                        else
                        {
                            Current.ClamdPort = 3310;
                        }

                        Current.ClamdIsLocal = parsedPreferences.TryGetValue("ClamdIsLocal", out obj) &&
                                               ((NSNumber)obj).ToBool();

                        Current.ClamdIsLocal = parsedPreferences.TryGetValue("UseVirusTotal", out obj) &&
                                               ((NSNumber)obj).ToBool();

                        Current.ClamdHost = parsedPreferences.TryGetValue("VirusTotalKey", out obj)
                                                    ? ((NSString)obj).ToString() : null;

                        prefsFs.Close();
                    }
                    else
                    {
                        prefsFs.Close();

                        SetDefaultSettings();
                        SaveSettings();
                    }
                }

                break;

                case PlatformID.Win32NT:
                case PlatformID.Win32S:
                case PlatformID.Win32Windows:
                case PlatformID.WinCE:
                case PlatformID.WindowsPhone:
                {
                    RegistryKey parentKey = Registry.CurrentUser.OpenSubKey("SOFTWARE")?.
                                            OpenSubKey("Canary Islands Computer Museum");

                    if (parentKey == null)
                    {
                        SetDefaultSettings();
                        SaveSettings();

                        return;
                    }

                    RegistryKey key = parentKey.OpenSubKey("AppRepoDBMgr");

                    if (key == null)
                    {
                        SetDefaultSettings();
                        SaveSettings();

                        return;
                    }

                    Current.TemporaryFolder = (string)key.GetValue("TemporaryFolder");
                    Current.DatabasePath    = (string)key.GetValue("DatabasePath");
                    Current.RepositoryPath  = (string)key.GetValue("RepositoryPath");
                    Current.UnArchiverPath  = (string)key.GetValue("UnArchiverPath");

                    if (!Enum.TryParse((string)key.GetValue("CompressionAlgorithm"), true,
                                       out Current.CompressionAlgorithm))
                    {
                        Current.CompressionAlgorithm = AlgoEnum.GZip;
                    }

                    Current.UseAntivirus  = bool.Parse((string)key.GetValue("UseAntivirus"));
                    Current.UseClamd      = bool.Parse((string)key.GetValue("UseClamd"));
                    Current.ClamdHost     = (string)key.GetValue("ClamdHost");
                    Current.ClamdPort     = ushort.Parse((string)key.GetValue("ClamdPort"));
                    Current.ClamdIsLocal  = bool.Parse((string)key.GetValue("ClamdIsLocal"));
                    Current.UseVirusTotal = bool.Parse((string)key.GetValue("UseVirusTotal"));
                    Current.VirusTotalKey = (string)key.GetValue("VirusTotalKey");
                }

                break;

                default:
                {
                    string configPath =
                        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config");

                    string settingsPath = Path.Combine(configPath, "AppRepoDBMgr.xml");

                    if (!Directory.Exists(configPath))
                    {
                        SetDefaultSettings();
                        SaveSettings();

                        return;
                    }

                    var xs = new XmlSerializer(Current.GetType());
                    prefsSr = new StreamReader(settingsPath);
                    Current = (SetSettings)xs.Deserialize(prefsSr);
                    prefsSr.Close();
                }

                break;
                }
            }
            catch
            {
                prefsFs?.Close();
                prefsSr?.Close();

                SetDefaultSettings();
                SaveSettings();
            }
        }