Beispiel #1
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]);
            }
        }
Beispiel #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()
 };
Beispiel #3
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));
        }
Beispiel #4
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]);
            }
        }
Beispiel #5
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;
     }
 }
Beispiel #6
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));
        }
Beispiel #7
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));
        }
Beispiel #8
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");
        }
Beispiel #9
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]);
            }
        }
Beispiel #10
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.");
            }
        }
Beispiel #11
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);
        }
        /// <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;
        }
Beispiel #13
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);
        }
        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();
        }
Beispiel #15
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;
                }
            }
Beispiel #16
0
        /// <summary>
        ///     Loads settings
        /// </summary>
        public static void LoadSettings()
        {
            Current = new DicSettings();
            PlatformID ptId     = DetectOS.GetRealPlatformID();
            string     homePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

            try
            {
                switch (ptId)
                {
                // In case of macOS or iOS statistics and reports will be saved in ~/Library/Application Support/Claunia.com/DiscImageChef
                case PlatformID.MacOSX:
                case PlatformID.iOS:
                {
                    string appSupportPath =
                        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library",
                                     "Application Support", "Claunia.com");
                    if (!Directory.Exists(appSupportPath))
                    {
                        Directory.CreateDirectory(appSupportPath);
                    }

                    string dicPath = Path.Combine(appSupportPath, "DiscImageChef");
                    if (!Directory.Exists(dicPath))
                    {
                        Directory.CreateDirectory(dicPath);
                    }

                    ReportsPath = Path.Combine(dicPath, "Reports");
                    if (!Directory.Exists(ReportsPath))
                    {
                        Directory.CreateDirectory(ReportsPath);
                    }

                    StatsPath = Path.Combine(dicPath, "Statistics");
                    if (!Directory.Exists(StatsPath))
                    {
                        Directory.CreateDirectory(StatsPath);
                    }
                }
                break;

                // In case of Windows statistics and reports will be saved in %APPDATA%\Claunia.com\DiscImageChef
                case PlatformID.Win32NT:
                case PlatformID.Win32S:
                case PlatformID.Win32Windows:
                case PlatformID.WinCE:
                case PlatformID.WindowsPhone:
                {
                    string appSupportPath =
                        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                                     "Claunia.com");
                    if (!Directory.Exists(appSupportPath))
                    {
                        Directory.CreateDirectory(appSupportPath);
                    }

                    string dicPath = Path.Combine(appSupportPath, "DiscImageChef");
                    if (!Directory.Exists(dicPath))
                    {
                        Directory.CreateDirectory(dicPath);
                    }

                    ReportsPath = Path.Combine(dicPath, "Reports");
                    if (!Directory.Exists(ReportsPath))
                    {
                        Directory.CreateDirectory(ReportsPath);
                    }

                    StatsPath = Path.Combine(dicPath, "Statistics");
                    if (!Directory.Exists(StatsPath))
                    {
                        Directory.CreateDirectory(StatsPath);
                    }
                }
                break;

                // Otherwise, statistics and reports will be saved in ~/.claunia.com/DiscImageChef
                default:
                {
                    string xdgDataPath =
                        Path.Combine(homePath,
                                     Environment.GetEnvironmentVariable(XDG_DATA_HOME) ?? XDG_DATA_HOME_RESOLVED);

                    string oldDicPath = Path.Combine(homePath, ".claunia.com", "DiscImageChef");
                    string dicPath    = Path.Combine(xdgDataPath, "DiscImageChef");

                    if (Directory.Exists(oldDicPath) && !Directory.Exists(dicPath))
                    {
                        Directory.Move(oldDicPath, dicPath);
                        Directory.Delete(Path.Combine(homePath, ".claunia.com"));
                    }

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

                    ReportsPath = Path.Combine(dicPath, "Reports");
                    if (!Directory.Exists(ReportsPath))
                    {
                        Directory.CreateDirectory(ReportsPath);
                    }

                    StatsPath = Path.Combine(dicPath, "Statistics");
                    if (!Directory.Exists(StatsPath))
                    {
                        Directory.CreateDirectory(StatsPath);
                    }
                }
                break;
                }
            }
            catch { ReportsPath = null; }

            FileStream   prefsFs = null;
            StreamReader prefsSr = null;

            try
            {
                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:
                {
                    string preferencesPath =
                        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library",
                                     "Preferences");
                    string preferencesFilePath = Path.Combine(preferencesPath, "com.claunia.discimagechef.plist");

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

                    prefsFs = new FileStream(preferencesFilePath, FileMode.Open, FileAccess.Read);

                    NSDictionary parsedPreferences = (NSDictionary)BinaryPropertyListParser.Parse(prefsFs);
                    if (parsedPreferences != null)
                    {
                        Current.SaveReportsGlobally =
                            parsedPreferences.TryGetValue("SaveReportsGlobally", out NSObject obj) &&
                            ((NSNumber)obj).ToBool();

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

                        if (parsedPreferences.TryGetValue("Stats", out obj))
                        {
                            NSDictionary stats = (NSDictionary)obj;

                            if (stats != null)
                            {
                                Current.Stats = new StatsSettings
                                {
                                    ShareStats =
                                        stats.TryGetValue("ShareStats", out NSObject obj2) &&
                                        ((NSNumber)obj2).ToBool(),
                                    BenchmarkStats =
                                        stats.TryGetValue("BenchmarkStats", out obj2) && ((NSNumber)obj2).ToBool(),
                                    CommandStats =
                                        stats.TryGetValue("CommandStats", out obj2) && ((NSNumber)obj2).ToBool(),
                                    DeviceStats =
                                        stats.TryGetValue("DeviceStats", out obj2) && ((NSNumber)obj2).ToBool(),
                                    FilesystemStats =
                                        stats.TryGetValue("FilesystemStats", out obj2) && ((NSNumber)obj2).ToBool(),
                                    FilterStats =
                                        stats.TryGetValue("FilterStats", out obj2) && ((NSNumber)obj2).ToBool(),
                                    MediaImageStats =
                                        stats.TryGetValue("MediaImageStats", out obj2) && ((NSNumber)obj2).ToBool(),
                                    MediaScanStats =
                                        stats.TryGetValue("MediaScanStats", out obj2) && ((NSNumber)obj2).ToBool(),
                                    PartitionStats =
                                        stats.TryGetValue("PartitionStats", out obj2) && ((NSNumber)obj2).ToBool(),
                                    MediaStats =
                                        stats.TryGetValue("MediaStats", out obj2) && ((NSNumber)obj2).ToBool(),
                                    VerifyStats =
                                        stats.TryGetValue("VerifyStats", out obj2) && ((NSNumber)obj2).ToBool()
                                }
                            }
                            ;
                        }
                        else
                        {
                            Current.Stats = null;
                        }

                        Current.GdprCompliance = parsedPreferences.TryGetValue("GdprCompliance", out obj)
                                                         ? (ulong)((NSNumber)obj).ToLong()
                                                         : 0;

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

                        SetDefaultSettings();
                        SaveSettings();
                    }
                }
                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")?.OpenSubKey("Claunia.com");
                    if (parentKey == null)
                    {
                        SetDefaultSettings();
                        SaveSettings();
                        return;
                    }

                    RegistryKey key = parentKey.OpenSubKey("DiscImageChef");
                    if (key == null)
                    {
                        SetDefaultSettings();
                        SaveSettings();
                        return;
                    }

                    Current.SaveReportsGlobally = Convert.ToBoolean(key.GetValue("SaveReportsGlobally"));
                    Current.ShareReports        = Convert.ToBoolean(key.GetValue("ShareReports"));
                    Current.GdprCompliance      = Convert.ToUInt64(key.GetValue("GdprCompliance"));

                    bool stats = Convert.ToBoolean(key.GetValue("Statistics"));
                    if (stats)
                    {
                        Current.Stats = new StatsSettings
                        {
                            ShareStats      = Convert.ToBoolean(key.GetValue("ShareStats")),
                            BenchmarkStats  = Convert.ToBoolean(key.GetValue("BenchmarkStats")),
                            CommandStats    = Convert.ToBoolean(key.GetValue("CommandStats")),
                            DeviceStats     = Convert.ToBoolean(key.GetValue("DeviceStats")),
                            FilesystemStats = Convert.ToBoolean(key.GetValue("FilesystemStats")),
                            FilterStats     = Convert.ToBoolean(key.GetValue("FilterStats")),
                            MediaImageStats = Convert.ToBoolean(key.GetValue("MediaImageStats")),
                            MediaScanStats  = Convert.ToBoolean(key.GetValue("MediaScanStats")),
                            PartitionStats  = Convert.ToBoolean(key.GetValue("PartitionStats")),
                            MediaStats      = Convert.ToBoolean(key.GetValue("MediaStats")),
                            VerifyStats     = Convert.ToBoolean(key.GetValue("VerifyStats"))
                        }
                    }
                    ;
                }

                break;
