Пример #1
0
        public virtual void TestOtherLinesWithActualTextAddition()
        {
            byte[] ttf = StreamUtil.InputStreamToArray(new FileStream(iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
                                                                                                                    .CurrentContext.TestDirectory) + "/resources/itext/io/font/otf/FreeSans.ttf", FileMode.Open, FileAccess.Read
                                                                      ));
            TrueTypeFont font          = new TrueTypeFont(ttf);
            GlyphLine    containerLine = new GlyphLine(ConstructGlyphListFromString("France", font));
            GlyphLine    childLine     = new GlyphLine(ConstructGlyphListFromString("---Liberte", font));

            childLine.SetActualText(3, 10, "Viva");
            containerLine.Add(childLine);
            containerLine.end = 16;
            for (int i = 0; i < 9; i++)
            {
                NUnit.Framework.Assert.IsNull(containerLine.actualText[i]);
            }
            for (int i = 9; i < 16; i++)
            {
                NUnit.Framework.Assert.AreEqual("Viva", containerLine.actualText[i].value);
            }
            NUnit.Framework.Assert.AreEqual("France---Viva", containerLine.ToString());
        }
Пример #2
0
        public virtual void TestActualTextForSubstitutedGlyphProcessingInSubstituteOneToMany01()
        {
            String expectedActualTextForFirstGlyph  = "0";
            String expectedActualTextForSecondGlyph = "A";

            byte[] ttf = StreamUtil.InputStreamToArray(new FileStream(iText.Test.TestUtil.GetParentProjectDirectory(NUnit.Framework.TestContext
                                                                                                                    .CurrentContext.TestDirectory) + "/resources/itext/io/font/otf/FreeSans.ttf", FileMode.Open, FileAccess.Read
                                                                      ));
            TrueTypeFont font = new TrueTypeFont(ttf);
            // no actual text for the second glyph is set - it should be created during substitution
            GlyphLine line = new GlyphLine(ConstructGlyphListFromString("AA", font));

            line.SetActualText(0, 1, expectedActualTextForFirstGlyph);
            line.idx = 1;
            line.SubstituteOneToMany(font.GetGsubTable(), new int[] { 39, 40 });
            NUnit.Framework.Assert.IsNotNull(line.actualText);
            NUnit.Framework.Assert.AreEqual(3, line.actualText.Count);
            NUnit.Framework.Assert.AreSame(line.actualText[1], line.actualText[2]);
            NUnit.Framework.Assert.AreEqual(expectedActualTextForSecondGlyph, line.actualText[1].value);
            // check that it hasn't been corrupted
            NUnit.Framework.Assert.AreEqual(expectedActualTextForFirstGlyph, line.actualText[0].value);
        }
Пример #3
0
        public static void Sample_String_To_CsvFile()
        {
            string data = @"Name;Address;Gpnr
John;Main Road; 4711
Jeffrey;;4712
Mike;Hauptstr.1;4713";

            string sampleDataPath = @"..\..\Samples\";
            var    watch          = new Stopwatch();

            using (Stream stream = StreamUtil.CreateStream(data))
            {
                using (var reader = new CsvAdapter(stream))
                {
                    reader.Separator = ";";

                    using (var writer = new CsvAdapter())
                    {
                        writer.FileName = sampleDataPath + "StringData.csv";

                        watch.Start();
                        int lineCount = 0;

                        reader.ReadData(30)
                        .ForEach(x =>
                        {
                            Console.WriteLine("Tablename=" + x.TableName + ", Count=" + x.Rows.Count);
                            lineCount += x.Rows.Count;
                        })
                        .Do(x => writer.WriteData(x));

                        watch.Stop();
                        Console.WriteLine("lineCount=" + lineCount + ", Time=" + watch.Elapsed);
                        Console.ReadLine();
                    }
                }
            }
        }
