예제 #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DiskImageFile"/> class.
        /// </summary>
        /// <param name="stream">The stream to read.</param>
        /// <param name="ownsStream">Indicates if the new instance should control the lifetime of the stream.</param>
        public DiskImageFile(Stream stream, Ownership ownsStream)
        {
            this.udifHeader = new UdifResourceFile();
            this.stream     = stream ?? throw new ArgumentNullException(nameof(stream));
            this.ownsStream = ownsStream;

            if (stream.Length < this.udifHeader.Size)
            {
                throw new InvalidDataException("The file is not a valid DMG file: could not read the UDIF header.");
            }

            stream.Position = stream.Length - this.udifHeader.Size;
            byte[] data = StreamUtilities.ReadExact(stream, this.udifHeader.Size);

            this.udifHeader.ReadFrom(data, 0);

            if (!this.udifHeader.SignatureValid)
            {
                throw new InvalidDataException("The file is not a valid DMG file: could not read the UDIF header.");
            }

            stream.Position = (long)this.udifHeader.XmlOffset;
            byte[] xmlData = StreamUtilities.ReadExact(stream, (int)this.udifHeader.XmlLength);
            Dictionary <string, object> plist = (Dictionary <string, object>)XmlPropertyListParser.Parse(xmlData).ToObject();

            this.resources = ResourceFork.FromPlist(plist);
            this.Buffer    = new UdifBuffer(stream, this.resources, this.udifHeader.SectorCount);
        }
예제 #2
0
        /// <summary>
        /// Reads a <see cref="ProvisioningProfile"/> off a <see cref="SignedCms"/> object.
        /// </summary>
        /// <param name="signedData">
        /// A <see cref="SignedCms"/> object which represents the signed provisioning
        /// profile.
        /// </param>
        /// <returns>
        /// A <see cref="ProvisioningProfile"/>.
        /// </returns>
        public static ProvisioningProfile Read(SignedCms signedData)
        {
            if (signedData == null)
            {
                throw new ArgumentNullException(nameof(signedData));
            }

            var propertyList = (NSDictionary)XmlPropertyListParser.Parse(signedData.ContentInfo.Content);

            return(new ProvisioningProfile()
            {
                AppIdName = propertyList.GetString("AppIDName"),
                ApplicationIdentifierPrefix = propertyList.GetStringArray("ApplicationIdentifierPrefix"),
                Platform = propertyList.GetStringArray("Platform"),
                CreationDate = propertyList.GetDateTime("CreationDate"),
                DeveloperCertificates = propertyList.GetDataArray("DeveloperCertificates").Select(d => Identity.FromX509Certificate(new X509Certificate2(d))).ToList(),
                Entitlements = Entitlements.Read(propertyList.GetDict("Entitlements")),
                ExpirationDate = propertyList.GetDateTime("ExpirationDate"),
                Name = propertyList.GetString("Name"),
                ProvisionsAllDevices = propertyList.GetNullableBoolean("ProvisionsAllDevices"),
                ProvisionedDevices = propertyList.GetStringArray("ProvisionedDevices"),
                TeamIdentifier = propertyList.GetStringArray("TeamIdentifier"),
                TeamName = propertyList.GetString("TeamName"),
                TimeToLive = propertyList.GetInt32("TimeToLive"),
                Uuid = new Guid(propertyList.GetString("UUID")),
                Version = propertyList.GetInt32("Version"),
            });
        }
예제 #3
0
    /// <summary>
    /// 将 plist 格式的 xml 内容,解析成 Newtowsoft.Json JObject 对象来访问
    /// </summary>
    /// <param name="plist">plist 格式的 xml 内容</param>
    /// <returns>JObject</returns>
    public static JObject ParsePListToJson(string plist)
    {
        NSObject obj  = XmlPropertyListParser.Parse(Encoding.UTF8.GetBytes(plist));
        string   json = JsonConvert.SerializeObject(obj.ToObject());

        return(JsonConvert.DeserializeObject <JObject>(json));
    }
예제 #4
0
        public static void RoundtripTest()
        {
            string   expected = File.ReadAllText(@"test-files/Roundtrip.plist");
            NSObject value    = XmlPropertyListParser.Parse(new FileInfo(@"test-files/Roundtrip.plist"));
            string   actual   = value.ToXmlPropertyList();

            Assert.Equal(expected, actual, false, true);
        }
