Readings and decodes protocol message fields.

This class is generally used by generated code to read appropriate primitives from the stream. It effectively encapsulates the lowest levels of protocol buffer format.

Repeated fields and map fields are not handled by this class; use RepeatedField{T} and MapField{TKey, TValue} to serialize such fields.

        /// <summary>
        /// Pick up 16 bytes IV from the front of cipher text, use it together with <paramref name="key"> to AES parse the protobuf stream.
        /// </summary>
        /// <typeparam name="P">Your protobuf type here.</typeparam>
        public static P ProtoFromStream <P>(Stream stream, byte[] key)
            where P : IMessage <P>, new()
        {
            //iOS used to complain about Protobuf doing JIT without this, not sure about now.
            Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");

            //This scheme we paste initialization vector as a header of the save file, so we just yank it back for use...
            byte[] ivRead = new byte[16];
            stream.Read(ivRead, 0, 16);

            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

            aes.Key = key;
            aes.IV  = ivRead;

            //Debug.Log($"Using {string.Join(",", des.Key.Select(x => x))} {string.Join(",", des.IV.Select(x => x))}");

            P loadedData = new P();

            using (var cryptoStream = new CryptoStream(stream, aes.CreateDecryptor(), CryptoStreamMode.Read))
            {
                using (Google.Protobuf.CodedInputStream cis = new Google.Protobuf.CodedInputStream(cryptoStream))
                {
                    loadedData = new MessageParser <P>(() => new P()).ParseFrom(cis);
                    return(loadedData);
                }
            }
        }
        /// <summary>
        /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64()
        /// </summary>
        private static void AssertReadVarint(byte[] data, ulong value)
        {
            CodedInputStream input = new CodedInputStream(data);
            Assert.AreEqual((uint) value, input.ReadRawVarint32());

            input = new CodedInputStream(data);
            Assert.AreEqual(value, input.ReadRawVarint64());
            Assert.IsTrue(input.IsAtEnd);

            // Try different block sizes.
            for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
            {
                input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
                Assert.AreEqual((uint) value, input.ReadRawVarint32());

                input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize));
                Assert.AreEqual(value, input.ReadRawVarint64());
                Assert.IsTrue(input.IsAtEnd);
            }

            // Try reading directly from a MemoryStream. We want to verify that it
            // doesn't read past the end of the input, so write an extra byte - this
            // lets us test the position at the end.
            MemoryStream memoryStream = new MemoryStream();
            memoryStream.Write(data, 0, data.Length);
            memoryStream.WriteByte(0);
            memoryStream.Position = 0;
            Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream));
            Assert.AreEqual(data.Length, memoryStream.Position);
        }
Exemple #3
0
 /// <summary>
 /// Merges data from the given byte array into an existing message.
 /// </summary>
 /// <param name="message">The message to merge the data into.</param>
 /// <param name="data">The data to merge, which must be protobuf-encoded binary data.</param>
 public static void MergeFrom(this IMessage message, byte[] data)
 {
     ProtoPreconditions.CheckNotNull(message, "message");
     ProtoPreconditions.CheckNotNull(data, "data");
     CodedInputStream input = new CodedInputStream(data);
     message.MergeFrom(input);
     input.CheckReadEndOfStreamTag();
 }
Exemple #4
0
 /// <summary>
 /// Merges data from the given stream into an existing message.
 /// </summary>
 /// <param name="message">The message to merge the data into.</param>
 /// <param name="input">Stream containing the data to merge, which must be protobuf-encoded binary data.</param>
 public static void MergeFrom(this IMessage message, Stream input)
 {
     ProtoPreconditions.CheckNotNull(message, "message");
     ProtoPreconditions.CheckNotNull(input, "input");
     CodedInputStream codedInput = new CodedInputStream(input);
     message.MergeFrom(codedInput);
     codedInput.CheckReadEndOfStreamTag();
 }
 /// <summary>
 /// Merges data from the given stream into an existing message.
 /// </summary>
 /// <param name="message">The message to merge the data into.</param>
 /// <param name="input">Stream containing the data to merge, which must be protobuf-encoded binary data.</param>
 public static void MergeFrom(this IMessage message, Stream input)
 {
     Preconditions.CheckNotNull(message, "message");
     Preconditions.CheckNotNull(input, "input");
     CodedInputStream codedInput = new CodedInputStream(input);
     message.MergeFrom(codedInput);
     codedInput.CheckLastTagWas(0);
 }
Exemple #6
0
 public void ByteStringToValueType ()
 {
     // From Google's protobuf documentation, varint encoding example:
     // 300 = 1010 1100 0000 0010 = 0xAC 0x02
     byte[] bytes = { 0xAC, 0x02 };
     var codedStream = new CodedInputStream (bytes);
     uint value = codedStream.ReadUInt32 ();
     Assert.AreEqual (300, value);
 }
