예제 #1
0
        protected override async Task Write(object value, WriteBuffer buf, LengthCache lengthCache, [CanBeNull] NpgsqlParameter parameter,
                                            bool async, CancellationToken cancellationToken)
        {
            ArraySegment <byte> segment;

            if (value is ArraySegment <byte> )
            {
                segment = (ArraySegment <byte>)value;
                if (!(parameter == null || parameter.Size <= 0 || parameter.Size >= segment.Count))
                {
                    segment = new ArraySegment <byte>(segment.Array, segment.Offset, parameter.Size);
                }
            }
            else
            {
                var array = (byte[])value;
                var len   = parameter == null || parameter.Size <= 0 || parameter.Size >= array.Length
                    ? array.Length
                    : parameter.Size;
                segment = new ArraySegment <byte>(array, 0, len);
            }

            // The entire segment fits in our buffer, copy it as usual.
            if (segment.Count <= buf.WriteSpaceLeft)
            {
                buf.WriteBytes(segment.Array, segment.Offset, segment.Count);
                return;
            }

            // The segment is larger than our buffer. Flush whatever is currently in the buffer and
            // write the array directly to the socket.
            await buf.Flush(async, cancellationToken);

            buf.DirectWrite(segment.Array, segment.Offset, segment.Count);
        }
예제 #2
0
    internal async Task WriteSASLInitialResponse(string mechanism, byte[] initialResponse, bool async, CancellationToken cancellationToken = default)
    {
        var len = sizeof(byte) +                                                // Message code
                  sizeof(int) +                                                 // Length
                  PGUtil.UTF8Encoding.GetByteCount(mechanism) + sizeof(byte) +  // Mechanism plus null terminator
                  sizeof(int) +                                                 // Initial response length
                  (initialResponse?.Length ?? 0);                               // Initial response payload

        if (WriteBuffer.WriteSpaceLeft < len)
        {
            await WriteBuffer.Flush(async, cancellationToken);
        }

        WriteBuffer.WriteByte(FrontendMessageCode.Password);
        WriteBuffer.WriteInt32(len - 1);

        WriteBuffer.WriteString(mechanism);
        WriteBuffer.WriteByte(0);   // null terminator
        if (initialResponse == null)
        {
            WriteBuffer.WriteInt32(-1);
        }
        else
        {
            WriteBuffer.WriteInt32(initialResponse.Length);
            WriteBuffer.WriteBytes(initialResponse);
        }
    }
예제 #3
0
        private void WriteImage(IImage image)
        {
            if (characterMarshal.HasMarshalled(image))
            {
                /* Been there, done that. */
                return;
            }

            ImageBlob blob = image as ImageBlob;

            if (blob == null)
            {
                throw new SWFModellerException(SWFModellerError.Internal, "Can't write " + image.ToString());
            }

            switch (blob.DataFormat)
            {
            case Tag.DefineBitsJPEG2:
            case Tag.DefineBitsLossless:
            case Tag.DefineBitsLossless2:
                WriteBuffer blobBuffer = OpenTag(blob.DataFormat);
                blobBuffer.WriteUI16((uint)characterMarshal.GetIDFor(image));
                blobBuffer.WriteBytes(blob.FormattedBytes);
                CloseTag();
                break;

            case Tag.DefineBits:
                if (blob.JPEGTable != null)
                {
                    if (writtenJPEGTable != null && writtenJPEGTable != blob.JPEGTable)
                    {
                        /* ISSUE 16 */
                        throw new SWFModellerException(SWFModellerError.UnimplementedFeature,
                                                       "Can't process multiple JPEG encoding tables yet.");
                    }

                    WriteBuffer tables = OpenTag(Tag.JPEGTables);
                    tables.WriteBytes(blob.JPEGTable.TableData);
                    CloseTag();

                    writtenJPEGTable = blob.JPEGTable;
                }

                WriteBuffer bits = OpenTag(Tag.DefineBits);
                bits.WriteUI16((uint)characterMarshal.GetIDFor(image));
                bits.WriteBytes(blob.FormattedBytes);
                CloseTag();
                break;

            default:
                throw new SWFModellerException(SWFModellerError.Internal, "Can't write image format " + blob.DataFormat.ToString());;
            }
        }
