CVE-2019-11938: Allocation of Resources Without Limits or Throttling (CWE-770)
value: Java Facebook Thrift servers would not error upon receiving messages declaring containers of sizes larger than the payload. As a result, malicious clients could send short messages which would result in a large memory allocation, potentially leading to denial of service. This issue affects Facebook Thrift prior to v2019.12.09.00.
CWE description: The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
CVSS v3 base score: 7.5
Published: 2020-03-10T21:15Z
Repository: https://github.com/facebook/fbthrift
Language: Java
Files changed: thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TBinaryProtocol.java, thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TCompactProtocol.java, thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TProtocol.java, thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TProtocolDecorator.java, thrift/lib/java/src/resources/testing_data_structures.thrift, thrift/lib/java/src/test/java/com/facebook/thrift/StructTest.java, thrift/lib/java/src/test/java/com/facebook/thrift/TruncatedFrameTest.java
Commit date: 2019-12-06 13:13:54 -0800
Commit message: Java: Check the size of the remaining frame before deserializing collection

Summary:
In order to avoid over-allocating memory for malformed or truncated frame, we ensure that we have enough data (we only check for the lower bound) in the current frame.

This is a partial fix for CVE-2019-11938.

Reviewed By: vitaut

Differential Revision: D14500775

fbshipit-source-id: ca8b38965514d6319addcb72c8999a6854a94a88

Diff: diff --git a/thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TBinaryProtocol.java b/thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TBinaryProtocol.java
index 097adeff0..3f4740a76 100644
--- a/thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TBinaryProtocol.java
+++ b/thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TBinaryProtocol.java
@@ -223,23 +223,33 @@ public class TBinaryProtocol extends TProtocol {
   }
 
   public void readFieldEnd() {}
 
   public TMap readMapBegin() throws TException {
-    return new TMap(readByte(), readByte(), readI32());
+    byte keyType = readByte();
+    byte valueType = readByte();
+    int size = readI32();
+    ensureMapHasEnough(size, keyType, valueType);
+    return new TMap(keyType, valueType, size);
   }
 
   public void readMapEnd() {}
 
   public TList readListBegin() throws TException {
-    return new TList(readByte(), readI32());
+    byte type = readByte();
+    int size = readI32();
+    ensureContainerHasEnough(size, type);
+    return new TList(type, size);
   }
 
   public void readListEnd() {}
 
   public TSet readSetBegin() throws TException {
-    return new TSet(readByte(), readI32());
+    byte type = readByte();
+    int size = readI32();
+    ensureContainerHasEnough(size, type);
+    return new TSet(type, size);
   }
 
   public void readSetEnd() {}
 
   public boolean readBool() throws TException {
@@ -366,6 +376,37 @@ public class TBinaryProtocol extends TProtocol {
       if (readLength_ < 0) {
         throw new TException("Message length exceeded: " + length);
       }
     }
   }
+
+  @Override
+  protected int typeMinimumSize(byte type) {
+    switch (type & 0x0f) {
+      case TType.BOOL:
+      case TType.BYTE:
+        return 1;
+      case TType.I16:
+        return 2;
+      case TType.I32:
+      case TType.FLOAT:
+        return 4;
+      case TType.DOUBLE:
+      case TType.I64:
+        return 8;
+      case TType.STRING:
+        return 4;
+      case TType.LIST:
+      case TType.SET:
+        // type (1 byte) + size (4 bytes)
+        return 1 + 4;
+      case TType.MAP:
+        // key type (1 byte) + value type (1 byte) + size (4 bytes)
+        return 1 + 1 + 4;
+      case TType.STRUCT:
+        return 1;
+      default:
+        throw new TProtocolException(
+            TProtocolException.INVALID_DATA, "Unexpected data type " + (byte) (type & 0x0f));
+    }
+  }
 }