Exemple #7
0
        public void MergeFrom(pb.CodedInputStream input)
        {
    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
            input.ReadRawMessage(this);
    #else
            uint tag;
            while ((tag = input.ReadTag()) != 0)
            {
                switch (tag)
                {
                default:
                    _unknownFields = pb.UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
                    break;

                case 10: {
                    ClientId = input.ReadString();
                    break;
                }

                case 18: {
                    MessageId = input.ReadString();
                    break;
                }

                case 24: {
                    Type = (MessageType)input.ReadEnum();
                    break;
                }

                case 34: {
                    if (time_ == null)
                    {
                        Time = new global.Google.Protobuf.WellKnownTypes.Timestamp();
                    }
                    input.ReadMessage(Time);
                    break;
                }

                case 40: {
                    Status = (MessageStatus)input.ReadEnum();
                    break;
                }

                case 50: {
                    Payload = input.ReadBytes();
                    break;
                }

                case 56: {
                    Response = (ResponseType)input.ReadEnum();
                    break;
                }
                }
            }
    #endif
        }
Exemple #8
0
        private void MergeAllFrom(List <Type> protoClasses, string pathToProtos1, string pathToProtos2)
        {
            if (pathToProtos1 == "" || pathToProtos2 == "")
            {
                MessageBox.Show("Please select data protos files first");
            }


            this.protoInstances1 = new List <object>();
            this.protoInstances2 = new List <object>();

            foreach (Type protoClass in protoClasses)
            {
                ConstructorInfo[] constructors = protoClass.GetConstructors();

                if (constructors.Count <ConstructorInfo>() > 0)
                {
                    try
                    {
                        var protoInstance1 = constructors[0].Invoke(null);
                        var protoInstance2 = constructors[0].Invoke(null);

                        IEnumerable <MethodInfo> protoMethods1 = (IEnumerable <MethodInfo>)protoInstance1.GetType().GetMethods();
                        IEnumerable <MethodInfo> protoMethods2 = (IEnumerable <MethodInfo>)protoInstance1.GetType().GetMethods();

                        var mergeFromList1 = protoMethods1.Where(m => m.Name == "MergeFrom").ToList();
                        var mergeFromList2 = protoMethods1.Where(m => m.Name == "MergeFrom").ToList();

                        var mergeFrom1 = mergeFromList1[1];
                        var mergeFrom2 = mergeFromList2[1];

                        byte[] protosBytes1 = File.ReadAllBytes(pathToProtos1);
                        var    googleCode1  = new Google.Protobuf.CodedInputStream(protosBytes1);

                        byte[] protosBytes2 = File.ReadAllBytes(pathToProtos2);
                        var    googleCode2  = new Google.Protobuf.CodedInputStream(protosBytes2);

                        mergeFrom1.Invoke(protoInstance1, new object[] { googleCode1 });
                        mergeFrom2.Invoke(protoInstance2, new object[] { googleCode2 });

                        protoInstances1.Add(protoInstance1);
                        protoInstances2.Add(protoInstance2);
                    }

                    catch (System.Reflection.TargetInvocationException i)
                    {
                    }
                }
            }
        }
Exemple #9
0
 /// <summary>
 /// Decode a value of the given type.
 /// Should not be called directly. This interface is used by service client stubs.
 /// </summary>
 public static object Decode(ByteString value, Type type, Connection client)
 {
     var stream = new CodedInputStream (value.ToByteArray ());
     if (type == typeof(double))
         return stream.ReadDouble ();
     else if (type == typeof(float))
         return stream.ReadFloat ();
     else if (type == typeof(int))
         return stream.ReadInt32 ();
     else if (type == typeof(long))
         return stream.ReadInt64 ();
     else if (type == typeof(uint))
         return stream.ReadUInt32 ();
     else if (type == typeof(ulong))
         return stream.ReadUInt64 ();
     else if (type == typeof(bool))
         return stream.ReadBool ();
     else if (type == typeof(string))
         return stream.ReadString ();
     else if (type == typeof(byte[]))
         return stream.ReadBytes ().ToByteArray ();
     else if (type.IsEnum)
         return stream.ReadInt32 ();
     else if (typeof(RemoteObject).IsAssignableFrom (type)) {
         if (client == null)
             throw new ArgumentException ("Client not passed when decoding remote object");
         var id = stream.ReadUInt64 ();
         if (id == 0)
             return null;
         return (RemoteObject)Activator.CreateInstance (type, client, id);
     } else if (typeof(IMessage).IsAssignableFrom (type)) {
         IMessage message = (IMessage)Activator.CreateInstance (type);
         message.MergeFrom (stream);
         return message;
     } else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof(IList<>))
         return DecodeList (value, type, client);
     else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof(IDictionary<,>))
         return DecodeDictionary (value, type, client);
     else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof(ISet<>))
         return DecodeSet (value, type, client);
     else if (type.IsGenericType &&
              (type.GetGenericTypeDefinition () == typeof(Tuple<>) ||
              type.GetGenericTypeDefinition () == typeof(Tuple<,>) ||
              type.GetGenericTypeDefinition () == typeof(Tuple<,,>) ||
              type.GetGenericTypeDefinition () == typeof(Tuple<,,,>) ||
              type.GetGenericTypeDefinition () == typeof(Tuple<,,,,>) ||
              type.GetGenericTypeDefinition () == typeof(Tuple<,,,,,>)))
         return DecodeTuple (value, type, client); // TODO: ugly handing of tuple types
     throw new ArgumentException (type + " is not a serializable type");
 }