#endif
                // Otherwise, settings will be saved in ~/.config/DiscImageChef.xml
                default:
                {
                    string oldConfigPath =
                        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config");
                    string oldSettingsPath = Path.Combine(oldConfigPath, "DiscImageChef.xml");

                    string xdgConfigPath =
                        Path.Combine(homePath,
                                     Environment.GetEnvironmentVariable(XDG_CONFIG_HOME) ??
                                     XDG_CONFIG_HOME_RESOLVED);
                    string settingsPath = Path.Combine(xdgConfigPath, "DiscImageChef.xml");

                    if (File.Exists(oldSettingsPath) && !File.Exists(settingsPath))
                    {
                        if (!Directory.Exists(xdgConfigPath))
                        {
                            Directory.CreateDirectory(xdgConfigPath);
                        }
                        File.Move(oldSettingsPath, settingsPath);
                    }

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

                    XmlSerializer xs = new XmlSerializer(Current.GetType());
                    prefsSr = new StreamReader(settingsPath);
                    Current = (DicSettings)xs.Deserialize(prefsSr);
                }

                break;
                }
            }
            catch
            {
                prefsFs?.Close();
                prefsSr?.Close();
                SetDefaultSettings();
                SaveSettings();
            }
        }
Beispiel #17
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.romrepomgr.plist
                case PlatformID.MacOSX:
                case PlatformID.iOS:
                {
                    var root = new NSDictionary
                    {
                        {
                            "DatabasePath", Current.DatabasePath
                        },
                        {
                            "RepositoryPath", Current.RepositoryPath
                        },
                        {
                            "TemporaryFolder", Current.TemporaryFolder
                        },
                        {
                            "UnArchiverPath", Current.UnArchiverPath
                        }
                    };

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

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

                    var 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/RomRepoMgr
                case PlatformID.Win32NT when OperatingSystem.IsWindows():
                case PlatformID.Win32S when OperatingSystem.IsWindows():
                case PlatformID.Win32Windows when OperatingSystem.IsWindows():
                case PlatformID.WinCE when OperatingSystem.IsWindows():
                case PlatformID.WindowsPhone when OperatingSystem.IsWindows():
                {
                    RegistryKey parentKey = Registry.CurrentUser.OpenSubKey("SOFTWARE", true)?.
                                            CreateSubKey("Claunia.com");

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

                    key?.SetValue("DatabasePath", Current.DatabasePath);
                    key?.SetValue("RepositoryPath", Current.RepositoryPath);
                    key?.SetValue("TemporaryFolder", Current.TemporaryFolder);
                    key?.SetValue("UnArchiverPath", Current.UnArchiverPath);
                }

                break;
                #endif

                // Otherwise, settings will be saved in ~/.config/RomRepoMgr.json
                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, "RomRepoMgr.json");

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

                    var prefsSr = new StreamWriter(settingsPath);

                    prefsSr.Write(JsonSerializer.Serialize(Current, new JsonSerializerOptions
                        {
                            AllowTrailingCommas         = true,
                            PropertyNameCaseInsensitive = true,
                            ReadCommentHandling         = JsonCommentHandling.Skip,
                            WriteIndented = true
                        }));

                    prefsSr.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
        }