Пример #4
0
        private void SetAES256DicEntries(PdfDictionary encryptionDictionary, byte[] oeKey, byte[] ueKey, byte[] aes256Perms
                                         , bool encryptMetadata, bool embeddedFilesOnly)
        {
            int vAes256     = 5;
            int rAes256     = 5;
            int rAes256Pdf2 = 6;

            encryptionDictionary.Put(PdfName.OE, new PdfLiteral(StreamUtil.CreateEscapedString(oeKey)));
            encryptionDictionary.Put(PdfName.UE, new PdfLiteral(StreamUtil.CreateEscapedString(ueKey)));
            encryptionDictionary.Put(PdfName.Perms, new PdfLiteral(StreamUtil.CreateEscapedString(aes256Perms)));
            encryptionDictionary.Put(PdfName.R, new PdfNumber(isPdf2 ? rAes256Pdf2 : rAes256));
            encryptionDictionary.Put(PdfName.V, new PdfNumber(vAes256));
            PdfDictionary stdcf = new PdfDictionary();

            stdcf.Put(PdfName.Length, new PdfNumber(32));
            if (!encryptMetadata)
            {
                encryptionDictionary.Put(PdfName.EncryptMetadata, PdfBoolean.FALSE);
            }
            if (embeddedFilesOnly)
            {
                stdcf.Put(PdfName.AuthEvent, PdfName.EFOpen);
                encryptionDictionary.Put(PdfName.EFF, PdfName.StdCF);
                encryptionDictionary.Put(PdfName.StrF, PdfName.Identity);
                encryptionDictionary.Put(PdfName.StmF, PdfName.Identity);
            }
            else
            {
                stdcf.Put(PdfName.AuthEvent, PdfName.DocOpen);
                encryptionDictionary.Put(PdfName.StrF, PdfName.StdCF);
                encryptionDictionary.Put(PdfName.StmF, PdfName.StdCF);
            }
            stdcf.Put(PdfName.CFM, PdfName.AESV3);
            PdfDictionary cf = new PdfDictionary();

            cf.Put(PdfName.StdCF, stdcf);
            encryptionDictionary.Put(PdfName.CF, cf);
        }
Пример #5
0
        public static Volume Deserialize(Stream stream, String password, int maxPossibleSize)
        {
            Volume volume = new Volume();
            var    offset = CalculateOffset(password);

            //deserialize header
            stream.Seek(offset, SeekOrigin.Current);                                            //moves stream cursor passed offset
            var IV = StreamUtil.ReadBytes(stream, 32);                                          //read IV
            int encryptedDataLength = BitConverter.ToInt32(StreamUtil.ReadBytes(stream, 4), 0); //read length of the following encrypted data
            var algorithmNo         = Convert.ToInt16(StreamUtil.ReadBytes(stream, 1)[0]);

            volume.AlgorithmNo = algorithmNo;

            if (encryptedDataLength < 32 || encryptedDataLength > maxPossibleSize) //encryptedDataLength is not valid, so the specified password cannot be for this volume.
            {
                return(null);
            }

            byte[] encryptedBytes = StreamUtil.ReadBytes(stream, encryptedDataLength);

            //decrypt volume
            byte[] decryptedBytes = CryptoUtil.Decrypt256(encryptedBytes, IV, password, algorithmNo);

            //deserialize decrypted volume
            MemoryStream decryptedStream = new MemoryStream(decryptedBytes);

            byte[] cryptographicHash = StreamUtil.ReadBytes(decryptedStream, 32);

            //verify volume
            if (!cryptographicHash.SequenceEqual(CryptoUtil.GetSha256Hash(Encoding.UTF8.GetBytes(password))))
            {
                return(null);
            }

            volume.Folder = Folder.Deserialize(decryptedStream);

            return(volume);
        }
Пример #6
0
    public void ProcessClients()
    {
        foreach (var client in Clients)
        {
            if (client.Key.Available <= 0)
            {
                continue;
            }
            var stream   = client.Key.GetStream();
            var inBytes  = StreamUtil.Read(stream);
            var received = Encoding.UTF8.GetString(inBytes);
            if (Verbose)
            {
                Logger.Info($"Received message [{received}] from client {client.Value}", "INFO-VERBOSE");
            }

            client.Value.OnHeartbeat();
            if (!ProcessSpecial(client.Key, received))
            {
                ProcessMessage(client.Key, received);
            }
        }
    }
Пример #7
0
        /// <summary>
        /// Fills the stream buffer.
        /// </summary>
        /// <returns>true if the buffer has been filled, false if the end of the stream has been reached</returns>
        private bool FillBuffer()
        {
            // first, carry over unprocessed samples from the end of the stream buffer to its beginning
            streamBufferOffset = streamBufferLevel - frameOffset;
            if (streamBufferOffset > 0)
            {
                Buffer.BlockCopy(streamBuffer, frameOffset, streamBuffer, 0, streamBufferOffset);
            }
            frameOffset = 0;

            // second, fill the stream input buffer - if no bytes returned we have reached the end of the stream
            streamBufferLevel = StreamUtil.ForceRead(stream, streamBuffer,
                                                     streamBufferOffset, streamBuffer.Length - streamBufferOffset);
            if (streamBufferLevel == 0)
            {
                Debug.WriteLine("stream windowing finished - end position {0}/{1}", stream.Position, stream.Length);
                return(false); // whole stream has been processed
            }
            streamBufferLevel += streamBufferOffset;
            streamBufferOffset = 0;

            return(true); // stream buffer successfully filled
        }