Exemple #10
0
        private bool MergeFrom(Type protoClass, string pathToProtos1, string pathToProtos2)
        {
            if (pathToProtos1 == "" || pathToProtos2 == "")
            {
                return(false);
            }

            ConstructorInfo[] constructors = protoClass.GetConstructors();

            if (constructors.Count <ConstructorInfo>() > 0)
            {
                try
                {
                    var protoInstance1 = constructors[0].Invoke(null);
                    var protoInstance2 = constructors[0].Invoke(null);

                    IEnumerable <MethodInfo> protoMethods1 = (IEnumerable <MethodInfo>)protoInstance1.GetType().GetMethods();
                    IEnumerable <MethodInfo> protoMethods2 = (IEnumerable <MethodInfo>)protoInstance1.GetType().GetMethods();

                    var mergeFromList1 = protoMethods1.Where(m => m.Name == "MergeFrom").ToList();
                    var mergeFromList2 = protoMethods1.Where(m => m.Name == "MergeFrom").ToList();

                    var mergeFrom1 = mergeFromList1[1];
                    var mergeFrom2 = mergeFromList2[1];

                    byte[] protosBytes1 = File.ReadAllBytes(pathToProtos1);
                    var    googleCode1  = new Google.Protobuf.CodedInputStream(protosBytes1);

                    byte[] protosBytes2 = File.ReadAllBytes(pathToProtos2);
                    var    googleCode2  = new Google.Protobuf.CodedInputStream(protosBytes2);

                    mergeFrom1.Invoke(protoInstance1, new object[] { googleCode1 });
                    mergeFrom2.Invoke(protoInstance2, new object[] { googleCode2 });

                    this.proto1 = protoInstance1;
                    this.proto2 = protoInstance2;
                    return(true);
                }

                catch (System.Reflection.TargetInvocationException i)
                {
                    return(false);
                }
            }

            return(false);
        }
Exemple #11
0
 protected override int Read (ref Request request, byte[] data, int offset, int length)
 {
     try {
         var codedStream = new CodedInputStream (data, offset, length);
         // Get the protobuf message size
         int size = (int)codedStream.ReadUInt32 ();
         int totalSize = (int)codedStream.Position + size;
         // Check if enough data is available, if not then delay the decoding
         if (length < totalSize)
             return 0;
         // Decode the request
         request = Schema.KRPC.Request.Parser.ParseFrom (codedStream).ToMessage ();
         return totalSize;
     } catch (InvalidProtocolBufferException e) {
         throw new MalformedRequestException (e.Message);
     }
 }
Exemple #12
0
    private static PlayerData PlayerDataFromStream(Stream stream)
    {
        Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");         //So that iOS don't complain about protobuf's JITing

        //Try to get the IV..
        byte[] ivRead = new byte[8];
        stream.Read(ivRead, 0, 8);

        DESCryptoServiceProvider des = new DESCryptoServiceProvider();

        des.Key = Key;
        des.IV  = ivRead;

        PlayerData loadedData = new PlayerData();

        using (var cryptoStream = new CryptoStream(stream, des.CreateDecryptor(), CryptoStreamMode.Read))
        {
            using (Google.Protobuf.CodedInputStream cis = new Google.Protobuf.CodedInputStream(cryptoStream))
            {
                loadedData = PlayerData.Parser.ParseFrom(cis);
                return(loadedData);
            }
        }
    }