예제 #4
0
        public void WriteZeroChars()
        {
            // Fill up the buffer entirely
            WriteBuffer.WriteBytes(new byte[WriteBuffer.Size], 0, WriteBuffer.Size);
            Assert.That(WriteBuffer.WriteSpaceLeft, Is.Zero);

            int  charsUsed;
            bool completed;

            WriteBuffer.WriteStringChunked("hello".ToCharArray(), 0, 5, true, out charsUsed, out completed);
            Assert.That(charsUsed, Is.Zero);
            Assert.That(completed, Is.False);
        }
예제 #5
0
        public void ChunkedByteArrayEncodingFits()
        {
            WriteBuffer.WriteBytes(new byte[WriteBuffer.Size - 1], 0, WriteBuffer.Size - 1);
            Assert.That(WriteBuffer.WriteSpaceLeft, Is.EqualTo(1));

            var charsUsed = 1;
            var completed = true;

            // This unicode character is three bytes when encoded in UTF8
            Assert.That(() => WriteBuffer.WriteStringChunked("\uD55C".ToCharArray(), 0, 1, true, out charsUsed, out completed), Throws.Nothing);
            Assert.That(charsUsed, Is.EqualTo(0));
            Assert.That(completed, Is.False);
        }
예제 #6
0
        public void Chunked_char_array_encoding_fits_with_surrogates()
        {
            WriteBuffer.WriteBytes(new byte[WriteBuffer.Size - 1]);
            Assert.That(WriteBuffer.WriteSpaceLeft, Is.EqualTo(1));

            var charsUsed = 1;
            var completed = true;
            var cyclone   = "🌀";

            Assert.That(() => WriteBuffer.WriteStringChunked(cyclone.ToCharArray(), 0, cyclone.Length, true, out charsUsed, out completed), Throws.Nothing);
            Assert.That(charsUsed, Is.EqualTo(0));
            Assert.That(completed, Is.False);
        }
예제 #7
0
        internal static void DoWrite(object value, WriteBuffer buf, bool isCidrHandler)
        {
            IPAddress ip;
            int       mask;

            if (value is NpgsqlInet)
            {
                var inet = ((NpgsqlInet)value);
                ip   = inet.Address;
                mask = inet.Netmask;
            }
            else
            {
                ip = value as IPAddress;
                if (ip == null)
                {
                    throw new InvalidCastException($"Can't send type {value.GetType()} as inet");
                }
                mask = -1;
            }

            switch (ip.AddressFamily)
            {
            case AddressFamily.InterNetwork:
                buf.WriteByte(IPv4);
                if (mask == -1)
                {
                    mask = 32;
                }
                break;

            case AddressFamily.InterNetworkV6:
                buf.WriteByte(IPv6);
                if (mask == -1)
                {
                    mask = 128;
                }
                break;

            default:
                throw new InvalidCastException(
                          $"Can't handle IPAddress with AddressFamily {ip.AddressFamily}, only InterNetwork or InterNetworkV6!");
            }

            buf.WriteByte((byte)mask);
            buf.WriteByte((byte)(isCidrHandler ? 1 : 0));  // Ignored on server side
            var bytes = ip.GetAddressBytes();

            buf.WriteByte((byte)bytes.Length);
            buf.WriteBytes(bytes, 0, bytes.Length);
        }
예제 #8
0
        protected override void Write(object value, WriteBuffer buf, NpgsqlParameter parameter = null)
        {
            if (parameter?.ConvertedValue != null)
            {
                value = parameter.ConvertedValue;
            }

            var bytes = ((Guid)value).ToByteArray();

            buf.WriteInt32(BitConverter.ToInt32(bytes, 0));
            buf.WriteInt16(BitConverter.ToInt16(bytes, 4));
            buf.WriteInt16(BitConverter.ToInt16(bytes, 6));
            buf.WriteBytes(bytes, 8, 8);
        }
예제 #9
0
        internal override void WriteFully(WriteBuffer buf)
        {
            buf.WriteByte(Code);
            buf.WriteInt32(Length - 1);

            buf.WriteString(_mechanism);
            buf.WriteByte(0);   // null terminator
            if (_initialResponse == null)
            {
                buf.WriteInt32(-1);
            }
            else
            {
                buf.WriteInt32(_initialResponse.Length);
                buf.WriteBytes(_initialResponse);
            }
        }