예제 #5
0
        public static void RoundtripTest()
        {
            var expected = File.ReadAllText(@"test-files\Roundtrip.plist");
            var value    = XmlPropertyListParser.Parse(new FileInfo(@"test-files\Roundtrip.plist"));
            var actual   = value.ToXmlPropertyList();

            Assert.Equal(expected, actual);
        }
예제 #6
0
        public static void RoundtripDataTest()
        {
            string   expected = File.ReadAllText(@"test-files/RoundtripBinary.plist");
            NSObject value    = XmlPropertyListParser.Parse(new FileInfo(@"test-files/RoundtripBinary.plist"));
            string   actual   = value.ToXmlPropertyList();

            Assert.Equal(expected, actual, ignoreLineEndingDifferences: true);
        }
예제 #7
0
        public void ToString_ValidPairingRecord()
        {
            var raw  = File.ReadAllText("Lockdown/0123456789abcdef0123456789abcdef01234567.plist");
            var dict = (NSDictionary)XmlPropertyListParser.ParseString(raw);

            var pairingRecord = PairingRecord.Read(dict);

            Assert.Equal("HostId: 01234567-012345678901234567, SystemBUID: 01234567890123456789012345, Host certificate: EE63391AA1FBA937E2784CC7DAAA9C22BA223B54 (expires: 2026-11-28 11:20:17Z)", pairingRecord.ToString());
        }
예제 #8
0
        public void ReadError_Works()
        {
            var dict = (NSDictionary)XmlPropertyListParser.Parse(File.ReadAllBytes("MobileImageMounter/mountImageAlreadyMountedResponse.bin"));
            MobileImageMounterResponse response = new MobileImageMounterResponse();

            response.FromDictionary(dict);

            Assert.NotNull(response.DetailedError);
            Assert.Equal(MobileImageMounterError.ImageMountFailed, response.Error);
            Assert.Null(response.Status);
        }
예제 #9
0
        public void ToPropertyList_ExcludesPrivateKeysIfRequired()
        {
            var raw  = File.ReadAllText("Lockdown/0123456789abcdef0123456789abcdef01234567.plist");
            var dict = (NSDictionary)XmlPropertyListParser.ParseString(raw);

            var pairingRecord  = PairingRecord.Read(dict);
            var serializedDict = pairingRecord.ToPropertyList(includePrivateKeys: false);

            Assert.False(serializedDict.ContainsKey("HostPrivateKey"));
            Assert.False(serializedDict.ContainsKey("RootPrivateKey"));
        }
예제 #10
0
        public void FromDictionary(string path, bool hasImage)
        {
            var response = new LookupImageResponse();

            NSDictionary dictionary = (NSDictionary)XmlPropertyListParser.Parse(File.ReadAllBytes(path));

            response.FromDictionary(dictionary);
            Assert.Null(response.DetailedError);
            Assert.Null(response.Error);
            Assert.Equal(hasImage, response.ImageSignature != null);
            Assert.Equal(MobileImageMounterStatus.Complete, response.Status);
        }
예제 #11
0
        public static void TestRealInResourceRule()
        {
            NSDictionary dict = (NSDictionary)XmlPropertyListParser.Parse(new FileInfo("test-files/ResourceRules.plist"));

            Assert.Equal(1, dict.Count);
            Assert.True(dict.ContainsKey("weight"));

            var weight = dict["weight"].ToObject();

            Assert.IsType <double>(weight);
            Assert.Equal(10d, (double)weight);
        }
예제 #12
0
파일: UIDTests.cs 프로젝트: hmyit/plist-cil
        public void XmlRoundTripTest()
        {
            UID original = new UID(0xabcd);

            string plist = original.ToXmlPropertyList();

            // UIDs don't exist in XML property lists, but they are represented as strings
            // for compability purposes
            NSString roundtrip = XmlPropertyListParser.ParseString(plist) as NSString;

            Assert.Equal("abcd", roundtrip.ToObject());
        }
예제 #13
0
        public void ToPropertyList_NoPrivateKeys_Works()
        {
            var raw  = File.ReadAllText("Lockdown/0123456789abcdef0123456789abcdef01234567.plist");
            var dict = (NSDictionary)XmlPropertyListParser.ParseString(raw);

            var pairingRecord = PairingRecord.Read(dict);

            pairingRecord.HostPrivateKey = null;
            pairingRecord.RootPrivateKey = null;
            var serializedDict = pairingRecord.ToPropertyList();

            Assert.Equal(dict.Keys.Count - 2, serializedDict.Keys.Count);
        }