Exemple #13
0
 internal uint <ForUInt32> b__7_0(CodedInputStream input)
 {
     return(input.ReadUInt32());
 }
        public void TestCodedInputOutputPosition()
        {
            byte[] content = new byte[110];
            for (int i = 0; i < content.Length; i++)
                content[i] = (byte)i;

            byte[] child = new byte[120];
            {
                MemoryStream ms = new MemoryStream(child);
                CodedOutputStream cout = new CodedOutputStream(ms, 20);
                // Field 11: numeric value: 500
                cout.WriteTag(11, WireFormat.WireType.Varint);
                Assert.AreEqual(1, cout.Position);
                cout.WriteInt32(500);
                Assert.AreEqual(3, cout.Position);
                //Field 12: length delimited 120 bytes
                cout.WriteTag(12, WireFormat.WireType.LengthDelimited);
                Assert.AreEqual(4, cout.Position);
                cout.WriteBytes(ByteString.CopyFrom(content));
                Assert.AreEqual(115, cout.Position);
                // Field 13: fixed numeric value: 501
                cout.WriteTag(13, WireFormat.WireType.Fixed32);
                Assert.AreEqual(116, cout.Position);
                cout.WriteSFixed32(501);
                Assert.AreEqual(120, cout.Position);
                cout.Flush();
            }

            byte[] bytes = new byte[130];
            {
                CodedOutputStream cout = new CodedOutputStream(bytes);
                // Field 1: numeric value: 500
                cout.WriteTag(1, WireFormat.WireType.Varint);
                Assert.AreEqual(1, cout.Position);
                cout.WriteInt32(500);
                Assert.AreEqual(3, cout.Position);
                //Field 2: length delimited 120 bytes
                cout.WriteTag(2, WireFormat.WireType.LengthDelimited);
                Assert.AreEqual(4, cout.Position);
                cout.WriteBytes(ByteString.CopyFrom(child));
                Assert.AreEqual(125, cout.Position);
                // Field 3: fixed numeric value: 500
                cout.WriteTag(3, WireFormat.WireType.Fixed32);
                Assert.AreEqual(126, cout.Position);
                cout.WriteSFixed32(501);
                Assert.AreEqual(130, cout.Position);
                cout.Flush();
            }
            // Now test Input stream:
            {
                CodedInputStream cin = new CodedInputStream(new MemoryStream(bytes), new byte[50], 0, 0);
                Assert.AreEqual(0, cin.Position);
                // Field 1:
                uint tag = cin.ReadTag();
                Assert.AreEqual(1, tag >> 3);
                Assert.AreEqual(1, cin.Position);
                Assert.AreEqual(500, cin.ReadInt32());
                Assert.AreEqual(3, cin.Position);
                //Field 2:
                tag = cin.ReadTag();
                Assert.AreEqual(2, tag >> 3);
                Assert.AreEqual(4, cin.Position);
                int childlen = cin.ReadLength();
                Assert.AreEqual(120, childlen);
                Assert.AreEqual(5, cin.Position);
                int oldlimit = cin.PushLimit((int)childlen);
                Assert.AreEqual(5, cin.Position);
                // Now we are reading child message
                {
                    // Field 11: numeric value: 500
                    tag = cin.ReadTag();
                    Assert.AreEqual(11, tag >> 3);
                    Assert.AreEqual(6, cin.Position);
                    Assert.AreEqual(500, cin.ReadInt32());
                    Assert.AreEqual(8, cin.Position);
                    //Field 12: length delimited 120 bytes
                    tag = cin.ReadTag();
                    Assert.AreEqual(12, tag >> 3);
                    Assert.AreEqual(9, cin.Position);
                    ByteString bstr = cin.ReadBytes();
                    Assert.AreEqual(110, bstr.Length);
                    Assert.AreEqual((byte) 109, bstr[109]);
                    Assert.AreEqual(120, cin.Position);
                    // Field 13: fixed numeric value: 501
                    tag = cin.ReadTag();
                    Assert.AreEqual(13, tag >> 3);
                    // ROK - Previously broken here, this returned 126 failing to account for bufferSizeAfterLimit
                    Assert.AreEqual(121, cin.Position);
                    Assert.AreEqual(501, cin.ReadSFixed32());
                    Assert.AreEqual(125, cin.Position);
                    Assert.IsTrue(cin.IsAtEnd);
                }
                cin.PopLimit(oldlimit);
                Assert.AreEqual(125, cin.Position);
                // Field 3: fixed numeric value: 501
                tag = cin.ReadTag();
                Assert.AreEqual(3, tag >> 3);
                Assert.AreEqual(126, cin.Position);
                Assert.AreEqual(501, cin.ReadSFixed32());
                Assert.AreEqual(130, cin.Position);
                Assert.IsTrue(cin.IsAtEnd);
            }
        }
 public override void ReadValue(CodedInputStream stream)
 {
 }
Exemple #16
0
 internal float <ForFloat> b__13_0(CodedInputStream input)
 {
     return(input.ReadFloat());
 }
Exemple #17
0
 static object DecodeSet (CodedInputStream stream, Type type, IConnection client)
 {
     var encodedSet = KRPC.Schema.KRPC.Set.Parser.ParseFrom (stream);
     var set = (IEnumerable)(typeof(HashSet<>)
         .MakeGenericType (type.GetGenericArguments ().Single ())
         .GetConstructor (Type.EmptyTypes)
         .Invoke (null));
     MethodInfo methodInfo = type.GetMethod ("Add");
     foreach (var item in encodedSet.Items) {
         var decodedItem = Decode (item, type.GetGenericArguments ().Single (), client);
         methodInfo.Invoke (set, new [] { decodedItem });
     }
     return set;
 }
Exemple #18
0
 internal int <ForSInt32> b__4_0(CodedInputStream input)
 {
     return(input.ReadSInt32());
 }
Exemple #19
0
 static object DecodeMessage (CodedInputStream stream, Type type)
 {
     if (type == typeof(Request)) {
         var message = new Schema.KRPC.Request ();
         message.MergeFrom (stream);
         return message.ToMessage ();
     }
     throw new ArgumentException ("Cannot decode protocol buffer messages of type " + type);
 }
Exemple #20
0
 internal uint <ForFixed32> b__5_0(CodedInputStream input)
 {
     return(input.ReadFixed32());
 }
Exemple #21
0
 internal long <ForSFixed64> b__11_0(CodedInputStream input)
 {
     return(input.ReadSFixed64());
 }
