Skip to content

Commit

Permalink
Check UTF16 string size before converting to string to avoid OOME
Browse files Browse the repository at this point in the history
Signed-off-by: Rishab Nahata <[email protected]>
  • Loading branch information
imRishN committed Jun 8, 2023
1 parent c58dc1a commit d27cd97
Showing 1 changed file with 9 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@

import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefIterator;
import org.apache.lucene.util.UnicodeUtil;
import org.opensearch.common.io.stream.StreamInput;
import org.opensearch.core.xcontent.XContentBuilder;

Expand All @@ -49,6 +50,7 @@
public abstract class AbstractBytesReference implements BytesReference {

private Integer hash = null; // we cache the hash of this reference since it can be quite costly to re-calculated it
static final int MAX_LENGTH = Integer.MAX_VALUE >> 1;

@Override
public int getInt(int index) {
Expand Down Expand Up @@ -82,6 +84,13 @@ public void writeTo(OutputStream os) throws IOException {

@Override
public String utf8ToString() {
BytesRef bytesRef = toBytesRef();
char[] ref = new char[bytesRef.length];
int len = UnicodeUtil.UTF8toUTF16(bytesRef.bytes, bytesRef.offset, bytesRef.length, ref);
if (len > MAX_LENGTH) {
throw new IllegalStateException("UTF16 String size is " + len +
", should be less than " + MAX_LENGTH);
}
return toBytesRef().utf8ToString();
}

Expand Down

0 comments on commit d27cd97

Please sign in to comment.