Пример #8
0
    private void onTextEntered(string pInput)
    {
        if (pInput == null || pInput.Length == 0)
        {
            return;
        }

        _panelWrapper.ClearInput();

        try
        {
            //echo client - send one, expect one (hint: that is not how a chat works ...)
            byte[] outBytes = Encoding.UTF8.GetBytes(pInput);
            StreamUtil.Write(_client.GetStream(), outBytes);
        }
        catch (Exception e)
        {
            _panelWrapper.AddOutput(e.Message);
            //for quicker testing, we reconnect if something goes wrong.
            _client.Close();
            connectToServer();
        }
    }
Пример #9
0
        private OcspResp GetOcspResponse(X509Certificate checkCert, X509Certificate rootCert, String url)
        {
            if (checkCert == null || rootCert == null)
            {
                return(null);
            }
            if (url == null)
            {
                url = CertificateUtil.GetOCSPURL(checkCert);
            }
            if (url == null)
            {
                return(null);
            }
            LOGGER.Info("Getting OCSP from " + url);
            OcspReq request = GenerateOCSPRequest(rootCert, checkCert.SerialNumber);

            byte[] array = request.GetEncoded();
            Uri    urlt  = new Uri(url);
            Stream @in   = SignUtils.GetHttpResponseForOcspRequest(array, urlt);

            return(new OcspResp(StreamUtil.InputStreamToArray(@in)));
        }
Пример #10
0
 public virtual void SRGBImageTest()
 {
     using (FileStream fis = new FileStream(sourceFolder + "sRGBImage.png", FileMode.Open, FileAccess.Read)) {
         byte[] imageBytes = StreamUtil.InputStreamToArray(fis);
         // Test a more specific entry point
         ImageData img = ImageDataFactory.CreatePng(imageBytes);
         NUnit.Framework.Assert.AreEqual(ImageType.PNG, img.GetOriginalType());
         NUnit.Framework.Assert.AreEqual(50, img.GetWidth(), 0);
         NUnit.Framework.Assert.AreEqual(50, img.GetHeight(), 0);
         NUnit.Framework.Assert.AreEqual(96, img.GetDpiX());
         NUnit.Framework.Assert.AreEqual(96, img.GetDpiY());
         NUnit.Framework.Assert.AreEqual(2.2, ((PngImageData)img).GetGamma(), 0.0001f);
         PngChromaticities pngChromaticities = ((PngImageData)img).GetPngChromaticities();
         NUnit.Framework.Assert.AreEqual(0.3127f, pngChromaticities.GetXW(), 0.0001f);
         NUnit.Framework.Assert.AreEqual(0.329f, pngChromaticities.GetYW(), 0.0001f);
         NUnit.Framework.Assert.AreEqual(0.64f, pngChromaticities.GetXR(), 0.0001f);
         NUnit.Framework.Assert.AreEqual(0.33f, pngChromaticities.GetYR(), 0.0001f);
         NUnit.Framework.Assert.AreEqual(0.3f, pngChromaticities.GetXG(), 0.0001f);
         NUnit.Framework.Assert.AreEqual(0.6f, pngChromaticities.GetYG(), 0.0001f);
         NUnit.Framework.Assert.AreEqual(0.15f, pngChromaticities.GetXB(), 0.0001f);
         NUnit.Framework.Assert.AreEqual(0.06f, pngChromaticities.GetYB(), 0.0001f);
     }
 }
    private void processExistingClients()
    {
        for (int i = 0; i < _clients.Count; i++)
        {
            LobbyClient client = _clients[i];

            if (client.TcpClient.Available == 0)
            {
                continue;
            }

            byte[]        inBytes  = StreamUtil.Read(client.TcpClient.GetStream());
            Packet        inPacket = new Packet(inBytes);
            ISerializable inObject = inPacket.ReadObject();
            Console.WriteLine("Received:" + inObject);

            if (inObject is SimpleMessage)
            {
                SimpleMessage message = inObject as SimpleMessage;
                handleSimpleMessage(client, message);
            }
        }
    }
Пример #12
0
        /// <summary>
        /// Resizes a block of data in the file.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="tag">The tag that the block belongs to, if any.</param>
        /// <param name="startOffset">The offset where the block to resize begins at.</param>
        /// <param name="oldSize">The current size of the block to resize.</param>
        /// <param name="newSize">The new size of the block.</param>
        /// <exception cref="System.ArgumentException">Cannot resize a block to a negative size</exception>
        private void ResizeBlock(Stream stream, CachedTagInstance tag, long startOffset, long oldSize, long newSize)
        {
            if (newSize < 0)
            {
                throw new ArgumentException("Cannot resize a block to a negative size");
            }
            else if (oldSize == newSize)
            {
                return;
            }

            var oldEndOffset = startOffset + oldSize;
            var sizeDelta    = newSize - oldSize;

            if (stream.Length - oldEndOffset >= 0)
            {
                StreamUtil.Copy(stream, oldEndOffset, oldEndOffset + sizeDelta, stream.Length - oldEndOffset);
                FixTagOffsets(oldEndOffset, sizeDelta, tag);
            }
            else
            {
                return;
            }
        }