Exemple #22
0
 public void MergeFrom(CodedInputStream input)
 {
     Invoke(0, input);
 }
        public void TestCodedInputOutputPosition()
        {
            byte[] content = new byte[110];
            for (int i = 0; i < content.Length; i++)
            {
                content[i] = (byte)i;
            }

            byte[] child = new byte[120];
            {
                MemoryStream      ms   = new MemoryStream(child);
                CodedOutputStream cout = new CodedOutputStream(ms, 20);
                // Field 11: numeric value: 500
                cout.WriteTag(11, WireFormat.WireType.Varint);
                Assert.AreEqual(1, cout.Position);
                cout.WriteInt32(500);
                Assert.AreEqual(3, cout.Position);
                //Field 12: length delimited 120 bytes
                cout.WriteTag(12, WireFormat.WireType.LengthDelimited);
                Assert.AreEqual(4, cout.Position);
                cout.WriteBytes(ByteString.CopyFrom(content));
                Assert.AreEqual(115, cout.Position);
                // Field 13: fixed numeric value: 501
                cout.WriteTag(13, WireFormat.WireType.Fixed32);
                Assert.AreEqual(116, cout.Position);
                cout.WriteSFixed32(501);
                Assert.AreEqual(120, cout.Position);
                cout.Flush();
            }

            byte[] bytes = new byte[130];
            {
                CodedOutputStream cout = new CodedOutputStream(bytes);
                // Field 1: numeric value: 500
                cout.WriteTag(1, WireFormat.WireType.Varint);
                Assert.AreEqual(1, cout.Position);
                cout.WriteInt32(500);
                Assert.AreEqual(3, cout.Position);
                //Field 2: length delimited 120 bytes
                cout.WriteTag(2, WireFormat.WireType.LengthDelimited);
                Assert.AreEqual(4, cout.Position);
                cout.WriteBytes(ByteString.CopyFrom(child));
                Assert.AreEqual(125, cout.Position);
                // Field 3: fixed numeric value: 500
                cout.WriteTag(3, WireFormat.WireType.Fixed32);
                Assert.AreEqual(126, cout.Position);
                cout.WriteSFixed32(501);
                Assert.AreEqual(130, cout.Position);
                cout.Flush();
            }
            // Now test Input stream:
            {
                CodedInputStream cin = new CodedInputStream(new MemoryStream(bytes), new byte[50], 0, 0, false);
                Assert.AreEqual(0, cin.Position);
                // Field 1:
                uint tag = cin.ReadTag();
                Assert.AreEqual(1, tag >> 3);
                Assert.AreEqual(1, cin.Position);
                Assert.AreEqual(500, cin.ReadInt32());
                Assert.AreEqual(3, cin.Position);
                //Field 2:
                tag = cin.ReadTag();
                Assert.AreEqual(2, tag >> 3);
                Assert.AreEqual(4, cin.Position);
                int childlen = cin.ReadLength();
                Assert.AreEqual(120, childlen);
                Assert.AreEqual(5, cin.Position);
                int oldlimit = cin.PushLimit((int)childlen);
                Assert.AreEqual(5, cin.Position);
                // Now we are reading child message
                {
                    // Field 11: numeric value: 500
                    tag = cin.ReadTag();
                    Assert.AreEqual(11, tag >> 3);
                    Assert.AreEqual(6, cin.Position);
                    Assert.AreEqual(500, cin.ReadInt32());
                    Assert.AreEqual(8, cin.Position);
                    //Field 12: length delimited 120 bytes
                    tag = cin.ReadTag();
                    Assert.AreEqual(12, tag >> 3);
                    Assert.AreEqual(9, cin.Position);
                    ByteString bstr = cin.ReadBytes();
                    Assert.AreEqual(110, bstr.Length);
                    Assert.AreEqual((byte)109, bstr[109]);
                    Assert.AreEqual(120, cin.Position);
                    // Field 13: fixed numeric value: 501
                    tag = cin.ReadTag();
                    Assert.AreEqual(13, tag >> 3);
                    // ROK - Previously broken here, this returned 126 failing to account for bufferSizeAfterLimit
                    Assert.AreEqual(121, cin.Position);
                    Assert.AreEqual(501, cin.ReadSFixed32());
                    Assert.AreEqual(125, cin.Position);
                    Assert.IsTrue(cin.IsAtEnd);
                }
                cin.PopLimit(oldlimit);
                Assert.AreEqual(125, cin.Position);
                // Field 3: fixed numeric value: 501
                tag = cin.ReadTag();
                Assert.AreEqual(3, tag >> 3);
                Assert.AreEqual(126, cin.Position);
                Assert.AreEqual(501, cin.ReadSFixed32());
                Assert.AreEqual(130, cin.Position);
                Assert.IsTrue(cin.IsAtEnd);
            }
        }
Exemple #24
0
 internal bool ContainsInputField(CodedInputStream stream, Type target, out Extension extension)
 {
     return(extensions.TryGetValue(new ObjectIntPair <Type>(target, WireFormat.GetTagFieldNumber(stream.LastTag)), out extension));
 }
Exemple #25
0
            internal static T Read <T>(CodedInputStream input, FieldCodec <T> codec)
            {
                int byteLimit = input.ReadLength();
                T   result;

                while (true)
                {
IL_FA:
                    uint arg_C8_0 = 1476935752u;
                    while (true)
                    {
                        uint num;
                        switch ((num = (arg_C8_0 ^ 2018772964u)) % 9u)
                        {
                        case 0u:
                            input.SkipLastField();
                            arg_C8_0 = 1768391466u;
                            continue;

                        case 1u:
                        {
                            uint num2;
                            arg_C8_0 = (((num2 = input.ReadTag()) == 0u) ? 789788880u : 1000495088u);
                            continue;
                        }

                        case 3u:
                            arg_C8_0 = (num * 422428889u ^ 15908708u);
                            continue;

                        case 4u:
                            result   = codec.Read(input);
                            arg_C8_0 = (num * 2015424451u ^ 1456283564u);
                            continue;

                        case 5u:
                        {
                            uint num2;
                            arg_C8_0 = ((num2 == codec.Tag) ? 627669222u : 345821031u);
                            continue;
                        }

                        case 6u:
                        {
                            input.CheckReadEndOfStreamTag();
                            int oldLimit;
                            input.PopLimit(oldLimit);
                            arg_C8_0 = (num * 1368242210u ^ 1133084529u);
                            continue;
                        }

                        case 7u:
                        {
                            int oldLimit = input.PushLimit(byteLimit);
                            result   = codec.DefaultValue;
                            arg_C8_0 = (num * 2466023856u ^ 3651674u);
                            continue;
                        }

                        case 8u:
                            goto IL_FA;
                        }
                        return(result);
                    }
                }
                return(result);
            }