예제 #14
0
        public void ToPropertyList_Works()
        {
            var raw  = File.ReadAllText("Lockdown/0123456789abcdef0123456789abcdef01234567.plist");
            var dict = (NSDictionary)XmlPropertyListParser.ParseString(raw);

            var pairingRecord  = PairingRecord.Read(dict);
            var serializedDict = pairingRecord.ToPropertyList();

            Assert.Equal(dict.Keys, serializedDict.Keys);

            foreach (var key in dict.Keys)
            {
                Assert.Equal(dict[key], serializedDict[key]);
            }

            var xml = serializedDict.ToXmlPropertyList();

            Assert.Equal(raw, xml, ignoreLineEndingDifferences: true);
        }
예제 #15
0
        /// <summary>
        /// Asynchronously receives a message from the remote muxer.
        /// </summary>
        /// <param name="cancellationToken">
        /// A <see cref="CancellationToken"/> which can be used to cancel the asynchronous operation.
        /// </param>
        /// <returns>
        /// A <see cref="DeviceListMessage"/> object which represents the property list value received
        /// from the remote muxer.
        /// </returns>
        public virtual async Task <MuxerMessage> ReadMessageAsync(CancellationToken cancellationToken)
        {
            int         read;
            MuxerHeader header;

            using (var headerBuffer = this.memoryPool.Rent(MuxerHeader.BinarySize))
            {
                if ((read = await this.stream.ReadBlockAsync(headerBuffer.Memory.Slice(0, MuxerHeader.BinarySize), cancellationToken).ConfigureAwait(false)) != MuxerHeader.BinarySize)
                {
                    this.logger.LogInformation("Could only read {read}/{total} bytes of the muxer header; exiting.", read, MuxerHeader.BinarySize);
                    return(null);
                }

                header = MuxerHeader.Read(headerBuffer.Memory.Slice(0, MuxerHeader.BinarySize).Span);
            }

            if (header.Message != MuxerMessageType.Plist)
            {
                throw new NotSupportedException($"Only Plist message types are supported; but a {header.Message} message was received");
            }

            int messageLength = (int)header.Length - MuxerHeader.BinarySize;

            using (var messageBuffer = this.memoryPool.Rent(messageLength))
            {
                if ((read = await this.stream.ReadBlockAsync(messageBuffer.Memory.Slice(0, messageLength), cancellationToken).ConfigureAwait(false)) != messageLength)
                {
                    this.logger.LogInformation("Could only read {read}/{total} bytes of the muxer header; exiting.", read, messageLength);
                    return(null);
                }

                var propertyListData = messageBuffer.Memory.Slice(0, messageLength).ToArray();
                var propertyList     = (NSDictionary)XmlPropertyListParser.Parse(propertyListData);

                return(MuxerMessage.ReadAny(propertyList));
            }
        }
예제 #16
0
        /// <summary>
        /// Opens the contents of this <see cref="XipFile"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="CpioFile"/> which represents the CPIO file embedded in this
        /// <see cref="XipFile"/>.
        /// </returns>
        public CpioFile Open()
        {
            Verify.NotDisposed(this);

            using (var metadataStream = this.xarFile.Open("Metadata"))
            {
                var metadataDictionary = (NSDictionary)XmlPropertyListParser.Parse(metadataStream);
                this.Metadata.ReadFrom(metadataDictionary);
            }

            var content = this.xarFile.Open("Content");

            // The .xip file will use the 'pbzx' compression method if
            // FileSystemCompressionFormat == "10.10". This isn't implemented (yet).
            if (this.Metadata.FileSystemCompressionFormat == null)
            {
                var gz = new GZipStream(content, CompressionMode.Decompress, leaveOpen: false);
                return(new CpioFile(gz, leaveOpen: false));
            }
            else
            {
                throw new NotSupportedException();
            }
        }