예제 #10
0
    internal Task WritePregenerated(byte[] data, bool async = false, CancellationToken cancellationToken = default)
    {
        if (WriteBuffer.WriteSpaceLeft < data.Length)
        {
            return(FlushAndWrite(data, async, cancellationToken));
        }

        WriteBuffer.WriteBytes(data, 0, data.Length);
        return(Task.CompletedTask);

        async Task FlushAndWrite(byte[] data, bool async, CancellationToken cancellationToken)
        {
            await Flush(async, cancellationToken);

            Debug.Assert(data.Length <= WriteBuffer.WriteSpaceLeft, $"Pregenerated message has length {data.Length} which is bigger than the buffer ({WriteBuffer.WriteSpaceLeft})");
            WriteBuffer.WriteBytes(data, 0, data.Length);
        }
    }
예제 #11
0
    internal async Task WritePassword(byte[] payload, int offset, int count, bool async, CancellationToken cancellationToken = default)
    {
        if (WriteBuffer.WriteSpaceLeft < sizeof(byte) + sizeof(int))
        {
            await WriteBuffer.Flush(async, cancellationToken);
        }
        WriteBuffer.WriteByte(FrontendMessageCode.Password);
        WriteBuffer.WriteInt32(sizeof(int) + count);

        if (count <= WriteBuffer.WriteSpaceLeft)
        {
            // The entire array fits in our WriteBuffer, copy it into the WriteBuffer as usual.
            WriteBuffer.WriteBytes(payload, offset, count);
            return;
        }

        await WriteBuffer.Flush(async, cancellationToken);

        await WriteBuffer.DirectWrite(new ReadOnlyMemory <byte>(payload, offset, count), async, cancellationToken);
    }
예제 #12
0
        internal override async Task Write(WriteBuffer buf, bool async, CancellationToken cancellationToken)
        {
            if (buf.WriteSpaceLeft < 1 + 5)
            {
                await buf.Flush(async);
            }
            buf.WriteByte(Code);
            buf.WriteInt32(4 + PayloadLength);

            if (PayloadLength <= buf.WriteSpaceLeft)
            {
                // The entire array fits in our buffer, copy it into the buffer as usual.
                buf.WriteBytes(Payload, PayloadOffset, Payload.Length);
                return;
            }

            await buf.Flush(async);

            buf.DirectWrite(Payload, PayloadOffset, PayloadLength);
        }
예제 #13
0
        // ReSharper disable once RedundantAssignment
        public override bool Write(ref DirectBuffer directBuf)
        {
            // If we're back here after having returned a direct buffer, we're done.
            if (_returnedBuffer)
            {
                _returnedBuffer = false;
                return(true);
            }

            // If the entire array fits in our buffer, copy it as usual.
            // Otherwise, switch to direct write from the user-provided buffer
            if (_value.Count <= _writeBuf.WriteSpaceLeft)
            {
                _writeBuf.WriteBytes(_value.Array, _value.Offset, _value.Count);
                return(true);
            }

            directBuf.Buffer = _value.Array;
            directBuf.Offset = _value.Offset;
            directBuf.Size   = _value.Count;
            _returnedBuffer  = true;
            return(false);
        }
예제 #14
0
 internal override void WriteFully(WriteBuffer buf)
 {
     buf.WriteByte(Code);
     buf.WriteInt32(Length - 1);
     buf.WriteBytes(Payload, PayloadOffset, Payload.Length);
 }
예제 #15
0
 internal override void WriteFully(WriteBuffer buf)
 {
     buf.WriteBytes(_data, 0, _data.Length);
 }
예제 #16
0
 internal override void WriteFully(WriteBuffer buf)
 {
     buf.WriteBytes(_data, 0, _data.Length);
 }
예제 #17
0
 internal override void WriteFully(WriteBuffer buf)
 {
     buf.WriteByte(Code);
     buf.WriteInt32(Length - 1);
     buf.WriteBytes(Password, 0, Password.Length);
 }