Exemple #26
0
 internal double <ForDouble> b__14_0(CodedInputStream input)
 {
     return(input.ReadDouble());
 }
Exemple #27
0
        public void TestSlowPathAvoidance()
        {
            using (var ms = new MemoryStream())
            {
                CodedOutputStream output = new CodedOutputStream(ms);
                output.WriteTag(1, WireFormat.WireType.LengthDelimited);
                output.WriteBytes(ByteString.CopyFrom(new byte[100]));
                output.WriteTag(2, WireFormat.WireType.LengthDelimited);
                output.WriteBytes(ByteString.CopyFrom(new byte[100]));
                output.Flush();

                ms.Position = 0;
                CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0);

                uint tag = input.ReadTag();
                Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag));
                Assert.AreEqual(100, input.ReadBytes().Length);

                tag = input.ReadTag();
                Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag));
                Assert.AreEqual(100, input.ReadBytes().Length);
            }
        }
Exemple #28
0
 internal bool <ForBool> b__2_0(CodedInputStream input)
 {
     return(input.ReadBool());
 }
Exemple #29
0
        /// <summary>
        /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and
        /// expects them to fail with an InvalidProtocolBufferException whose
        /// description matches the given one.
        /// </summary>
        private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data)
        {
            CodedInputStream input = new CodedInputStream(data);
            var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32());
            Assert.AreEqual(expected.Message, exception.Message);

            input = new CodedInputStream(data);
            exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint64());
            Assert.AreEqual(expected.Message, exception.Message);

            // Make sure we get the same error when reading directly from a Stream.
            exception = Assert.Throws<InvalidProtocolBufferException>(() => CodedInputStream.ReadRawVarint32(new MemoryStream(data)));
            Assert.AreEqual(expected.Message, exception.Message);
        }
Exemple #30
0
 internal ulong <ForFixed64> b__10_0(CodedInputStream input)
 {
     return(input.ReadFixed64());
 }
        public void ResetSizeCounter()
        {
            CodedInputStream input = new CodedInputStream(
                new SmallBlockInputStream(new byte[256], 8));
            input.SetSizeLimit(16);
            input.ReadRawBytes(16);

            Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawByte());

            input.ResetSizeCounter();
            input.ReadRawByte(); // No exception thrown.

            Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawBytes(16));
        }
Exemple #32
0
 static object DecodeList (CodedInputStream stream, Type type, IConnection client)
 {
     var encodedList = KRPC.Schema.KRPC.List.Parser.ParseFrom (stream);
     var list = (IList)(typeof(List<>)
         .MakeGenericType (type.GetGenericArguments ().Single ())
         .GetConstructor (Type.EmptyTypes)
         .Invoke (null));
     foreach (var item in encodedList.Items)
         list.Add (Decode (item, type.GetGenericArguments ().Single (), client));
     return list;
 }
Exemple #33
0
 public void MergeFrom(pb.CodedInputStream input)
 {
     throw new System.NotImplementedException();
 }
Exemple #34
0
 internal ulong <ForUInt64> b__12_0(CodedInputStream input)
 {
     return(input.ReadUInt64());
 }
Exemple #35
0
 internal ByteString <ForBytes> b__1_0(CodedInputStream input)
 {
     return(input.ReadBytes());
 }
Exemple #36
0
 internal long <ForSInt64> b__9_0(CodedInputStream input)
 {
     return(input.ReadSInt64());
 }
Exemple #37
0
 internal string <ForString> b__0_0(CodedInputStream input)
 {
     return(input.ReadString());
 }
Exemple #38
0
 public void Dispose_DisposesUnderlyingStream()
 {
     var memoryStream = new MemoryStream();
     Assert.IsTrue(memoryStream.CanRead);
     using (var cis = new CodedInputStream(memoryStream))
     {
     }
     Assert.IsFalse(memoryStream.CanRead); // Disposed
 }
Exemple #39
0
 public void Dispose_WithLeaveOpen()
 {
     var memoryStream = new MemoryStream();
     Assert.IsTrue(memoryStream.CanRead);
     using (var cis = new CodedInputStream(memoryStream, true))
     {
     }
     Assert.IsTrue(memoryStream.CanRead); // We left the stream open
 }
Exemple #40
0
        public void ReadInvalidUtf8()
        {
            MemoryStream ms = new MemoryStream();
            CodedOutputStream output = new CodedOutputStream(ms);

            uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
            output.WriteRawVarint32(tag);
            output.WriteRawVarint32(1);
            output.WriteRawBytes(new byte[] {0x80});
            output.Flush();
            ms.Position = 0;

            CodedInputStream input = new CodedInputStream(ms);

            Assert.AreEqual(tag, input.ReadTag());
            string text = input.ReadString();
            Assert.AreEqual('\ufffd', text[0]);
        }