예제 #17
0
        public bool Open(IFilter imageFilter)
        {
            Stream stream = imageFilter.GetDataForkStream();

            if (stream.Length < 512)
            {
                return(false);
            }

            stream.Seek(-Marshal.SizeOf <UdifFooter>(), SeekOrigin.End);
            byte[] footerB = new byte[Marshal.SizeOf <UdifFooter>()];

            stream.Read(footerB, 0, Marshal.SizeOf <UdifFooter>());
            footer = Marshal.ByteArrayToStructureBigEndian <UdifFooter>(footerB);

            if (footer.signature != UDIF_SIGNATURE)
            {
                stream.Seek(0, SeekOrigin.Begin);
                footerB = new byte[Marshal.SizeOf <UdifFooter>()];

                stream.Read(footerB, 0, Marshal.SizeOf <UdifFooter>());
                footer = Marshal.ByteArrayToStructureBigEndian <UdifFooter>(footerB);

                if (footer.signature != UDIF_SIGNATURE)
                {
                    throw new Exception("Unable to find UDIF signature.");
                }

                AaruConsole.VerboseWriteLine("Found obsolete UDIF format.");
            }

            AaruConsole.DebugWriteLine("UDIF plugin", "footer.signature = 0x{0:X8}", footer.signature);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.version = {0}", footer.version);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.headerSize = {0}", footer.headerSize);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.flags = {0}", footer.flags);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.runningDataForkOff = {0}", footer.runningDataForkOff);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.dataForkOff = {0}", footer.dataForkOff);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.dataForkLen = {0}", footer.dataForkLen);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.rsrcForkOff = {0}", footer.rsrcForkOff);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.rsrcForkLen = {0}", footer.rsrcForkLen);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.segmentNumber = {0}", footer.segmentNumber);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.segmentCount = {0}", footer.segmentCount);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.segmentId = {0}", footer.segmentId);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.dataForkChkType = {0}", footer.dataForkChkType);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.dataForkLen = {0}", footer.dataForkLen);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.dataForkChk = 0x{0:X8}", footer.dataForkChk);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.plistOff = {0}", footer.plistOff);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.plistLen = {0}", footer.plistLen);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.masterChkType = {0}", footer.masterChkType);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.masterChkLen = {0}", footer.masterChkLen);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.masterChk = 0x{0:X8}", footer.masterChk);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.imageVariant = {0}", footer.imageVariant);
            AaruConsole.DebugWriteLine("UDIF plugin", "footer.sectorCount = {0}", footer.sectorCount);

            AaruConsole.DebugWriteLine("UDIF plugin", "footer.reserved1 is empty? = {0}",
                                       ArrayHelpers.ArrayIsNullOrEmpty(footer.reserved1));

            AaruConsole.DebugWriteLine("UDIF plugin", "footer.reserved2 is empty? = {0}",
                                       ArrayHelpers.ArrayIsNullOrEmpty(footer.reserved2));

            AaruConsole.DebugWriteLine("UDIF plugin", "footer.reserved3 is empty? = {0}",
                                       ArrayHelpers.ArrayIsNullOrEmpty(footer.reserved3));

            AaruConsole.DebugWriteLine("UDIF plugin", "footer.reserved4 is empty? = {0}",
                                       ArrayHelpers.ArrayIsNullOrEmpty(footer.reserved4));

            // Block chunks and headers
            List <byte[]> blkxList = new List <byte[]>();

            chunks = new Dictionary <ulong, BlockChunk>();

            bool fakeBlockChunks = false;

            byte[] vers = null;

            if (footer.plistLen == 0 &&
                footer.rsrcForkLen != 0)
            {
                AaruConsole.DebugWriteLine("UDIF plugin", "Reading resource fork.");
                byte[] rsrcB = new byte[footer.rsrcForkLen];
                stream.Seek((long)footer.rsrcForkOff, SeekOrigin.Begin);
                stream.Read(rsrcB, 0, rsrcB.Length);

                var rsrc = new ResourceFork(rsrcB);

                if (!rsrc.ContainsKey(BLOCK_OS_TYPE))
                {
                    throw new
                          ImageNotSupportedException("Image resource fork doesn't contain UDIF block chunks. Please fill an issue and send it to us.");
                }

                Resource blkxRez = rsrc.GetResource(BLOCK_OS_TYPE);

                if (blkxRez == null)
                {
                    throw new
                          ImageNotSupportedException("Image resource fork doesn't contain UDIF block chunks. Please fill an issue and send it to us.");
                }

                if (blkxRez.GetIds().Length == 0)
                {
                    throw new
                          ImageNotSupportedException("Image resource fork doesn't contain UDIF block chunks. Please fill an issue and send it to us.");
                }

                blkxList.AddRange(blkxRez.GetIds().Select(blkxId => blkxRez.GetResource(blkxId)));

                Resource versRez = rsrc.GetResource(0x76657273);

                if (versRez != null)
                {
                    vers = versRez.GetResource(versRez.GetIds()[0]);
                }
            }
            else if (footer.plistLen != 0)
            {
                AaruConsole.DebugWriteLine("UDIF plugin", "Reading property list.");
                byte[] plistB = new byte[footer.plistLen];
                stream.Seek((long)footer.plistOff, SeekOrigin.Begin);
                stream.Read(plistB, 0, plistB.Length);

                AaruConsole.DebugWriteLine("UDIF plugin", "Parsing property list.");
                var plist = (NSDictionary)XmlPropertyListParser.Parse(plistB);

                if (plist == null)
                {
                    throw new Exception("Could not parse property list.");
                }

                if (!plist.TryGetValue(RESOURCE_FORK_KEY, out NSObject rsrcObj))
                {
                    throw new Exception("Could not retrieve resource fork.");
                }

                var rsrc = (NSDictionary)rsrcObj;

                if (!rsrc.TryGetValue(BLOCK_KEY, out NSObject blkxObj))
                {
                    throw new Exception("Could not retrieve block chunks array.");
                }

                NSObject[] blkx = ((NSArray)blkxObj).GetArray();

                foreach (NSDictionary part in blkx.Cast <NSDictionary>())
                {
                    if (!part.TryGetValue("Name", out _))
                    {
                        throw new Exception("Could not retrieve Name");
                    }

                    if (!part.TryGetValue("Data", out NSObject dataObj))
                    {
                        throw new Exception("Could not retrieve Data");
                    }

                    blkxList.Add(((NSData)dataObj).Bytes);
                }

                if (rsrc.TryGetValue("vers", out NSObject versObj))
                {
                    NSObject[] versArray = ((NSArray)versObj).GetArray();

                    if (versArray.Length >= 1)
                    {
                        vers = ((NSData)versArray[0]).Bytes;
                    }
                }
            }
            else
            {
                // Obsolete read-only UDIF only prepended the header and then put the image without any kind of block references.
                // So let's falsify a block chunk
                var bChnk = new BlockChunk
                {
                    length = footer.dataForkLen, offset = footer.dataForkOff, sector = 0, sectors = footer.sectorCount,
                    type   = CHUNK_TYPE_COPY
                };

                imageInfo.Sectors = footer.sectorCount;
                chunks.Add(bChnk.sector, bChnk);
                buffersize      = 2048 * SECTOR_SIZE;
                fakeBlockChunks = true;
            }

            if (vers != null)
            {
                var version = new Version(vers);

                string release = null;
                string dev     = null;
                string pre     = null;

                string major = $"{version.MajorVersion}";
                string minor = $".{version.MinorVersion / 10}";

                if (version.MinorVersion % 10 > 0)
                {
                    release = $".{version.MinorVersion % 10}";
                }

                switch (version.DevStage)
                {
                case Version.DevelopmentStage.Alpha:
                    dev = "a";

                    break;

                case Version.DevelopmentStage.Beta:
                    dev = "b";

                    break;

                case Version.DevelopmentStage.PreAlpha:
                    dev = "d";

                    break;
                }

                if (dev == null &&
                    version.PreReleaseVersion > 0)
                {
                    dev = "f";
                }

                if (dev != null)
                {
                    pre = $"{version.PreReleaseVersion}";
                }

                imageInfo.ApplicationVersion = $"{major}{minor}{release}{dev}{pre}";
                imageInfo.Application        = version.VersionString;
                imageInfo.Comments           = version.VersionMessage;

                if (version.MajorVersion == 3)
                {
                    imageInfo.Application = "ShrinkWrap™";
                }
                else if (version.MajorVersion == 6)
                {
                    imageInfo.Application = "DiskCopy";
                }
            }
            else
            {
                imageInfo.Application = "DiskCopy";
            }

            AaruConsole.DebugWriteLine("UDIF plugin", "Image application = {0} version {1}", imageInfo.Application,
                                       imageInfo.ApplicationVersion);

            imageInfo.Sectors = 0;

            if (!fakeBlockChunks)
            {
                if (blkxList.Count == 0)
                {
                    throw new
                          ImageNotSupportedException("Could not retrieve block chunks. Please fill an issue and send it to us.");
                }

                buffersize = 0;

                foreach (byte[] blkxBytes in blkxList)
                {
                    var    bHdr  = new BlockHeader();
                    byte[] bHdrB = new byte[Marshal.SizeOf <BlockHeader>()];
                    Array.Copy(blkxBytes, 0, bHdrB, 0, Marshal.SizeOf <BlockHeader>());
                    bHdr = Marshal.ByteArrayToStructureBigEndian <BlockHeader>(bHdrB);

                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.signature = 0x{0:X8}", bHdr.signature);
                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.version = {0}", bHdr.version);
                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.sectorStart = {0}", bHdr.sectorStart);
                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.sectorCount = {0}", bHdr.sectorCount);
                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.dataOffset = {0}", bHdr.dataOffset);
                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.buffers = {0}", bHdr.buffers);
                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.descriptor = 0x{0:X8}", bHdr.descriptor);
                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.reserved1 = {0}", bHdr.reserved1);
                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.reserved2 = {0}", bHdr.reserved2);
                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.reserved3 = {0}", bHdr.reserved3);
                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.reserved4 = {0}", bHdr.reserved4);
                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.reserved5 = {0}", bHdr.reserved5);
                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.reserved6 = {0}", bHdr.reserved6);
                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.checksumType = {0}", bHdr.checksumType);
                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.checksumLen = {0}", bHdr.checksumLen);
                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.checksum = 0x{0:X8}", bHdr.checksum);
                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.chunks = {0}", bHdr.chunks);

                    AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.reservedChk is empty? = {0}",
                                               ArrayHelpers.ArrayIsNullOrEmpty(bHdr.reservedChk));

                    if (bHdr.buffers > buffersize)
                    {
                        buffersize = bHdr.buffers * SECTOR_SIZE;
                    }

                    for (int i = 0; i < bHdr.chunks; i++)
                    {
                        var    bChnk  = new BlockChunk();
                        byte[] bChnkB = new byte[Marshal.SizeOf <BlockChunk>()];

                        Array.Copy(blkxBytes, Marshal.SizeOf <BlockHeader>() + (Marshal.SizeOf <BlockChunk>() * i),
                                   bChnkB, 0, Marshal.SizeOf <BlockChunk>());

                        bChnk = Marshal.ByteArrayToStructureBigEndian <BlockChunk>(bChnkB);

                        AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.chunk[{0}].type = 0x{1:X8}", i, bChnk.type);
                        AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.chunk[{0}].comment = {1}", i, bChnk.comment);
                        AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.chunk[{0}].sector = {1}", i, bChnk.sector);
                        AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.chunk[{0}].sectors = {1}", i, bChnk.sectors);
                        AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.chunk[{0}].offset = {1}", i, bChnk.offset);
                        AaruConsole.DebugWriteLine("UDIF plugin", "bHdr.chunk[{0}].length = {1}", i, bChnk.length);

                        if (bChnk.type == CHUNK_TYPE_END)
                        {
                            break;
                        }

                        imageInfo.Sectors += bChnk.sectors;

                        // Chunk offset is relative
                        bChnk.sector += bHdr.sectorStart;
                        bChnk.offset += bHdr.dataOffset;

                        switch (bChnk.type)
                        {
                        // TODO: Handle comments
                        case CHUNK_TYPE_COMMNT: continue;

                        // TODO: Handle compressed chunks
                        case CHUNK_TYPE_KENCODE:
                            throw new
                                  ImageNotSupportedException("Chunks compressed with KenCode are not yet supported.");

                        case CHUNK_TYPE_LZH:
                            throw new
                                  ImageNotSupportedException("Chunks compressed with LZH are not yet supported.");

                        case CHUNK_TYPE_LZFSE:
                            throw new
                                  ImageNotSupportedException("Chunks compressed with lzfse are not yet supported.");
                        }

                        if ((bChnk.type > CHUNK_TYPE_NOCOPY && bChnk.type < CHUNK_TYPE_COMMNT) ||
                            (bChnk.type > CHUNK_TYPE_LZFSE && bChnk.type < CHUNK_TYPE_END))
                        {
                            throw new ImageNotSupportedException($"Unsupported chunk type 0x{bChnk.type:X8} found");
                        }

                        if (bChnk.sectors > 0)
                        {
                            chunks.Add(bChnk.sector, bChnk);
                        }
                    }
                }
            }

            sectorCache           = new Dictionary <ulong, byte[]>();
            chunkCache            = new Dictionary <ulong, byte[]>();
            currentChunkCacheSize = 0;
            imageStream           = stream;

            imageInfo.CreationTime         = imageFilter.GetCreationTime();
            imageInfo.LastModificationTime = imageFilter.GetLastWriteTime();
            imageInfo.MediaTitle           = Path.GetFileNameWithoutExtension(imageFilter.GetFilename());
            imageInfo.SectorSize           = SECTOR_SIZE;
            imageInfo.XmlMediaType         = XmlMediaType.BlockMedia;
            imageInfo.MediaType            = MediaType.GENERIC_HDD;
            imageInfo.ImageSize            = imageInfo.Sectors * SECTOR_SIZE;
            imageInfo.Version = $"{footer.version}";

            imageInfo.Cylinders       = (uint)(imageInfo.Sectors / 16 / 63);
            imageInfo.Heads           = 16;
            imageInfo.SectorsPerTrack = 63;

            return(true);
        }