예제 #18
0
        private void WriteFont(SWFFont font, int fid)
        {
            WriteBuffer fontTag = this.OpenTag(Tag.DefineFont3, font.Name + "; id=" + fid);

            char[] codes = font.CodePoints;

            /* Tag.DefineFont3 */
            {
                fontTag.WriteUI16((uint)fid);

                fontTag.WriteBit(font.HasLayout);

                fontTag.WriteBit(false); /* ISSUE 50: ShiftJIS support */
                fontTag.WriteBit(font.IsSmall);
                fontTag.WriteBit(false); /* ISSUE 51: ANSI support, though I think this might never be false. */

                fontTag.WriteBit(true);  /* ISSUE 52: We always write wide offsets. This is because we're too lazy to measure our table. */
                fontTag.WriteBit(true);  /* Spec says must be true. */

                fontTag.WriteBit(font.IsItalic);
                fontTag.WriteBit(font.IsBold);

                fontTag.WriteUI8((uint)font.LanguageCode);

                fontTag.WriteString(font.Name, true);

                fontTag.WriteUI16((uint)font.GlyphCount);

                byte[][] shapeData       = new byte[font.GlyphCount][];
                int      totalShapeBytes = 0;
                for (int i = 0; i < font.GlyphCount; i++)
                {
                    Tag format;
                    shapeData[i] = ShapeWriter.ShapeToBytes(font.GetGlyphShape(codes[i]), out format);

                    if (format != Tag.DefineFont3)
                    {
                        throw new SWFModellerException(SWFModellerError.Internal, "Can't write non-font shapes as glyphs");
                    }

                    totalShapeBytes += shapeData[i].Length;
                }

                int startOffset = font.GlyphCount * 4 + 4; /* 4 bytes per offset (wide offsets) + 4 for the code table offset */
                int nextOffset  = startOffset;
                foreach (byte[] shapeBytes in shapeData)
                {
                    fontTag.WriteUI32((uint)nextOffset);
                    nextOffset += shapeBytes.Length;
                }

                fontTag.WriteUI32((uint)(startOffset + totalShapeBytes));

                foreach (byte[] shapeBytes in shapeData)
                {
                    fontTag.WriteBytes(shapeBytes);
                }

                foreach (char code in codes)
                {
                    fontTag.WriteUI16((uint)code);
                }

                if (font.HasLayout)
                {
                    fontTag.WriteSI16(font.Ascent.Value);
                    fontTag.WriteSI16(font.Descent.Value);
                    fontTag.WriteSI16(font.Leading.Value);

                    Rect[] bounds    = new Rect[font.GlyphCount];
                    int    boundsPos = 0;
                    foreach (char c in codes)
                    {
                        GlyphLayout gl = font.GetLayout(c);
                        fontTag.WriteSI16(gl.Advance);
                        bounds[boundsPos++] = gl.Bounds;
                    }

                    foreach (Rect bound in bounds)
                    {
                        fontTag.WriteRect(bound);
                        fontTag.Align8();
                    }

                    fontTag.WriteUI16((uint)font.KerningTable.Length);
                    foreach (KerningPair kern in font.KerningTable)
                    {
                        fontTag.WriteUI16(kern.LeftChar);
                        fontTag.WriteUI16(kern.RightChar);
                        fontTag.WriteSI16(kern.Adjustment);
                    }
                }
            }

            this.CloseTag();

            if (font.HasPixelAlignment)
            {
                WriteBuffer zonesTag = this.OpenTag(Tag.DefineFontAlignZones, font.Name + "; id=" + fid);

                zonesTag.WriteUI16((uint)fid);

                if (font.ThicknessHint == null)
                {
                    throw new SWFModellerException(SWFModellerError.Internal, "Can't have pixel aligmnent without a font thickness hint.");
                }

                zonesTag.WriteUBits((uint)font.ThicknessHint, 2);
                zonesTag.WriteUBits(0, 6); /* Reserved */

                foreach (char c in codes)
                {
                    PixelAlignment pa = font.GetPixelAligment(c);

                    if (pa.ZoneInfo.Length != 2)
                    {
                        throw new SWFModellerException(SWFModellerError.Internal, "Pixel aligment should always have 2 zones.");
                    }

                    zonesTag.WriteUI8((uint)pa.ZoneInfo.Length);

                    foreach (PixelAlignment.ZoneData zi in pa.ZoneInfo)
                    {
                        /* These int values are just unparsed 16-bit floats. */
                        zonesTag.WriteUI16((uint)zi.AlignmentCoord);
                        zonesTag.WriteUI16((uint)zi.Range);
                    }

                    zonesTag.WriteUBits(0, 6); /* Reserved */
                    zonesTag.WriteBit(pa.HasY);
                    zonesTag.WriteBit(pa.HasX);
                }

                this.CloseTag();
            }

            if (font.HasExtraNameInfo)
            {
                WriteBuffer nameTag = this.OpenTag(Tag.DefineFontName, font.FullName + "; id=" + fid);

                nameTag.WriteUI16((uint)fid);
                nameTag.WriteString(font.FullName);
                nameTag.WriteString(font.Copyright);

                this.CloseTag();
            }
        }