Exemple #41
0
 static object DecodeDictionary (CodedInputStream stream, Type type, IConnection client)
 {
     var encodedDictionary = KRPC.Schema.KRPC.Dictionary.Parser.ParseFrom (stream);
     var dictionary = (IDictionary)(typeof(Dictionary<,>)
         .MakeGenericType (type.GetGenericArguments () [0], type.GetGenericArguments () [1])
         .GetConstructor (Type.EmptyTypes)
         .Invoke (null));
     foreach (var entry in encodedDictionary.Entries) {
         var key = Decode (entry.Key, type.GetGenericArguments () [0], client);
         var value = Decode (entry.Value, type.GetGenericArguments () [1], client);
         dictionary [key] = value;
     }
     return dictionary;
 }
Exemple #42
0
        public void RecursionLimitAppliedWhileSkippingGroup()
        {
            var stream = new MemoryStream();
            var output = new CodedOutputStream(stream);
            for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
            {
                output.WriteTag(1, WireFormat.WireType.StartGroup);
            }
            for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++)
            {
                output.WriteTag(1, WireFormat.WireType.EndGroup);
            }
            output.Flush();
            stream.Position = 0;

            // Now act like a generated client
            var input = new CodedInputStream(stream);
            Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag());
            Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
        }
Exemple #43
0
 static object DecodeTuple (CodedInputStream stream, Type type, IConnection client)
 {
     var encodedTuple = KRPC.Schema.KRPC.Tuple.Parser.ParseFrom (stream);
     var valueTypes = type.GetGenericArguments ().ToArray ();
     var genericType = Type.GetType ("System.Tuple`" + valueTypes.Length.ToString ());
     var values = new object[valueTypes.Length];
     for (int i = 0; i < valueTypes.Length; i++) {
         var item = encodedTuple.Items [i];
         values [i] = Decode (item, valueTypes [i], client);
     }
     var tuple = genericType
         .MakeGenericType (valueTypes)
         .GetConstructor (valueTypes)
         .Invoke (values);
     return tuple;
 }
Exemple #44
0
        public void SkipGroup()
        {
            // Create an output stream with a group in:
            // Field 1: string "field 1"
            // Field 2: group containing:
            //   Field 1: fixed int32 value 100
            //   Field 2: string "ignore me"
            //   Field 3: nested group containing
            //      Field 1: fixed int64 value 1000
            // Field 3: string "field 3"
            var stream = new MemoryStream();
            var output = new CodedOutputStream(stream);
            output.WriteTag(1, WireFormat.WireType.LengthDelimited);
            output.WriteString("field 1");

            // The outer group...
            output.WriteTag(2, WireFormat.WireType.StartGroup);
            output.WriteTag(1, WireFormat.WireType.Fixed32);
            output.WriteFixed32(100);
            output.WriteTag(2, WireFormat.WireType.LengthDelimited);
            output.WriteString("ignore me");
            // The nested group...
            output.WriteTag(3, WireFormat.WireType.StartGroup);
            output.WriteTag(1, WireFormat.WireType.Fixed64);
            output.WriteFixed64(1000);
            // Note: Not sure the field number is relevant for end group...
            output.WriteTag(3, WireFormat.WireType.EndGroup);

            // End the outer group
            output.WriteTag(2, WireFormat.WireType.EndGroup);

            output.WriteTag(3, WireFormat.WireType.LengthDelimited);
            output.WriteString("field 3");
            output.Flush();
            stream.Position = 0;

            // Now act like a generated client
            var input = new CodedInputStream(stream);
            Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
            Assert.AreEqual("field 1", input.ReadString());
            Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
            input.SkipLastField(); // Should consume the whole group, including the nested one.
            Assert.AreEqual(WireFormat.MakeTag(3, WireFormat.WireType.LengthDelimited), input.ReadTag());
            Assert.AreEqual("field 3", input.ReadString());
        }
Exemple #45
0
            internal void Main()
            {
                client = new TcpClient ();
                client.Connect (address, port);
                stream = client.GetStream ();
                stream.Write (Encoder.streamHelloMessage, 0, Encoder.streamHelloMessage.Length);
                stream.Write (clientIdentifier, 0, clientIdentifier.Length);
                var recvOkMessage = new byte [Encoder.okMessage.Length];
                stream.Read (recvOkMessage, 0, Encoder.okMessage.Length);
                if (recvOkMessage.Equals (Encoder.okMessage))
                    throw new Exception ("Invalid hello message received from stream server. " +
                    "Got " + Encoder.ToHexString (recvOkMessage));
                this.codedStream = new CodedInputStream (stream);

                try {
                    while (true) {
                        var message = new StreamMessage ();
                        codedStream.ReadMessage (message);
                        foreach (var response in message.Responses)
                            manager.Update (response.Id, response.Response);
                    }
                } catch (IOException) {
                    // Exit when the connection closes
                }
            }
Exemple #46
0
 public void Tag0Throws()
 {
     var input = new CodedInputStream(new byte[] { 0 });
     Assert.Throws<InvalidProtocolBufferException>(() => input.ReadTag());
 }