diff --git a/thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TCompactProtocol.java b/thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TCompactProtocol.java
index 7bc03289d..1a33ddc78 100755
--- a/thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TCompactProtocol.java
+++ b/thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TCompactProtocol.java
@@ -511,12 +511,16 @@ public class TCompactProtocol extends TProtocol {
    * means that 0-length maps will yield TMaps without the "correct" types.
    */
   public TMap readMapBegin() throws TException {
     int size = readVarint32();
     byte keyAndValueType = size == 0 ? 0 : readByte();
-    return new TMap(
-        getTType((byte) (keyAndValueType >> 4)), getTType((byte) (keyAndValueType & 0xf)), size);
+    byte keyType = getTType((byte) (keyAndValueType >> 4));
+    byte valueType = getTType((byte) (keyAndValueType & 0xf));
+    if (size > 0) {
+      ensureMapHasEnough(size, keyType, valueType);
+    }
+    return new TMap(keyType, valueType, size);
   }
 
   /**
    * Read a list header off the wire. If the list size is 0-14, the size will be packed into the
    * element type header. If it's a longer list, the 4 MSB of the element type header will be 0xF,
@@ -527,10 +531,11 @@ public class TCompactProtocol extends TProtocol {
     int size = (size_and_type >> 4) & 0x0f;
     if (size == 15) {
       size = readVarint32();
     }
     byte type = getTType(size_and_type);
+    ensureContainerHasEnough(size, type);
     return new TList(type, size);
   }
 
   /**
    * Read a set header off the wire. If the set size is 0-14, the size will be packed into the
@@ -827,6 +832,32 @@ public class TCompactProtocol extends TProtocol {
 
   /** Given a TType value, find the appropriate TCompactProtocol.Types constant. */
   private byte getCompactType(byte ttype) {
     return ttypeToCompactType[ttype];
   }
+
+  @Override
+  protected int typeMinimumSize(byte type) {
+    switch (type & 0x0f) {
+      case TType.BOOL:
+      case TType.BYTE:
+      case TType.I16: // because of variable length encoding
+      case TType.I32: // because of variable length encoding
+      case TType.I64: // because of variable length encoding
+        return 1;
+      case TType.FLOAT:
+        return 4;
+      case TType.DOUBLE:
+        return 8;
+      case TType.STRING:
+      case TType.STRUCT:
+      case TType.MAP:
+      case TType.SET:
+      case TType.LIST:
+      case TType.ENUM:
+        return 1;
+      default:
+        throw new TProtocolException(
+            TProtocolException.INVALID_DATA, "Unexpected data type " + (byte) (type & 0x0f));
+    }
+  }
 }
diff --git a/thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TProtocol.java b/thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TProtocol.java
index 083e9083f..813aff839 100644
--- a/thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TProtocol.java
+++ b/thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TProtocol.java
@@ -177,6 +177,33 @@ public abstract class TProtocol {
 
   /** Scheme accessor */
   public Class<? extends IScheme> getScheme() {
     return StandardScheme.class;
   }
+
+  /** Return the minimum size of a type */
+  protected int typeMinimumSize(byte type) {
+    return 1;
+  }
+
+  protected void ensureContainerHasEnough(int size, byte type) {
+    int minimumExpected = size * typeMinimumSize(type);
+    ensureHasEnoughBytes(minimumExpected);
+  }
+
+  protected void ensureMapHasEnough(int size, byte keyType, byte valueType) {
+    int minimumExpected = size * (typeMinimumSize(keyType) + typeMinimumSize(valueType));
+    ensureHasEnoughBytes(minimumExpected);
+  }
+
+  private void ensureHasEnoughBytes(int minimumExpected) {
+    int remaining = trans_.getBytesRemainingInBuffer();
+    if (remaining < 0) {
+      return; // Some transport are not buffered
+    }
+    if (remaining < minimumExpected) {
+      throw new TProtocolException(
+          TProtocolException.INVALID_DATA,
+          "Not enough bytes to read the entire message, the data appears to be truncated");
+    }
+  }
 }