예제 #19
0
        private void WriteCharacter(ICharacter ch, ListSet <Timeline> unboundClasses)
        {
            int cid;

            if (ch == null)
            {
                return;
            }

            if (this.characterMarshal.HasMarshalled(ch))
            {
                return;
            }

            int fontID = -1;

            if (ch is IFontUserProcessor)
            {
                IFontUserProcessor fup = (IFontUserProcessor)ch;
                fup.FontUserProc(delegate(IFontUser fu)
                {
                    if (fu.HasFont && !characterMarshal.HasMarshalled(fu.Font))
                    {
                        fontID = characterMarshal.GetIDFor(fu.Font);
                        this.WriteFont(fu.Font, fontID);
                    }
                    else
                    {
                        fontID = characterMarshal.GetExistingIDFor(fu.Font);
                    }
                });
            }

            if (ch is IShape)
            {
                IImage[] images = ((IShape)ch).GetImages();

                if (images != null)
                {
                    foreach (IImage image in images)
                    {
                        this.WriteImage(image);
                    }
                }

                Tag    format;
                byte[] shapeBytes = ShapeWriter.ShapeToBytes((IShape)ch, out format);

                WriteBuffer shapeTag = this.OpenTag(format);
                cid = this.characterMarshal.GetIDFor(ch);
                shapeTag.WriteUI16((uint)cid);
                shapeTag.WriteBytes(shapeBytes);
#if DEBUG
                this.LogMessage("char id=" + cid);
#endif
                this.CloseTag();
            }
            else if (ch is Sprite)
            {
                this.WriteSprite((Sprite)ch, unboundClasses);
            }
            else if (ch is EditText)
            {
                this.WriteEditText((EditText)ch, fontID);
            }
            else if (ch is StaticText)
            {
                this.WriteStaticText((StaticText)ch);
            }
            else
            {
                /* ISSUE 73 */
                throw new SWFModellerException(
                          SWFModellerError.UnimplementedFeature,
                          "Character of type " + ch.GetType().ToString() + " not currently supported in writer");
            }

            if (ch is Timeline)
            {
                Timeline tl = (Timeline)ch;
                if (tl.HasClass && !(tl.Class is AdobeClass) && !unboundClasses.Contains(tl))
                {
                    unboundClasses.Add(tl);
                }
            }
        }