Пример #13
0
    public static ASCIIGridMetadata ReadMetadata(string path)
    {
        ASCIIGridMetadata metadata = new ASCIIGridMetadata();

        using (StreamReader input = new StreamReader(StreamUtil.GetFileStream(path))) {
            string line;
            bool   keepGoing = true;
            while (keepGoing && (line = input.ReadLine()) != null)
            {
                switch (line[0])
                {
                case ' ':
                    keepGoing = false;     // We hit the actual data, stop reading
                    break;

                default:
                    string[] keyValue = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    metadata.Set(keyValue[0], keyValue[1]);
                    break;
                }
            }
        }
        return(metadata);
    }
        public ushort CreateIndexBuffer(RenderGeometryApiResourceDefinition resourceDefinition, Stream outputStream, List <ushort> buffer)
        {
            resourceDefinition.IndexBuffers.Add(new TagStructureReference <IndexBufferDefinition>
            {
                Definition = new IndexBufferDefinition
                {
                    Format = IndexBufferFormat.TriangleStrip,
                    Data   = new TagData
                    {
                        Size     = buffer.Count() * 2,
                        Unused4  = 0,
                        Unused8  = 0,
                        Address  = new CacheAddress(),
                        Unused10 = 0
                    }
                }
            });

            var indexBuffer = resourceDefinition.IndexBuffers.Last().Definition;

            var indexCount = indexBuffer.Data.Size / 2;

            var outIndexStream = new EndianWriter(
                outputStream,
                EndianFormat.LittleEndian);

            StreamUtil.Align(outputStream, 4);
            indexBuffer.Data.Address = new CacheAddress(CacheAddressType.Resource, (int)outputStream.Position);

            for (var j = 0; j < indexCount; j++)
            {
                outIndexStream.Write((short)buffer[j]);
            }

            return((ushort)resourceDefinition.IndexBuffers.IndexOf(resourceDefinition.IndexBuffers.Last()));
        }
Пример #15
0
        public Task CreateImageAsync(ImagesCreateParameters parameters, Stream imageStream, AuthConfig authConfig, IProgress <JSONMessage> progress, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            HttpMethod           httpMethod = HttpMethod.Post;
            BinaryRequestContent content    = null;

            if (imageStream != null)
            {
                content            = new BinaryRequestContent(imageStream, TarContentType);
                parameters.FromSrc = ImportFromBodySource;
            }

            IQueryString queryParameters = new QueryString <ImagesCreateParameters>(parameters);

            return(StreamUtil.MonitorStreamForMessagesAsync(
                       this._client.MakeRequestForStreamAsync(this._client.NoErrorHandlers, httpMethod, "images/create", queryParameters, content, RegistryAuthHeaders(authConfig), cancellationToken),
                       this._client,
                       cancellationToken,
                       progress));
        }
Пример #16
0
        /// <summary>
        /// 获得网页的所有内容,将根据Response中的content-type读取网页内容编码,默认为 GBK;
        /// 但如果HTTP响应的头中标记了utf-8或者utf8,则转换为 UTF8 编码;
        /// </summary>
        /// <param name="url">网页的url</param>
        /// <param name="enc">网页的所有编码</param>
        /// <returns>网页的所有内容</returns>
        public static string ReadWeb(string url, Encoding enc)
        {
            string result = "";

            try
            {
                var request = HttpWebRequest.Create(url);
                using (var response = request.GetResponse())
                {
                    MemoryStream ms = new MemoryStream();
                    using (var stream = response.GetResponseStream())
                    {
                        StreamUtil.WriteStream(ms, stream);
                    }
                    byte[] bytes = ms.ToArray();
                    return(enc.GetString(bytes));
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.StackTrace);
            }
            return(result);
        }
Пример #17
0
        private void ReadFileEntries(EndianReader reader, ISerializationContext context, TagDeserializer deserializer)
        {
            Files = new Dictionary <string, Stream>();

            var section = GetSectionHeader(reader, ModPackageSection.Files);

            if (!GoToSectionHeaderOffset(reader, section))
            {
                return;
            }

            var fileTable = new GenericSectionEntry(reader);

            reader.BaseStream.Position = fileTable.TableOffset + section.Offset;
            for (int i = 0; i < fileTable.Count; i++)
            {
                var tableEntry = deserializer.Deserialize <FileTableEntry>(context);

                var stream = new MemoryStream();
                StreamUtil.Copy(reader.BaseStream, stream, tableEntry.Size);

                Files.Add(tableEntry.Path, stream);
            }
        }