Beispiel #18
0
        /// <summary>
        ///     Saves statistics to disk
        /// </summary>
        public static void SaveStats()
        {
            if (AllStats == null)
            {
                return;
            }

            if (AllStats.OperatingSystems != null)
            {
                long count = 0;

                OsStats old = null;
                foreach (OsStats nvs in AllStats.OperatingSystems.Where(nvs =>
                                                                        nvs.name == DetectOS
                                                                        .GetRealPlatformID().ToString() &&
                                                                        nvs.version == DetectOS.GetVersion()))
                {
                    count = nvs.Value + 1;
                    old   = nvs;
                    break;
                }

                if (old != null)
                {
                    AllStats.OperatingSystems.Remove(old);
                }

                count++;
                AllStats.OperatingSystems.Add(new OsStats
                {
                    name    = DetectOS.GetRealPlatformID().ToString(),
                    Value   = count,
                    version = DetectOS.GetVersion()
                });
            }
            else if (CurrentStats != null)
            {
                AllStats.OperatingSystems = CurrentStats.OperatingSystems;
            }

            if (AllStats.Versions != null)
            {
                long count = 0;

                NameValueStats old = null;
                foreach (NameValueStats nvs in AllStats.Versions.Where(nvs => nvs.name == Version.GetVersion()))
                {
                    count = nvs.Value + 1;
                    old   = nvs;
                    break;
                }

                if (old != null)
                {
                    AllStats.Versions.Remove(old);
                }

                count++;
                AllStats.Versions.Add(new NameValueStats {
                    name = Version.GetVersion(), Value = count
                });
            }
            else if (CurrentStats != null)
            {
                AllStats.Versions = CurrentStats.Versions;
            }

            FileStream fs = new FileStream(Path.Combine(Settings.Settings.StatsPath, "Statistics.xml"),
                                           FileMode.Create);
            XmlSerializer xs = new XmlSerializer(AllStats.GetType());

            xs.Serialize(fs, AllStats);
            fs.Close();

            if (CurrentStats != null)
            {
                string partial = $"PartialStats_{DateTime.UtcNow:yyyyMMddHHmmssfff}.xml";

                fs = new FileStream(Path.Combine(Settings.Settings.StatsPath, partial), FileMode.Create);
                xs = new XmlSerializer(CurrentStats.GetType());
                xs.Serialize(fs, CurrentStats);
                fs.Close();
            }

            if (Settings.Settings.Current.Stats != null && Settings.Settings.Current.Stats.ShareStats)
            {
                SubmitStats();
            }
        }