예제 #18
0
        public static Dictionary <int, SongStructS> LoadItunesXML(string filePath)
        {
            if (!File.Exists(filePath))
            {
                MessageBox.Show("invalid filepath: '" + filePath + "'");
                return(new Dictionary <int, SongStructS> ());
            }

            Dictionary <int, SongStructS> bibliotek = new Dictionary <int, SongStructS> ();
            NSDictionary tracks = (XmlPropertyListParser.Parse(new FileInfo(filePath)) as NSDictionary)["Tracks"] as NSDictionary;

            foreach (var entry in tracks)
            {
                NSDictionary track     = (NSDictionary)entry.Value;
                SongStructS  musicFile = new SongStructS();
                int          id        = 0;

                // Get importend informations
                if (track.ContainsKey("Location"))
                {
                    musicFile.Location = Path2String(track["Location"].ToString());
                }

                // ToDo: set Filter?
                // if (File.Exists(musicFile.Location))
                //    continue;

                // strings
                if (track.ContainsKey("Name"))
                {
                    musicFile.Name = track["Name"].ToString();
                }

                if (track.ContainsKey("Album"))
                {
                    musicFile.Album = track["Album"].ToString();
                }

                if (track.ContainsKey("Artist"))
                {
                    musicFile.Artist = track["Artist"].ToString();
                }

                if (track.ContainsKey("Album Artist"))
                {
                    musicFile.AlbumArtist = track["Album Artist"].ToString();
                }

                if (track.ContainsKey("Genre"))
                {
                    musicFile.Genre = track["Genre"].ToString();
                }

                // integer
                if (track.ContainsKey("Track ID"))
                {
                    id = musicFile.ID = int.Parse(track["Track ID"].ToString());
                }

                if (track.ContainsKey("Track Number"))
                {
                    musicFile.Track = int.Parse(track["Track Number"].ToString());
                }

                if (track.ContainsKey("Year"))
                {
                    musicFile.Year = int.Parse(track["Year"].ToString());
                }

                if (track.ContainsKey("Album Rating"))
                {
                    musicFile.AlbumRating = int.Parse(track["Album Rating"].ToString());
                }

                if (track.ContainsKey("Total Time"))
                {
                    musicFile.TotalTime = int.Parse(track["Total Time"].ToString());
                }

                if (track.ContainsKey("Bit Rate"))
                {
                    musicFile.BitRate = int.Parse(track["Bit Rate"].ToString());
                }

                if (track.ContainsKey("Play Count"))
                {
                    musicFile.PlayCount = int.Parse(track["Play Count"].ToString());
                }

                //// bool
                if (track.ContainsKey("Rating Computed"))
                {
                    musicFile.RatingComputed = (track["Rating Computed"].ToString().ToLower() == "true") ? true : false;
                }

                // ToDo: TryCatch ??

                bibliotek.Add(id, musicFile);
            }
            return(bibliotek);
        }