Пример #18
0
 public ActionResult CreateFile(DocumentationFileViewModel vm)
 {
     if (ModelState.IsValid)
     {
         if (vm.FileData != null && vm.FileData.ContentLength > 0)
         {
             using (Stream fileStream = vm.FileData.InputStream)
             {
                 DocumentationFile file = new DocumentationFile();
                 file.FileName             = vm.FileData.FileName;
                 file.FileData             = StreamUtil.StreamToBytes(fileStream);
                 file.Title                = vm.Title;
                 file.Description          = vm.Description;
                 file.LastModifiedDate     = vm.LastModifiedDate.HasValue ? vm.LastModifiedDate.Value : DateTime.Now;
                 file.UploadedBy           = this.userTasks.GetAdminUser(User.Identity.Name);
                 file.UploadedDate         = DateTime.Now;
                 file.DocumentationFileTag = this.docTasks.GetDocumentationFileTag(vm.TagId);
                 file = this.docTasks.SaveDocumentationFile(file);
                 return(RedirectToAction("Manage"));
             }
         }
     }
     return(CreateFile());
 }
Пример #19
0
        public void StreamByte_ToBytes_ToStream_Test()
        {
            var bytes = Encoding.UTF8.GetBytes("Hello,world");

            using (var stream = StreamUtil.BufferToStream(bytes))
            {
                stream.Position = 1;
                var actualBytes = StreamUtil.StreamToBuffer(stream, 5);

                var newArray = new byte[bytes.Length];
                Array.Copy(actualBytes, 0, newArray, 0, bytes.Length);
                Assert.Equal(bytes.Length, newArray.Length);
                Assert.Equal(bytes, newArray);
            }

            using (var stream = StreamUtil.BufferToStream(bytes))
            {
                var actualBytes = StreamUtil.StreamToBuffer(stream);
                var newArray    = new byte[bytes.Length];
                Array.Copy(actualBytes, 0, newArray, 0, bytes.Length);
                Assert.Equal(bytes.Length, newArray.Length);
                Assert.Equal(bytes, newArray);
            }
        }
Пример #20
0
        internal static Dictionary <String, Object> ReadFontProperties(String name)
        {
            name += ".properties";
            Stream     isp = StreamUtil.GetResourceStream(RESOURCE_PATH_CMAP + name);
            Properties p   = new Properties();

            p.Load(isp);
            isp.Close();
            IntHashtable W = CreateMetric(p["W"]);

            p.Remove("W");
            IntHashtable W2 = CreateMetric(p["W2"]);

            p.Remove("W2");
            Dictionary <String, Object> map = new Dictionary <string, object>();

            foreach (string key in p.Keys)
            {
                map[key] = p[key];
            }
            map["W"]  = W;
            map["W2"] = W2;
            return(map);
        }
Пример #21
0
        private PdfArray GetEncodedRecipients()
        {
            PdfArray EncodedRecipients = new PdfArray();

            byte[] cms;
            for (int i = 0; i < recipients.Count; i++)
            {
                try {
                    cms = GetEncodedRecipient(i);
                    EncodedRecipients.Add(new PdfLiteral(StreamUtil.CreateEscapedString(cms)));
                }
                catch (GeneralSecurityException) {
                    EncodedRecipients = null;
                    // break was added while porting to itext7
                    break;
                }
                catch (System.IO.IOException) {
                    EncodedRecipients = null;
                    // break was added while porting to itext7
                    break;
                }
            }
            return(EncodedRecipients);
        }
Пример #22
0
 public virtual void SetUp()
 {
     StreamUtil.AddToResourceSearch(@"iTextAsian.dll");
 }
Пример #23
0
        private static void DecodePass(int xOffset, int yOffset, int xStep, int yStep, int passWidth, int passHeight
                                       , PngImageHelper.PngParameters png)
        {
            if ((passWidth == 0) || (passHeight == 0))
            {
                return;
            }
            int bytesPerRow = (png.inputBands * passWidth * png.bitDepth + 7) / 8;

            byte[] curr  = new byte[bytesPerRow];
            byte[] prior = new byte[bytesPerRow];
            // Decode the (sub)image row-by-row
            int srcY;
            int dstY;

            for (srcY = 0, dstY = yOffset; srcY < passHeight; srcY++, dstY += yStep)
            {
                // Read the filter type byte and a row of data
                int filter = 0;
                try {
                    filter = png.dataStream.Read();
                    StreamUtil.ReadFully(png.dataStream, curr, 0, bytesPerRow);
                }
                catch (Exception) {
                }
                switch (filter)
                {
                case PNG_FILTER_NONE: {
                    // empty on purpose
                    break;
                }

                case PNG_FILTER_SUB: {
                    DecodeSubFilter(curr, bytesPerRow, png.bytesPerPixel);
                    break;
                }

                case PNG_FILTER_UP: {
                    DecodeUpFilter(curr, prior, bytesPerRow);
                    break;
                }

                case PNG_FILTER_AVERAGE: {
                    DecodeAverageFilter(curr, prior, bytesPerRow, png.bytesPerPixel);
                    break;
                }

                case PNG_FILTER_PAETH: {
                    DecodePaethFilter(curr, prior, bytesPerRow, png.bytesPerPixel);
                    break;
                }

                default: {
                    // Error -- uknown filter type
                    throw new iText.IO.IOException(iText.IO.IOException.UnknownPngFilter);
                }
                }
                ProcessPixels(curr, xOffset, xStep, dstY, passWidth, png);
                // Swap curr and prior
                byte[] tmp = prior;
                prior = curr;
                curr  = tmp;
            }
        }