Beispiel #19
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();
            }
        }
Beispiel #20
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;
                }
            }
        }
Beispiel #21
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();
        }
Beispiel #22
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
        }
Beispiel #23
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();
        }
Beispiel #24
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);
        }
Beispiel #25
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");
                }
Beispiel #26
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();
    }
Beispiel #27
0
        /// <summary>Loads settings</summary>
        public static void LoadSettings()
        {
            Current = new SetSettings();
            PlatformID ptId     = DetectOS.GetRealPlatformID();
            string     homePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

            FileStream   prefsFs = null;
            StreamReader prefsSr = null;

            try
            {
                switch (ptId)
                {
                // In case of macOS or iOS settings will be saved in ~/Library/Preferences/com.claunia.romrepomgr.plist
                case PlatformID.MacOSX:
                case PlatformID.iOS:
                {
                    string preferencesPath =
                        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library",
                                     "Preferences");

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

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

                    prefsFs = new FileStream(preferencesFilePath, FileMode.Open, FileAccess.Read);

                    var parsedPreferences = (NSDictionary)BinaryPropertyListParser.Parse(prefsFs);

                    if (parsedPreferences != null)
                    {
                        NSObject obj;

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

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

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

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

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

                        SetDefaultSettings();
                        SaveSettings();
                    }
                }

                break;

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

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

                        return;
                    }

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

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

                        return;
                    }

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

                break;
                #endif

                // Otherwise, settings will be saved in ~/.config/RomRepoMgr.json
                default:
                {
                    string xdgConfigPath =
                        Path.Combine(homePath,
                                     Environment.GetEnvironmentVariable(XDG_CONFIG_HOME) ??
                                     XDG_CONFIG_HOME_RESOLVED);

                    string settingsPath = Path.Combine(xdgConfigPath, "RomRepoMgr.json");

                    if (!File.Exists(settingsPath))
                    {
                        SetDefaultSettings();
                        SaveSettings();

                        return;
                    }

                    prefsSr = new StreamReader(settingsPath);

                    Current = JsonSerializer.Deserialize <SetSettings>(prefsSr.ReadToEnd(), new JsonSerializerOptions
                        {
                            AllowTrailingCommas         = true,
                            PropertyNameCaseInsensitive = true,
                            ReadCommentHandling         = JsonCommentHandling.Skip,
                            WriteIndented = true
                        });
                }

                break;
                }
            }
            catch
            {
                prefsFs?.Close();
                prefsSr?.Close();
                SetDefaultSettings();
                SaveSettings();
            }
        }
Beispiel #28
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();
        }
Beispiel #29
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")));
        }
Beispiel #30
0
        protected void OnBtnSaveClicked(object sender, EventArgs e)
        {
            var dlgSave = new SaveFileDialog
            {
                CheckFileExists = true
            };

            dlgSave.Filters.Add(new FileFilter
            {
                Extensions = new[]
                {
                    "log"
                },
                Name = "Log files"
            });

            DialogResult result = dlgSave.ShowDialog(this);

            if (result != DialogResult.Ok)
            {
                return;
            }

            try
            {
                var logFs = new FileStream(dlgSave.FileName, FileMode.Create, FileAccess.ReadWrite);
                var logSw = new StreamWriter(logFs);

                logSw.WriteLine("Log saved at {0}", DateTime.Now);

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

                var assemblyVersion =
                    Attribute.GetCustomAttribute(typeof(AaruConsole).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 GUI mode using {0}", Application.Instance.Platform.ID);
            #if DEBUG
                logSw.WriteLine("DEBUG version");
            #endif
                logSw.WriteLine("Command line: {0}", Environment.CommandLine);
                logSw.WriteLine();

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

                foreach (LogEntry entry in ConsoleHandler.Entries)
                {
                    if (entry.Type != "Info")
                    {
                        logSw.WriteLine("{0}: ({1}) {2}", entry.Timestamp, entry.Type.ToLower(), entry.Message);
                    }
                    else
                    {
                        logSw.WriteLine("{0}: {1}", entry.Timestamp, entry.Message);
                    }
                }

                logSw.Close();
                logFs.Close();
            }
            catch (Exception exception)
            {
                MessageBox.Show("Exception {0} trying to save logfile, details has been sent to console.",
                                exception.Message);

                AaruConsole.ErrorWriteLine("Console", exception.Message);
                AaruConsole.ErrorWriteLine("Console", exception.StackTrace);
            }
        }