Exemple #47
0
 /// <summary>
 /// Tries to merge a field from the coded input, returning true if the field was merged.
 /// If the set is null or the field was not otherwise merged, this returns false.
 /// </summary>
 public static bool TryMergeFieldFrom <TTarget>(ref ExtensionSet <TTarget> set, CodedInputStream stream) where TTarget : IExtendableMessage <TTarget>
 {
     ParseContext.Initialize(stream, out ParseContext ctx);
     try
     {
         return(TryMergeFieldFrom <TTarget>(ref set, ref ctx));
     }
     finally
     {
         ctx.CopyStateTo(stream);
     }
 }
Exemple #48
0
 internal int <ForSFixed32> b__6_0(CodedInputStream input)
 {
     return(input.ReadSFixed32());
 }
Exemple #49
0
        public void ReadMaliciouslyLargeBlob()
        {
            MemoryStream ms = new MemoryStream();
            CodedOutputStream output = new CodedOutputStream(ms);

            uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited);
            output.WriteRawVarint32(tag);
            output.WriteRawVarint32(0x7FFFFFFF);
            output.WriteRawBytes(new byte[32]); // Pad with a few random bytes.
            output.Flush();
            ms.Position = 0;

            CodedInputStream input = new CodedInputStream(ms);
            Assert.AreEqual(tag, input.ReadTag());

            Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes());
        }
Exemple #50
0
 public void MergeFrom(CodedInputStream input)
 {
     hasValue = true;
     codec.ValueMerger(input, ref field);
 }
Exemple #51
0
        public void RogueEndGroupTag()
        {
            // If we have an end-group tag without a leading start-group tag, generated
            // code will just call SkipLastField... so that should fail.

            var stream = new MemoryStream();
            var output = new CodedOutputStream(stream);
            output.WriteTag(1, WireFormat.WireType.EndGroup);
            output.Flush();
            stream.Position = 0;

            var input = new CodedInputStream(stream);
            Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.EndGroup), input.ReadTag());
            Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
        }
Exemple #52
0
 public void MergeFrom(CodedInputStream input)
 {
     field.AddEntriesFrom(input, codec);
 }
Exemple #53
0
        public void SkipGroup_WrongEndGroupTag()
        {
            // Create an output stream with:
            // Field 1: string "field 1"
            // Start group 2
            //   Field 3: fixed int32
            // End group 4 (should give an error)
            var stream = new MemoryStream();
            var output = new CodedOutputStream(stream);
            output.WriteTag(1, WireFormat.WireType.LengthDelimited);
            output.WriteString("field 1");

            // The outer group...
            output.WriteTag(2, WireFormat.WireType.StartGroup);
            output.WriteTag(3, WireFormat.WireType.Fixed32);
            output.WriteFixed32(100);
            output.WriteTag(4, WireFormat.WireType.EndGroup);
            output.Flush();
            stream.Position = 0;

            // Now act like a generated client
            var input = new CodedInputStream(stream);
            Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag());
            Assert.AreEqual("field 1", input.ReadString());
            Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag());
            Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
        }
Exemple #54
0
        public void ReadTag_ZeroFieldRejected(byte tag)
        {
            CodedInputStream cis = new CodedInputStream(new byte[] { tag });

            Assert.Throws <InvalidProtocolBufferException>(() => cis.ReadTag());
        }
Exemple #55
0
 public void TestNegativeEnum()
 {
     byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 };
     CodedInputStream input = new CodedInputStream(bytes);
     Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum());
     Assert.IsTrue(input.IsAtEnd);
 }
Exemple #56
0
        public void Dispose_FromByteArray()
        {
            var stream = new CodedInputStream(new byte[10]);

            stream.Dispose();
        }
Exemple #57
0
        /// <summary>
        /// Parses the given bytes using ReadRawLittleEndian64() and checks
        /// that the result matches the given value.
        /// </summary>
        private static void AssertReadLittleEndian64(byte[] data, ulong value)
        {
            CodedInputStream input = new CodedInputStream(data);
            Assert.AreEqual(value, input.ReadRawLittleEndian64());
            Assert.IsTrue(input.IsAtEnd);

            // Try different block sizes.
            for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
            {
                input = new CodedInputStream(
                    new SmallBlockInputStream(data, blockSize));
                Assert.AreEqual(value, input.ReadRawLittleEndian64());
                Assert.IsTrue(input.IsAtEnd);
            }
        }
 public static void Initialize(CodedInputStream codedInputStream, out SegmentedBufferHelper instance)
 {
     instance.totalLength = codedInputStream.InternalInputStream == null ? (int?)codedInputStream.InternalBuffer.Length : null;
     instance.readOnlySequenceEnumerator = default;
     instance.codedInputStream           = codedInputStream;
 }
Exemple #59
0
        public void EndOfStreamReachedWhileSkippingGroup()
        {
            var stream = new MemoryStream();
            var output = new CodedOutputStream(stream);
            output.WriteTag(1, WireFormat.WireType.StartGroup);
            output.WriteTag(2, WireFormat.WireType.StartGroup);
            output.WriteTag(2, WireFormat.WireType.EndGroup);

            output.Flush();
            stream.Position = 0;

            // Now act like a generated client
            var input = new CodedInputStream(stream);
            input.ReadTag();
            Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField);
        }
Exemple #60
0
        public void Tag0Throws()
        {
            var input = new CodedInputStream(new byte[] { 0 });

            Assert.Throws <InvalidProtocolBufferException>(() => input.ReadTag());
        }