Пример #24
0
        /// <exception cref="System.IO.IOException"/>
        private static void ReadPng(Stream pngStream, PngImageHelper.PngParameters png)
        {
            for (int i = 0; i < PNGID.Length; i++)
            {
                if (PNGID[i] != pngStream.Read())
                {
                    throw new System.IO.IOException("file.is.not.a.valid.png");
                }
            }
            byte[] buffer = new byte[TRANSFERSIZE];
            while (true)
            {
                int    len    = GetInt(pngStream);
                String marker = GetString(pngStream);
                if (len < 0 || !CheckMarker(marker))
                {
                    throw new System.IO.IOException("corrupted.png.file");
                }
                if (IDAT.Equals(marker))
                {
                    int size;
                    while (len != 0)
                    {
                        size = pngStream.JRead(buffer, 0, Math.Min(len, TRANSFERSIZE));
                        if (size < 0)
                        {
                            return;
                        }
                        png.idat.Write(buffer, 0, size);
                        len -= size;
                    }
                }
                else
                {
                    if (tRNS.Equals(marker))
                    {
                        switch (png.colorType)
                        {
                        case 0: {
                            if (len >= 2)
                            {
                                len -= 2;
                                int gray = GetWord(pngStream);
                                if (png.bitDepth == 16)
                                {
                                    png.transRedGray = gray;
                                }
                                else
                                {
                                    png.additional.Put("Mask", MessageFormatUtil.Format("[{0} {1}]", gray, gray));
                                }
                            }
                            break;
                        }

                        case 2: {
                            if (len >= 6)
                            {
                                len -= 6;
                                int red   = GetWord(pngStream);
                                int green = GetWord(pngStream);
                                int blue  = GetWord(pngStream);
                                if (png.bitDepth == 16)
                                {
                                    png.transRedGray = red;
                                    png.transGreen   = green;
                                    png.transBlue    = blue;
                                }
                                else
                                {
                                    png.additional.Put("Mask", MessageFormatUtil.Format("[{0} {1} {2} {3} {4} {5}]", red, red, green, green, blue
                                                                                        , blue));
                                }
                            }
                            break;
                        }

                        case 3: {
                            if (len > 0)
                            {
                                png.trans = new byte[len];
                                for (int k = 0; k < len; ++k)
                                {
                                    png.trans[k] = (byte)pngStream.Read();
                                }
                                len = 0;
                            }
                            break;
                        }
                        }
                        StreamUtil.Skip(pngStream, len);
                    }
                    else
                    {
                        if (IHDR.Equals(marker))
                        {
                            png.width             = GetInt(pngStream);
                            png.height            = GetInt(pngStream);
                            png.bitDepth          = pngStream.Read();
                            png.colorType         = pngStream.Read();
                            png.compressionMethod = pngStream.Read();
                            png.filterMethod      = pngStream.Read();
                            png.interlaceMethod   = pngStream.Read();
                        }
                        else
                        {
                            if (PLTE.Equals(marker))
                            {
                                if (png.colorType == 3)
                                {
                                    Object[] colorspace = new Object[4];
                                    colorspace[0] = "/Indexed";
                                    colorspace[1] = GetColorspace(png);
                                    colorspace[2] = len / 3 - 1;
                                    ByteBuffer colorTableBuf = new ByteBuffer();
                                    while ((len--) > 0)
                                    {
                                        colorTableBuf.Append(pngStream.Read());
                                    }
                                    png.colorTable = colorTableBuf.ToByteArray();
                                    colorspace[3]  = PdfEncodings.ConvertToString(png.colorTable, null);
                                    png.additional.Put("ColorSpace", colorspace);
                                }
                                else
                                {
                                    StreamUtil.Skip(pngStream, len);
                                }
                            }
                            else
                            {
                                if (pHYs.Equals(marker))
                                {
                                    int dx   = GetInt(pngStream);
                                    int dy   = GetInt(pngStream);
                                    int unit = pngStream.Read();
                                    if (unit == 1)
                                    {
                                        png.dpiX = (int)(dx * 0.0254f + 0.5f);
                                        png.dpiY = (int)(dy * 0.0254f + 0.5f);
                                    }
                                    else
                                    {
                                        if (dy != 0)
                                        {
                                            png.XYRatio = (float)dx / (float)dy;
                                        }
                                    }
                                }
                                else
                                {
                                    if (cHRM.Equals(marker))
                                    {
                                        png.xW      = GetInt(pngStream) / 100000f;
                                        png.yW      = GetInt(pngStream) / 100000f;
                                        png.xR      = GetInt(pngStream) / 100000f;
                                        png.yR      = GetInt(pngStream) / 100000f;
                                        png.xG      = GetInt(pngStream) / 100000f;
                                        png.yG      = GetInt(pngStream) / 100000f;
                                        png.xB      = GetInt(pngStream) / 100000f;
                                        png.yB      = GetInt(pngStream) / 100000f;
                                        png.hasCHRM = !(Math.Abs(png.xW) < 0.0001f || Math.Abs(png.yW) < 0.0001f || Math.Abs(png.xR) < 0.0001f ||
                                                        Math.Abs(png.yR) < 0.0001f || Math.Abs(png.xG) < 0.0001f || Math.Abs(png.yG) < 0.0001f || Math.Abs(png
                                                                                                                                                           .xB) < 0.0001f || Math.Abs(png.yB) < 0.0001f);
                                    }
                                    else
                                    {
                                        if (sRGB.Equals(marker))
                                        {
                                            int ri = pngStream.Read();
                                            png.intent  = intents[ri];
                                            png.gamma   = 2.2f;
                                            png.xW      = 0.3127f;
                                            png.yW      = 0.329f;
                                            png.xR      = 0.64f;
                                            png.yR      = 0.33f;
                                            png.xG      = 0.3f;
                                            png.yG      = 0.6f;
                                            png.xB      = 0.15f;
                                            png.yB      = 0.06f;
                                            png.hasCHRM = true;
                                        }
                                        else
                                        {
                                            if (gAMA.Equals(marker))
                                            {
                                                int gm = GetInt(pngStream);
                                                if (gm != 0)
                                                {
                                                    png.gamma = 100000f / gm;
                                                    if (!png.hasCHRM)
                                                    {
                                                        png.xW      = 0.3127f;
                                                        png.yW      = 0.329f;
                                                        png.xR      = 0.64f;
                                                        png.yR      = 0.33f;
                                                        png.xG      = 0.3f;
                                                        png.yG      = 0.6f;
                                                        png.xB      = 0.15f;
                                                        png.yB      = 0.06f;
                                                        png.hasCHRM = true;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if (iCCP.Equals(marker))
                                                {
                                                    do
                                                    {
                                                        --len;
                                                    }while (pngStream.Read() != 0);
                                                    pngStream.Read();
                                                    --len;
                                                    byte[] icccom = new byte[len];
                                                    int    p      = 0;
                                                    while (len > 0)
                                                    {
                                                        int r = pngStream.JRead(icccom, p, len);
                                                        if (r < 0)
                                                        {
                                                            throw new System.IO.IOException("premature.end.of.file");
                                                        }
                                                        p   += r;
                                                        len -= r;
                                                    }
                                                    byte[] iccp = FilterUtil.FlateDecode(icccom, true);
                                                    icccom = null;
                                                    try {
                                                        png.iccProfile = IccProfile.GetInstance(iccp);
                                                    }
                                                    catch (Exception) {
                                                        png.iccProfile = null;
                                                    }
                                                }
                                                else
                                                {
                                                    if (IEND.Equals(marker))
                                                    {
                                                        break;
                                                    }
                                                    else
                                                    {
                                                        StreamUtil.Skip(pngStream, len);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                StreamUtil.Skip(pngStream, 4);
            }
        }
Пример #25
0
 /// <summary>Skips "len" amount of bytes from the InputStream.</summary>
 /// <remarks>Skips "len" amount of bytes from the InputStream. If len is &lt; 0, nothing is skipped.</remarks>
 /// <param name="len">amount of bytes needed to skip</param>
 /// <exception cref="System.IO.IOException"/>
 public virtual void Skip(int len)
 {
     length += len;
     StreamUtil.Skip(@in, len);
 }
Пример #26
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     StreamUtil.AddToResourceSearch(HttpContext.Current.Server.MapPath("~/AsianFonts/iTextAsian.dll"));
 }
Пример #27
0
 public override void WriteText(String text, PdfOutputStream stream)
 {
     StreamUtil.WriteHexedString(stream, ConvertToBytes(text));
 }
Пример #28
0
        private IEnumerator <string> GetEnumeratorImpl(Stream stream)
        {
            try
            {
                long position = stream.Length;

                if (encoding is UnicodeEncoding && (position & 1) != 0)
                {
                    throw new InvalidDataException("UTF-16 encoding provided, but stream has odd length.");
                }

                // Allow up to two bytes for data from the start of the previous
                // read which didn't quite make it as full characters
                byte[] buffer       = new byte[bufferSize + 2];
                char[] charBuffer   = new char[encoding.GetMaxCharCount(buffer.Length)];
                int    leftOverData = 0;
                String previousEnd  = null;
                // TextReader doesn't return an empty string if there's line break at the end
                // of the data. Therefore we don't return an empty string if it's our *first*
                // return.
                bool firstYield = true;

                // A line-feed at the start of the previous buffer means we need to swallow
                // the carriage-return at the end of this buffer - hence this needs declaring
                // way up here!
                bool swallowCarriageReturn = false;

                while (position > 0)
                {
                    int bytesToRead = Math.Min(position > int.MaxValue ? bufferSize : (int)position, bufferSize);

                    position       -= bytesToRead;
                    stream.Position = position;
                    StreamUtil.ReadExactly(stream, buffer, bytesToRead);
                    // If we haven't read a full buffer, but we had bytes left
                    // over from before, copy them to the end of the buffer
                    if (leftOverData > 0 && bytesToRead != bufferSize)
                    {
                        // Buffer.BlockCopy doesn't document its behaviour with respect
                        // to overlapping data: we *might* just have read 7 bytes instead of
                        // 8, and have two bytes to copy...
                        Array.Copy(buffer, bufferSize, buffer, bytesToRead, leftOverData);
                    }
                    // We've now *effectively* read this much data.
                    bytesToRead += leftOverData;

                    int firstCharPosition = 0;
                    while (!characterStartDetector(position + firstCharPosition, buffer[firstCharPosition]))
                    {
                        firstCharPosition++;
                        // Bad UTF-8 sequences could trigger this. For UTF-8 we should always
                        // see a valid character start in every 3 bytes, and if this is the start of the file
                        // so we've done a short read, we should have the character start
                        // somewhere in the usable buffer.
                        if (firstCharPosition == 3 || firstCharPosition == bytesToRead)
                        {
                            throw new InvalidDataException("Invalid UTF-8 data");
                        }
                    }
                    leftOverData = firstCharPosition;

                    int charsRead    = encoding.GetChars(buffer, firstCharPosition, bytesToRead - firstCharPosition, charBuffer, 0);
                    int endExclusive = charsRead;

                    for (int i = charsRead - 1; i >= 0; i--)
                    {
                        char lookingAt = charBuffer[i];
                        if (swallowCarriageReturn)
                        {
                            swallowCarriageReturn = false;
                            if (lookingAt == '\r')
                            {
                                endExclusive--;
                                continue;
                            }
                        }
                        // Anything non-line-breaking, just keep looking backwards
                        if (lookingAt != '\n' && lookingAt != '\r')
                        {
                            continue;
                        }
                        // End of CRLF? Swallow the preceding CR
                        if (lookingAt == '\n')
                        {
                            swallowCarriageReturn = true;
                        }
                        int    start          = i + 1;
                        string bufferContents = new string(charBuffer, start, endExclusive - start);
                        endExclusive = i;
                        string stringToYield = previousEnd == null ? bufferContents : bufferContents + previousEnd;
                        if (!firstYield || stringToYield.Length != 0)
                        {
                            yield return(stringToYield);
                        }
                        firstYield  = false;
                        previousEnd = null;
                    }

                    previousEnd = endExclusive == 0 ? null : (new string(charBuffer, 0, endExclusive) + previousEnd);

                    // If we didn't decode the start of the array, put it at the end for next time
                    if (leftOverData != 0)
                    {
                        Buffer.BlockCopy(buffer, 0, buffer, bufferSize, leftOverData);
                    }
                }
                if (leftOverData != 0)
                {
                    // At the start of the final buffer, we had the end of another character.
                    throw new InvalidDataException("Invalid UTF-8 data at start of stream");
                }
                if (firstYield && string.IsNullOrEmpty(previousEnd))
                {
                    yield break;
                }
                yield return(previousEnd ?? "");
            }
            finally
            {
                stream.Dispose();
            }
        }
Пример #29
0
 /// <summary>
 /// Reads data from a stream and decrypts it
 /// </summary>
 /// <param name="data_in">The stream to read the encrypted data from</param>
 /// <param name="dkey">Decryption key</param>
 /// <param name="length">Number of bytes to read from stream for decryption</param>
 /// <returns>The raw, decrypted data as a byte array</returns>
 public byte[] Decrypt(Stream data_in, ICipherParameters dkey, int length) => Decrypt(StreamUtil.Read(data_in, length), dkey);
Пример #30
0
 /// <summary>
 /// Reads data from a stream and encrypts it
 /// </summary>
 /// <param name="data_in">Stream to read from</param>
 /// <param name="ckey">Encryption key</param>
 /// <param name="length">Number of bytes to read from the stream for encryption</param>
 public byte[] Encrypt(Stream data_in, ICipherParameters ckey, int length) => Encrypt(StreamUtil.Read(data_in, length), ckey);