No public description

PiperOrigin-RevId: 647161068
Change-Id: Icd47a98516d9adb200751938c643e7c7217700f1
diff --git a/current/src/main/java/com/sun/mail/iap/ResponseInputStream.java b/current/src/main/java/com/sun/mail/iap/ResponseInputStream.java
index 7bbba00..9e0ecde 100644
--- a/current/src/main/java/com/sun/mail/iap/ResponseInputStream.java
+++ b/current/src/main/java/com/sun/mail/iap/ResponseInputStream.java
@@ -58,6 +58,9 @@
     private static final int maxIncrement = 256 * 1024;
     private static final int incrementSlop = 16;
 
+		private final int inputStreamBufferMaxSize =
+				Integer.getInteger("com.sun.mail.iap.inputStreamBufferMaxSize", 0);
+
     // where we read from
     private BufferedInputStream bin;
 
@@ -109,7 +112,7 @@
 		    int incr = buffer.length;
 		    if (incr > maxIncrement)
 			incr = maxIncrement;
-		    ba.grow(incr);
+		    checkBeforeGrow(ba, incr);
 		    buffer = ba.getBytes();
 		}
 		buffer[idx++] = (byte)b;
@@ -145,7 +148,7 @@
 		int avail = buffer.length - idx; // available space in buffer
 		if (count + incrementSlop > avail) {
 		    // need count-avail more bytes
-		    ba.grow(minIncrement > count + incrementSlop - avail ? 
+		    checkBeforeGrow(ba, minIncrement > count + incrementSlop - avail ? 
 			    minIncrement : count + incrementSlop - avail);
 		    buffer = ba.getBytes();
 		}
@@ -179,4 +182,15 @@
     public int available() throws IOException {
 	return bin.available();
     }
+
+		// TODO: b/349666261 - Push for a fix upstream, or deprecate sun_mail.
+		private void checkBeforeGrow(ByteArray ba, int incr) throws IOException {
+			if (inputStreamBufferMaxSize > 0 && ba.getBytes().length + incr > inputStreamBufferMaxSize) {
+				throw new IOException(
+						String.format(
+								"Buffer in ResponseInputStream grows too large. Limit: %d, actual: %d",
+								inputStreamBufferMaxSize, ba.getBytes().length + incr));
+			}
+			ba.grow(incr);
+		}
 }