diff --git a/thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TProtocolDecorator.java b/thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TProtocolDecorator.java
index 5156493f0..248cb0f42 100644
--- a/thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TProtocolDecorator.java
+++ b/thrift/lib/java/src/main/java/com/facebook/thrift/protocol/TProtocolDecorator.java
@@ -215,6 +215,11 @@ public abstract class TProtocolDecorator extends TProtocol {
   }
 
   public byte[] readBinary() throws TException {
     return concreteProtocol.readBinary();
   }
+
+  @Override
+  protected int typeMinimumSize(byte type) {
+    return concreteProtocol.typeMinimumSize(type);
+  }
 }
diff --git a/thrift/lib/java/src/resources/testing_data_structures.thrift b/thrift/lib/java/src/resources/testing_data_structures.thrift
index 938f0a51b..1c3d738c5 100644
--- a/thrift/lib/java/src/resources/testing_data_structures.thrift
+++ b/thrift/lib/java/src/resources/testing_data_structures.thrift
@@ -12,11 +12,12 @@
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
-namespace java com.facebook.thrift.test
+namespace java com.facebook.thrift.java.test
+namespace java.swift com.facebook.thrift.javaswift.test
 
 struct MySimpleStruct {
   1: i64 id,
   2: string name,
 }
@@ -47,5 +48,17 @@ enum BigEnum {
   SEVENTEEN = 17,
   EIGHTEEN = 18,
   NINETEEN = 19,
   TWENTY = 20,
 }
+
+struct MyListStruct {
+  1: list<i64> ids
+}
+
+struct MySetStruct {
+  1: set<i64> ids
+}
+
+struct MyMapStruct {
+  1: map<i64, string> mapping
+}
diff --git a/thrift/lib/java/src/test/java/com/facebook/thrift/StructTest.java b/thrift/lib/java/src/test/java/com/facebook/thrift/StructTest.java
index 054445e44..4c1e6df3f 100644
--- a/thrift/lib/java/src/test/java/com/facebook/thrift/StructTest.java
+++ b/thrift/lib/java/src/test/java/com/facebook/thrift/StructTest.java
@@ -19,13 +19,13 @@ package com.facebook.thrift;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.not;
 import static org.hamcrest.core.Is.is;
 import static org.junit.Assert.assertThat;
 