예제 #20
0
        /// <summary>
        /// Does the grunt-work of writing all the objects in the SWF file, tagging
        /// each of them with a record header.
        /// </summary>
        private void WriteTags()
        {
            /* Start with a file attributes tag */
            this.WriteFileAttributesTag();
            /* Despite background color being specified in the header, flash always puts this in too. */
            this.WriteBGColorTag();

            if (swf.ProtectHash != null)
            {
                /* ISSUE 45: This should be an option of some kind. */
                WriteBuffer protectTag = this.OpenTag(Tag.Protect);
                protectTag.WriteUI16(0); /* Reserved, always 0 */
                protectTag.WriteString(swf.ProtectHash);
                this.CloseTag();
            }

            if (this.options.EnableDebugger)
            {
                WriteBuffer dbugTag = this.OpenTag(Tag.EnableDebugger2);
                dbugTag.WriteUI16(0);                                /* Reserved, always 0 */
                dbugTag.WriteString("$1$ZH$B14iwyCzzcXcqLaJz0Mif0"); /* MD5-encoded password "abc"; http://devadraco.blogspot.com/2009/06/guide-to-cracking-enabledebugger2.html */
                this.CloseTag();
            }

            /* ISSUE 46: Write DefineSceneAndFrameLabelData tag */
            foreach (DoABC abc in this.swf.Scripts)
            {
                WriteBuffer abcOut = this.OpenTag(Tag.DoABC);

                abcOut.WriteUI32((uint)(abc.IsLazilyInitialized ? ABCValues.AbcFlagLazyInitialize : 0));
                abcOut.WriteString(abc.Name);

                AbcWriter abcWriter = new AbcWriter();
                abcWriter.AssembleIfNecessary(
                    abc,
                    this.options.EnableDebugger,
                    this.swf.Class == null ? null : this.swf.Class.QualifiedName,
                    this.abcWriteLog);

                abcOut.WriteBytes(abc.Bytecode);

                this.CloseTag();
            }

            ListSet <Timeline> writtenSymbolClasses = new ListSet <Timeline>();
            ListSet <Timeline> unboundClasses       = new ListSet <Timeline>();

            foreach (Sprite exported in this.swf.ExportOnFirstFrame)
            {
                this.WriteSprite(exported, unboundClasses);
            }

            this.BindClasses(unboundClasses);

            if (this.swf.FrameCount > 0)
            {
                int writtenFrames = 0;

                if (this.swf.HasClass)
                {
                    WriteBuffer scbuf = this.OpenTag(Tag.SymbolClass);
                    scbuf.WriteUI16(1);                              /* Count */
                    scbuf.WriteUI16(0);                              /* Character ref */
                    scbuf.WriteString(this.swf.Class.QualifiedName); /* Name */
                    this.LogMessage(this.swf.Class.QualifiedName);
                    this.CloseTag();
                }

                foreach (Frame f in this.swf.Frames)
                {
                    if (f.HasLabel)
                    {
#if DEBUG
                        this.LogMessage("frame label=" + f.Label);
#endif
                        WriteBuffer labelWriter = this.OpenTag(Tag.FrameLabel);
                        labelWriter.WriteString(f.Label);
                        this.CloseTag();
                    }

                    foreach (IDisplayListItem dli in f.DisplayList)
                    {
                        switch (dli.Type)
                        {
                        case DisplayListItemType.PlaceObjectX:
                            this.WriteCharacter(((ICharacterReference)dli).Character, unboundClasses);
                            this.WritePlaceObjectTag((PlaceObject)dli);
                            break;

                        case DisplayListItemType.RemoveObjectX:
                        default:
                            this.WriteRemoveObjectTag((RemoveObject)dli);
                            break;
                        }
                    }

                    this.BindClasses(unboundClasses);

                    this.WriteBodylessTag(Tag.ShowFrame);

                    writtenFrames++;

                    List <SymbolClass> symbolClasses = new List <SymbolClass>();
                }
            }
            else
            {
                /* No SWF should be frameless. Awwww. */
                this.WriteBodylessTag(Tag.ShowFrame);
            }

            /* Finish with an end tag */
            this.WriteBodylessTag(Tag.End);
        }
예제 #21
0
        protected override void Write(object value, WriteBuffer buf, NpgsqlParameter parameter)
        {
            var bytes = ((PhysicalAddress)value).GetAddressBytes();

            buf.WriteBytes(bytes, 0, bytes.Length);
        }
예제 #22
0
 public override void Write(object value, WriteBuffer buf, NpgsqlParameter parameter)
 {
     buf.WriteBytes(((PhysicalAddress)value).GetAddressBytes(), 0, 6);
 }
예제 #23
0
 protected override void Write(object value, WriteBuffer buf, NpgsqlParameter parameter = null)
 => buf.WriteBytes(((PhysicalAddress)value).GetAddressBytes(), 0, 6);
예제 #24
0
 internal override void WriteFully(WriteBuffer buf)
 {
     buf.WriteByte(Code);
     buf.WriteInt32(Length - 1);
     buf.WriteBytes(Password, 0, Password.Length);
 }