-import com.facebook.thrift.test.BigEnum;
-import com.facebook.thrift.test.MySimpleStruct;
-import com.facebook.thrift.test.SmallEnum;
+import com.facebook.thrift.java.test.BigEnum;
+import com.facebook.thrift.java.test.MySimpleStruct;
+import com.facebook.thrift.java.test.SmallEnum;
 import junit.framework.TestCase;
 import org.junit.Test;
 
 public class StructTest extends TestCase {
   @Test
diff --git a/thrift/lib/java/src/test/java/com/facebook/thrift/TruncatedFrameTest.java b/thrift/lib/java/src/test/java/com/facebook/thrift/TruncatedFrameTest.java
new file mode 100644
index 000000000..7bd4670e1
--- /dev/null
+++ b/thrift/lib/java/src/test/java/com/facebook/thrift/TruncatedFrameTest.java
@@ -0,0 +1,288 @@
+/*
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.facebook.thrift;
+
+import com.facebook.thrift.java.test.MyListStruct;
+import com.facebook.thrift.java.test.MyMapStruct;
+import com.facebook.thrift.java.test.MySetStruct;
+import com.facebook.thrift.protocol.TBinaryProtocol;
+import com.facebook.thrift.protocol.TCompactProtocol;
+import com.facebook.thrift.protocol.TProtocol;
+import com.facebook.thrift.protocol.TProtocolException;
+import com.facebook.thrift.protocol.TType;
+import com.facebook.thrift.transport.TMemoryInputTransport;
+import org.junit.Test;
+
+public class TruncatedFrameTest extends junit.framework.TestCase {
+  private static final byte[] kBinaryListEncoding = {
+    TType.LIST, // Field Type = List
+    (byte) 0x00,
+    (byte) 0x01, // Field id = 1
+    TType.I64, // List type = i64
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0xFF, // List length (255 > 3!)
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x01, // value = 1L
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x01, // value = 2L
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x01, // value = 3L
+    (byte) 0x00, // Stop
+  };
+
+  private static final byte[] kCompactListEncoding = {
+    (byte) 0b00011001, // field id delta (0001) + type (1001) = List
+    (byte) 0b11100110, // list size (0111) and 7>3 + list type (0110) = i64
+    (byte) 0x02, // value = 1 (zigzag encoded)
+    (byte) 0x04, // value = 2 (zigzag encoded)
+    (byte) 0x06, // value = 3 (zigzag encoded)
+    (byte) 0x00, // Stop
+  };
+
+  private static final byte[] kCompactListEncoding2 = {
+    (byte) 0b00011001, // field id delta (0001) + type (1001) = List
+    (byte) 0b11110110, // list size magic marker (1111) + list type (0110) = i64
+    (byte) 0x64, // list actual size (varint of 1 byte here) = 100
+    (byte) 0x02, // value = 1 (zigzag encoded)
+    (byte) 0x04, // value = 2 (zigzag encoded)
+    (byte) 0x06, // value = 3 (zigzag encoded)
+    (byte) 0x00, // Stop
+  };
+
+  public static void testTruncated(TBase struct, TProtocol iprot) throws Exception {
+    try {
+      struct.read(iprot);
+      assertTrue("Not reachable", false);
+    } catch (TProtocolException ex) {
+      assertEquals(
+          "Not enough bytes to read the entire message, the data appears to be truncated",
+          ex.getMessage());
+    }
+  }
+
+  @Test
+  public static void testListBinary() throws Exception {
+    TMemoryInputTransport buf = new TMemoryInputTransport(kBinaryListEncoding);
+    TProtocol iprot = new TBinaryProtocol(buf);
+    testTruncated(new MyListStruct(), iprot);
+  }
+
+  @Test
+  public static void testListCompact() throws Exception {
+    TMemoryInputTransport buf = new TMemoryInputTransport(kCompactListEncoding);
+    TProtocol iprot = new TCompactProtocol(buf);
+    testTruncated(new MyListStruct(), iprot);
+  }
+
+  @Test
+  public static void testLongListCompact() throws Exception {
+    TMemoryInputTransport buf = new TMemoryInputTransport(kCompactListEncoding2);
+    TProtocol iprot = new TCompactProtocol(buf);
+    testTruncated(new MyListStruct(), iprot);
+  }
+
+  private static final byte[] kBinarySetEncoding = {
+    TType.SET, // Field Type = Set
+    (byte) 0x00,
+    (byte) 0x01, // Field id = 1
+    TType.I64, // Set type = i64
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0xFF, // Set length (255 > 3!)
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x01, // value = 1L
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x01, // value = 2L
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x01, // value = 3L
+    (byte) 0x00, // Stop
+  };
+
+  private static final byte[] kCompactSetEncoding = {
+    (byte) 0b00011010, // field id delta (0001) + type (1010) = Set
+    (byte) 0b01110110, // set size (0111) and 7>3 + set type (0110) = i64
+    (byte) 0x02, // value = 1 (zigzag encoded)
+    (byte) 0x04, // value = 2 (zigzag encoded)
+    (byte) 0x06, // value = 3 (zigzag encoded)
+    (byte) 0x00, // Stop
+  };
+
+  private static final byte[] kCompactSetEncoding2 = {
+    (byte) 0b00011010, // field id delta (0001) + type (1010) = Set
+    (byte) 0b11110110, // set size magic marker (1111) + set type (0110) = i64
+    (byte) 0x64, // set actual size (varint of 1 byte here) = 100
+    (byte) 0x02, // value = 1 (zigzag encoded)
+    (byte) 0x04, // value = 2 (zigzag encoded)
+    (byte) 0x06, // value = 3 (zigzag encoded)
+    (byte) 0x00, // Stop
+  };
+
+  @Test
+  public static void testSetBinary() throws Exception {
+    TMemoryInputTransport buf = new TMemoryInputTransport(kBinarySetEncoding);
+    TProtocol iprot = new TBinaryProtocol(buf);
+    testTruncated(new MySetStruct(), iprot);
+  }
+
+  @Test
+  public static void testSetCompact() throws Exception {
+    TMemoryInputTransport buf = new TMemoryInputTransport(kCompactSetEncoding);
+    TProtocol iprot = new TCompactProtocol(buf);
+    testTruncated(new MySetStruct(), iprot);
+  }
+
+  @Test
+  public static void testLongSetCompact() throws Exception {
+    TMemoryInputTransport buf = new TMemoryInputTransport(kCompactSetEncoding2);
+    TProtocol iprot = new TCompactProtocol(buf);
+    testTruncated(new MySetStruct(), iprot);
+  }
+
+  private static final byte[] kBinaryMapEncoding = {
+    TType.MAP, // field type = Map
+    (byte) 0x00,
+    (byte) 0x01, // field id = 1
+    TType.I64, // key type = i64
+    TType.STRING, // value type = string
+    (byte) 0x00,
+    (byte) 0xFF,
+    (byte) 0xFF,
+    (byte) 0xFF, // size = 0x00FFFFFF
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00, // key = 0
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x01, // string size = 1
+    (byte) 0x30, // string value = "0"
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x01, // key = 1
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x01, // string size = 1
+    (byte) 0x31, // string value = "1"
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x02, // key = 2
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x00,
+    (byte) 0x01, // string size = 1
+    (byte) 0x32, // string value = "2"
+    (byte) 0x00, // Stop
+  };
+
+  private static final byte[] kCompactMapEncoding = {
+    (byte) 0b00011011, // field id delta (0001) + type (1011) = Map
+    (byte) 0x64, // map size (varint = 100)
+    (byte) 0b01101000, // key type (0110) i64, value type (1000) string
+    (byte) 0x00, // key value = 0
+    (byte) 0x01, // value: string size = 1
+    (byte) 0x30, // string content = "0"
+    (byte) 0x02, // key value = 1 (zigzag encoded)
+    (byte) 0x01, // value: string size = 1
+    (byte) 0x31, // string content = "1"
+    (byte) 0x04, // key value = 2 (zigzag encoded)
+    (byte) 0x01, // value: string size = 1
+    (byte) 0x32, // string content = "2"
+    (byte) 0x00, // Stop
+  };
+
+  @Test
+  public static void testMapBinary() throws Exception {
+    TMemoryInputTransport buf = new TMemoryInputTransport(kBinaryMapEncoding);
+    TProtocol iprot = new TBinaryProtocol(buf);
+    testTruncated(new MyMapStruct(), iprot);
+  }
+
+  @Test
+  public static void testMapCompact() throws Exception {
+    TMemoryInputTransport buf = new TMemoryInputTransport(kCompactMapEncoding);
+    TProtocol iprot = new TCompactProtocol(buf);
+    testTruncated(new MyMapStruct(), iprot);
+  }
+
+  private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
+
+  private static String bytesToHex(byte[] bytes, int length) {
+    String out = "";
+    for (int j = 0; j < length; j++) {
+      int v = bytes[j] & 0xFF;
+      out += hexArray[v >>> 4];
+      out += hexArray[v & 0x0F];
+      out += " ";
+    }
+    return out;
+  }
+}

Vulnerable code:     return new TMap(readByte(), readByte(), readI32());
    return new TList(readByte(), readI32());
    return new TSet(readByte(), readI32());
    return new TMap(
        getTType((byte) (keyAndValueType >> 4)), getTType((byte) (keyAndValueType & 0xf)), size);
namespace java com.facebook.thrift.test
import com.facebook.thrift.test.BigEnum;
import com.facebook.thrift.test.MySimpleStruct;
import com.facebook.thrift.test.SmallEnum;
Fixed code:     byte keyType = readByte();
    byte valueType = readByte();
    int size = readI32();
    ensureMapHasEnough(size, keyType, valueType);
    return new TMap(keyType, valueType, size);
    byte type = readByte();
    int size = readI32();
    ensureContainerHasEnough(size, type);
    return new TList(type, size);
    byte type = readByte();
    int size = readI32();
    ensureContainerHasEnough(size, type);
    return new TSet(type, size);

  @Override
  protected int typeMinimumSize(byte type) {
    switch (type & 0x0f) {
      case TType.BOOL:
      case TType.BYTE:
        return 1;
      case TType.I16:
        return 2;
      case TType.I32:
      case TType.FLOAT:
        return 4;
      case TType.DOUBLE:
      case TType.I64:
        return 8;
      case TType.STRING:
        return 4;
      case TType.LIST:
      case TType.SET:
        // type (1 byte) + size (4 bytes)
        return 1 + 4;
      case TType.MAP:
        // key type (1 byte) + value type (1 byte) + size (4 bytes)
        return 1 + 1 + 4;
      case TType.STRUCT:
        return 1;
      default:
        throw new TProtocolException(
            TProtocolException.INVALID_DATA, "Unexpected data type " + (byte) (type & 0x0f));
    }
  }
    byte keyType = getTType((byte) (keyAndValueType >> 4));
    byte valueType = getTType((byte) (keyAndValueType & 0xf));
    if (size > 0) {
      ensureMapHasEnough(size, keyType, valueType);
    }
    return new TMap(keyType, valueType, size);
    ensureContainerHasEnough(size, type);

  @Override
  protected int typeMinimumSize(byte type) {
    switch (type & 0x0f) {
      case TType.BOOL:
      case TType.BYTE:
      case TType.I16: // because of variable length encoding
      case TType.I32: // because of variable length encoding
      case TType.I64: // because of variable length encoding
        return 1;
      case TType.FLOAT:
        return 4;
      case TType.DOUBLE:
        return 8;
      case TType.STRING:
      case TType.STRUCT:
      case TType.MAP:
      case TType.SET:
      case TType.LIST:
      case TType.ENUM:
        return 1;
      default:
        throw new TProtocolException(
            TProtocolException.INVALID_DATA, "Unexpected data type " + (byte) (type & 0x0f));
    }
  }

  /** Return the minimum size of a type */
  protected int typeMinimumSize(byte type) {
    return 1;
  }

  protected void ensureContainerHasEnough(int size, byte type) {
    int minimumExpected = size * typeMinimumSize(type);
    ensureHasEnoughBytes(minimumExpected);
  }

  protected void ensureMapHasEnough(int size, byte keyType, byte valueType) {
    int minimumExpected = size * (typeMinimumSize(keyType) + typeMinimumSize(valueType));
    ensureHasEnoughBytes(minimumExpected);
  }

  private void ensureHasEnoughBytes(int minimumExpected) {
    int remaining = trans_.getBytesRemainingInBuffer();
    if (remaining < 0) {
      return; // Some transport are not buffered
    }
    if (remaining < minimumExpected) {
      throw new TProtocolException(
          TProtocolException.INVALID_DATA,
          "Not enough bytes to read the entire message, the data appears to be truncated");
    }
  }

  @Override
  protected int typeMinimumSize(byte type) {
    return concreteProtocol.typeMinimumSize(type);
  }
namespace java com.facebook.thrift.java.test
namespace java.swift com.facebook.thrift.javaswift.test

struct MyListStruct {
  1: list<i64> ids
}

struct MySetStruct {
  1: set<i64> ids
}

struct MyMapStruct {
  1: map<i64, string> mapping
}
import com.facebook.thrift.java.test.BigEnum;
import com.facebook.thrift.java.test.MySimpleStruct;
import com.facebook.thrift.java.test.SmallEnum;
/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.facebook.thrift;

import com.facebook.thrift.java.test.MyListStruct;
import com.facebook.thrift.java.test.MyMapStruct;
import com.facebook.thrift.java.test.MySetStruct;
import com.facebook.thrift.protocol.TBinaryProtocol;
import com.facebook.thrift.protocol.TCompactProtocol;
import com.facebook.thrift.protocol.TProtocol;
import com.facebook.thrift.protocol.TProtocolException;
import com.facebook.thrift.protocol.TType;
import com.facebook.thrift.transport.TMemoryInputTransport;
import org.junit.Test;

public class TruncatedFrameTest extends junit.framework.TestCase {
  private static final byte[] kBinaryListEncoding = {
    TType.LIST, // Field Type = List
    (byte) 0x00,
    (byte) 0x01, // Field id = 1
    TType.I64, // List type = i64
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0xFF, // List length (255 > 3!)
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x01, // value = 1L
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x01, // value = 2L
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x01, // value = 3L
    (byte) 0x00, // Stop
  };

  private static final byte[] kCompactListEncoding = {
    (byte) 0b00011001, // field id delta (0001) + type (1001) = List
    (byte) 0b11100110, // list size (0111) and 7>3 + list type (0110) = i64
    (byte) 0x02, // value = 1 (zigzag encoded)
    (byte) 0x04, // value = 2 (zigzag encoded)
    (byte) 0x06, // value = 3 (zigzag encoded)
    (byte) 0x00, // Stop
  };

  private static final byte[] kCompactListEncoding2 = {
    (byte) 0b00011001, // field id delta (0001) + type (1001) = List
    (byte) 0b11110110, // list size magic marker (1111) + list type (0110) = i64
    (byte) 0x64, // list actual size (varint of 1 byte here) = 100
    (byte) 0x02, // value = 1 (zigzag encoded)
    (byte) 0x04, // value = 2 (zigzag encoded)
    (byte) 0x06, // value = 3 (zigzag encoded)
    (byte) 0x00, // Stop
  };

  public static void testTruncated(TBase struct, TProtocol iprot) throws Exception {
    try {
      struct.read(iprot);
      assertTrue("Not reachable", false);
    } catch (TProtocolException ex) {
      assertEquals(
          "Not enough bytes to read the entire message, the data appears to be truncated",
          ex.getMessage());
    }
  }

  @Test
  public static void testListBinary() throws Exception {
    TMemoryInputTransport buf = new TMemoryInputTransport(kBinaryListEncoding);
    TProtocol iprot = new TBinaryProtocol(buf);
    testTruncated(new MyListStruct(), iprot);
  }

  @Test
  public static void testListCompact() throws Exception {
    TMemoryInputTransport buf = new TMemoryInputTransport(kCompactListEncoding);
    TProtocol iprot = new TCompactProtocol(buf);
    testTruncated(new MyListStruct(), iprot);
  }

  @Test
  public static void testLongListCompact() throws Exception {
    TMemoryInputTransport buf = new TMemoryInputTransport(kCompactListEncoding2);
    TProtocol iprot = new TCompactProtocol(buf);
    testTruncated(new MyListStruct(), iprot);
  }

  private static final byte[] kBinarySetEncoding = {
    TType.SET, // Field Type = Set
    (byte) 0x00,
    (byte) 0x01, // Field id = 1
    TType.I64, // Set type = i64
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0xFF, // Set length (255 > 3!)
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x01, // value = 1L
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x01, // value = 2L
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x01, // value = 3L
    (byte) 0x00, // Stop
  };

  private static final byte[] kCompactSetEncoding = {
    (byte) 0b00011010, // field id delta (0001) + type (1010) = Set
    (byte) 0b01110110, // set size (0111) and 7>3 + set type (0110) = i64
    (byte) 0x02, // value = 1 (zigzag encoded)
    (byte) 0x04, // value = 2 (zigzag encoded)
    (byte) 0x06, // value = 3 (zigzag encoded)
    (byte) 0x00, // Stop
  };

  private static final byte[] kCompactSetEncoding2 = {
    (byte) 0b00011010, // field id delta (0001) + type (1010) = Set
    (byte) 0b11110110, // set size magic marker (1111) + set type (0110) = i64
    (byte) 0x64, // set actual size (varint of 1 byte here) = 100
    (byte) 0x02, // value = 1 (zigzag encoded)
    (byte) 0x04, // value = 2 (zigzag encoded)
    (byte) 0x06, // value = 3 (zigzag encoded)
    (byte) 0x00, // Stop
  };

  @Test
  public static void testSetBinary() throws Exception {
    TMemoryInputTransport buf = new TMemoryInputTransport(kBinarySetEncoding);
    TProtocol iprot = new TBinaryProtocol(buf);
    testTruncated(new MySetStruct(), iprot);
  }

  @Test
  public static void testSetCompact() throws Exception {
    TMemoryInputTransport buf = new TMemoryInputTransport(kCompactSetEncoding);
    TProtocol iprot = new TCompactProtocol(buf);
    testTruncated(new MySetStruct(), iprot);
  }

  @Test
  public static void testLongSetCompact() throws Exception {
    TMemoryInputTransport buf = new TMemoryInputTransport(kCompactSetEncoding2);
    TProtocol iprot = new TCompactProtocol(buf);
    testTruncated(new MySetStruct(), iprot);
  }

  private static final byte[] kBinaryMapEncoding = {
    TType.MAP, // field type = Map
    (byte) 0x00,
    (byte) 0x01, // field id = 1
    TType.I64, // key type = i64
    TType.STRING, // value type = string
    (byte) 0x00,
    (byte) 0xFF,
    (byte) 0xFF,
    (byte) 0xFF, // size = 0x00FFFFFF
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00, // key = 0
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x01, // string size = 1
    (byte) 0x30, // string value = "0"
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x01, // key = 1
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x01, // string size = 1
    (byte) 0x31, // string value = "1"
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x02, // key = 2
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x00,
    (byte) 0x01, // string size = 1
    (byte) 0x32, // string value = "2"
    (byte) 0x00, // Stop
  };

  private static final byte[] kCompactMapEncoding = {
    (byte) 0b00011011, // field id delta (0001) + type (1011) = Map
    (byte) 0x64, // map size (varint = 100)
    (byte) 0b01101000, // key type (0110) i64, value type (1000) string
    (byte) 0x00, // key value = 0
    (byte) 0x01, // value: string size = 1
    (byte) 0x30, // string content = "0"
    (byte) 0x02, // key value = 1 (zigzag encoded)
    (byte) 0x01, // value: string size = 1
    (byte) 0x31, // string content = "1"
    (byte) 0x04, // key value = 2 (zigzag encoded)
    (byte) 0x01, // value: string size = 1
    (byte) 0x32, // string content = "2"
    (byte) 0x00, // Stop
  };

  @Test
  public static void testMapBinary() throws Exception {
    TMemoryInputTransport buf = new TMemoryInputTransport(kBinaryMapEncoding);
    TProtocol iprot = new TBinaryProtocol(buf);
    testTruncated(new MyMapStruct(), iprot);
  }

  @Test
  public static void testMapCompact() throws Exception {
    TMemoryInputTransport buf = new TMemoryInputTransport(kCompactMapEncoding);
    TProtocol iprot = new TCompactProtocol(buf);
    testTruncated(new MyMapStruct(), iprot);
  }

  private static final char[] hexArray = "0123456789ABCDEF".toCharArray();

  private static String bytesToHex(byte[] bytes, int length) {
    String out = "";
    for (int j = 0; j < length; j++) {
      int v = bytes[j] & 0xFF;
      out += hexArray[v >>> 4];
      out += hexArray[v & 0x0F];
      out += " ";
    }
    return out;
  }
}