[Git][java-team/jackson-dataformats-text][master] 4 commits: New upstream version 2.23.0
Emmanuel Bourg (@ebourg)
gitlab at salsa.debian.org
Mon Nov 9 17:04:20 GMT 2026
Emmanuel Bourg pushed to branch master at Debian Java Maintainers / jackson-dataformats-text
Commits:
a22d292c by Emmanuel Bourg at 2026-11-09T17:07:32+01:00
New upstream version 2.23.0
- - - - -
d95dad65 by Emmanuel Bourg at 2026-11-09T17:07:38+01:00
Update upstream source from tag 'upstream/2.23.0'
Update to upstream version '2.23.0'
with Debian dir eb6ae4c30afcadcf188634802c03d26f2416b673
- - - - -
2bd987df by Emmanuel Bourg at 2026-11-09T17:09:09+01:00
Tightened the dependencies on the other jackson packages
- - - - -
3ae8e131 by Emmanuel Bourg at 2026-11-09T17:27:27+01:00
Upload to unstable
- - - - -
27 changed files:
- .github/workflows/main.yml
- csv/pom.xml
- csv/src/main/java/com/fasterxml/jackson/dataformat/csv/CsvSchema.java
- csv/src/main/java/com/fasterxml/jackson/dataformat/csv/impl/CsvParserBootstrapper.java
- csv/src/main/java/com/fasterxml/jackson/dataformat/csv/impl/UTF8Reader.java
- + csv/src/test/java/com/fasterxml/jackson/dataformat/csv/deser/InvalidUTF8Encoding763Test.java
- + csv/src/test/java/com/fasterxml/jackson/dataformat/csv/deser/UTF8ReaderTest.java
- csv/src/test/java/com/fasterxml/jackson/dataformat/csv/fuzz/FuzzCSVReadTest.java
- csv/src/test/java/com/fasterxml/jackson/dataformat/csv/schema/CsvSchemaTest.java
- debian/changelog
- debian/control
- pom.xml
- properties/pom.xml
- release-notes/CREDITS-2.x
- release-notes/VERSION-2.x
- toml/pom.xml
- toml/src/main/java/com/fasterxml/jackson/dataformat/toml/Parser.java
- toml/src/main/java/com/fasterxml/jackson/dataformat/toml/TomlGenerator.java
- toml/src/test/java/com/fasterxml/jackson/dataformat/toml/ComplianceValidTest.java
- toml/src/test/java/com/fasterxml/jackson/dataformat/toml/TomlGeneratorTest.java
- toml/src/test/java/com/fasterxml/jackson/dataformat/toml/TomlParserTest.java
- yaml/pom.xml
- yaml/src/main/java/com/fasterxml/jackson/dataformat/yaml/UTF8Reader.java
- yaml/src/test/java/com/fasterxml/jackson/dataformat/yaml/FormatDetectionTest.java
- + yaml/src/test/java/com/fasterxml/jackson/dataformat/yaml/deser/InvalidUTF8Encoding764Test.java
- yaml/src/test/java/com/fasterxml/jackson/dataformat/yaml/fuzz/FuzzYAMLReadTest.java
- yaml/src/test/java/com/fasterxml/jackson/dataformat/yaml/misc/PolymorphicDeductionTest.java
Changes:
=====================================
.github/workflows/main.yml
=====================================
@@ -56,7 +56,7 @@ jobs:
run: ./mvnw -B -q -ff -ntp test
- name: Publish code coverage
if: ${{ matrix.release_build && github.event_name != 'pull_request' }}
- uses: codecov/codecov-action at 5a1091511ad55cbe89839c7260b706298ca349f7 # v5.5.1
+ uses: codecov/codecov-action at 303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: ./target/site/jacoco/jacoco.xml
=====================================
csv/pom.xml
=====================================
@@ -9,7 +9,7 @@
<parent>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformats-text</artifactId>
- <version>2.22.4</version>
+ <version>2.23.0</version>
</parent>
<artifactId>jackson-dataformat-csv</artifactId>
<name>Jackson-dataformat-CSV</name>
=====================================
csv/src/main/java/com/fasterxml/jackson/dataformat/csv/CsvSchema.java
=====================================
@@ -629,6 +629,55 @@ public class CsvSchema
return this;
}
+ /**
+ * Method for renaming an existing column, located by its current name
+ * instead of by index.
+ *
+ * @param oldName Current name of the column to rename
+ * @param newName New name to assign to the column
+ *
+ * @throws IllegalArgumentException if no column with given {@code oldName} exists
+ *
+ * @since 2.23
+ */
+ public Builder renameColumn(String oldName, String newName) {
+ return renameColumn(_columnIndex(oldName), newName);
+ }
+
+ /**
+ * Method for replacing an existing column, located by its current name
+ * instead of by index.
+ *<p>
+ * NOTE: index of the replacement column {@code c} is ignored (as with
+ * {@link #replaceColumn(int, Column)}): columns are renumbered to match
+ * their actual position when {@link #build()} is called. Caller hence does
+ * not need to know index of the column being replaced.
+ *
+ * @param name Name of the column to replace
+ * @param c Column definition to use as replacement
+ *
+ * @throws IllegalArgumentException if no column with given {@code name} exists
+ *
+ * @since 2.23
+ */
+ public Builder replaceColumn(String name, Column c) {
+ return replaceColumn(_columnIndex(name), c);
+ }
+
+ /**
+ * Method for removing an existing column, located by its name instead
+ * of by index.
+ *
+ * @param name Name of the column to remove
+ *
+ * @throws IllegalArgumentException if no column with given {@code name} exists
+ *
+ * @since 2.23
+ */
+ public Builder removeColumn(String name) {
+ return removeColumn(_columnIndex(name));
+ }
+
/**
* Helper method called to drop the last collected column name if
* it is empty: called if {link CsvParser.Feature#ALLOW_TRAILING_COMMA}
@@ -651,12 +700,41 @@ public class CsvSchema
return this;
}
+ /**
+ * Method for changing type of an existing column, located by its name
+ * instead of by index.
+ *
+ * @param name Name of the column to change type of
+ * @param type Type to assign to the column
+ *
+ * @throws IllegalArgumentException if no column with given {@code name} exists
+ *
+ * @since 2.23
+ */
+ public Builder setColumnType(String name, ColumnType type) {
+ return setColumnType(_columnIndex(name), type);
+ }
+
public Builder removeArrayElementSeparator(int index) {
_checkIndex(index);
_columns.set(index, _columns.get(index).withArrayElementSeparator(""));
return this;
}
+ /**
+ * Method for removing array element separator of an existing column,
+ * located by its name instead of by index.
+ *
+ * @param name Name of the column to remove array element separator of
+ *
+ * @throws IllegalArgumentException if no column with given {@code name} exists
+ *
+ * @since 2.23
+ */
+ public Builder removeArrayElementSeparator(String name) {
+ return removeArrayElementSeparator(_columnIndex(name));
+ }
+
/**
* @since 2.7
*/
@@ -666,6 +744,25 @@ public class CsvSchema
return this;
}
+ /**
+ * Method for setting array element separator of an existing column,
+ * located by its name instead of by index.
+ *<p>
+ * NOTE: not to be confused with single-argument
+ * {@link #setArrayElementSeparator(String)}, which sets the schema-wide
+ * default separator instead of that of a single column.
+ *
+ * @param name Name of the column to set array element separator of
+ * @param sep Array element separator to assign to the column
+ *
+ * @throws IllegalArgumentException if no column with given {@code name} exists
+ *
+ * @since 2.23
+ */
+ public Builder setArrayElementSeparator(String name, String sep) {
+ return setArrayElementSeparator(_columnIndex(name), sep);
+ }
+
public Builder setAnyPropertyName(String name) {
_anyPropertyName = name;
return this;
@@ -694,12 +791,31 @@ public class CsvSchema
* @since 2.9
*/
public boolean hasColumn(String name) {
+ return columnIndex(name) >= 0;
+ }
+
+ /**
+ * Method for finding index of the column with given name, if any.
+ *<p>
+ * NOTE: this method requires linear scan over existing columns
+ * so it may be more efficient to use other types of lookups if
+ * available (for example, {@link CsvSchema#columnIndex(String)} has a
+ * hash lookup to use).
+ *
+ * @param name Name of column to find
+ *
+ * @return Index of the first column with given name, if one exists;
+ * {@code -1} if not
+ *
+ * @since 2.23
+ */
+ public int columnIndex(String name) {
for (int i = 0, end = _columns.size(); i < end; ++i) {
if (_columns.get(i).getName().equals(name)) {
- return true;
+ return i;
}
}
- return false;
+ return -1;
}
/**
@@ -869,6 +985,42 @@ public class CsvSchema
throw new IllegalArgumentException("Illegal index "+index+"; only got "+_columns.size()+" columns");
}
}
+
+ /**
+ * Helper method for finding index of the column with given name, for
+ * use by name-based mutators; same as {@link #columnIndex(String)} except
+ * that a missing column is reported as an exception instead of {@code -1}.
+ *
+ * @param name Name of the column to find
+ *
+ * @return Index of the first column with given name
+ *
+ * @throws IllegalArgumentException if no column with given {@code name} exists
+ *
+ * @since 2.23
+ */
+ protected int _columnIndex(String name) {
+ int ix = columnIndex(name);
+ if (ix < 0) {
+ throw new IllegalArgumentException("No column '"+name+"' in CsvSchema.Builder (known columns: "
+ +_columnNames()+")");
+ }
+ return ix;
+ }
+
+ /**
+ * Helper method for constructing List of names of currently included
+ * columns, for use in exception messages.
+ *
+ * @since 2.23
+ */
+ private List<String> _columnNames() {
+ List<String> names = new ArrayList<>(_columns.size());
+ for (int i = 0, end = _columns.size(); i < end; ++i) {
+ names.add(_columns.get(i).getName());
+ }
+ return names;
+ }
}
/*
=====================================
csv/src/main/java/com/fasterxml/jackson/dataformat/csv/impl/CsvParserBootstrapper.java
=====================================
@@ -190,8 +190,9 @@ public final class CsvParserBootstrapper
}
case UTF8:
// Important: do not pass context, if we got byte[], nothing to release
+ // `_inputProcessed` so that byte positions include BOM, if any
return new UTF8Reader((_in == null) ? null : _context, _in, autoClose,
- _inputBuffer, _inputPtr, _inputEnd - _inputPtr);
+ _inputBuffer, _inputPtr, _inputEnd - _inputPtr, _inputProcessed);
default:
throw new RuntimeException();
}
=====================================
csv/src/main/java/com/fasterxml/jackson/dataformat/csv/impl/UTF8Reader.java
=====================================
@@ -55,18 +55,13 @@ public final class UTF8Reader
/**
* Total read character count; used for error reporting purposes
*/
- private int _charCount = 0;
+ private long _charCount = 0;
/**
- * Total read byte count; used for error reporting purposes
+ * Number of input bytes that precede {@code _inputBuffer[0]};
+ * used for error reporting purposes
*/
- private int _byteCount = 0;
-
- /**
- * Flag that is set when a pending decode error has been detected; needed
- * to properly handle deferred reporting.
- */
- private int _decodeErrorOffset;
+ private long _byteCount;
/*
/**********************************************************************
@@ -76,6 +71,21 @@ public final class UTF8Reader
public UTF8Reader(IOContext ctxt, InputStream in, boolean autoClose,
byte[] buf, int ptr, int len)
+ {
+ // byte positions relative to start of content, not of buffer
+ this(ctxt, in, autoClose, buf, ptr, len, -ptr);
+ }
+
+ /**
+ * @param bytesBefore Number of input bytes that precede {@code buf[0]}, used
+ * for byte positions in error messages: for example, if {@code buf} starts
+ * with a BOM that has already been skipped (and {@code ptr} points past it),
+ * {@code 0} so that BOM is included in byte positions
+ *
+ * @since 2.23
+ */
+ public UTF8Reader(IOContext ctxt, InputStream in, boolean autoClose,
+ byte[] buf, int ptr, int len, long bytesBefore)
{
super((in == null) ? buf : in);
_ioContext = ctxt;
@@ -87,6 +97,7 @@ public final class UTF8Reader
// Unmodifiable if there is no stream to actually read from
// (ideally caller should pass explicitly)
_inputBufferReadOnly = (in == null);
+ _byteCount = bytesBefore;
}
public UTF8Reader(IOContext ctxt, byte[] buf, int ptr, int len)
@@ -100,6 +111,7 @@ public final class UTF8Reader
_autoClose = true;
// This is the case when we have a buffer of contents already read
_inputBufferReadOnly = true;
+ _byteCount = -ptr;
}
public UTF8Reader(IOContext ctxt, InputStream in, boolean autoClose)
@@ -162,6 +174,13 @@ public final class UTF8Reader
@Override
public int read(final char[] cbuf, final int start, int len) throws IOException
{
+ if (start < 0 || len <= 0 || len > cbuf.length - start) {
+ // Nothing to read? (must not write buffered surrogate, if any)
+ if (len == 0 && start >= 0 && start <= cbuf.length) {
+ return 0;
+ }
+ reportBounds(cbuf, start, len);
+ }
// Already EOF?
if (_inputBuffer == null) {
return -1;
@@ -181,10 +200,6 @@ public final class UTF8Reader
}
// otherwise let things work the way they should
} else {
- if (_decodeErrorOffset != 0) {
- reportDeferredInvalid();
- }
-
// To prevent unnecessary blocking (esp. with network streams),
// we'll only require decoding of a single char
int left = (_inputEnd - _inputPtr);
@@ -207,6 +222,10 @@ public final class UTF8Reader
final byte[] buf = _inputBuffer;
int inPtr = _inputPtr;
final int inBufLen = _inputEnd;
+ // start of current multi-byte sequence, and whether it is invalid: details are
+ // only figured out if (and when) error is reported
+ int seqStart = 0;
+ boolean invalid = false;
main_loop:
while (outPtr < len) {
@@ -237,6 +256,7 @@ public final class UTF8Reader
}
int needed;
+ seqStart = inPtr - 1;
// Ok; if we end here, we got multi-byte combination
if ((c & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF), from 110xxxxx
@@ -246,13 +266,10 @@ public final class UTF8Reader
c = (c & 0x0F);
needed = 2;
} else if ((c & 0xF8) == 0xF0) { // 4 bytes from 11110xxx (double-char w/ surrogates and all)
- c = (c & 0x0F);
+ c = (c & 0x07);
needed = 3;
} else {
- reportInvalidInitial(c & 0xFF, outPtr-start);
- // 25-Aug-2016, tatu: As per [dataformat-csv#132], only returns
- // if we are ok to return already decoded content and defer error reporting
- --inPtr;
+ invalid = true;
break main_loop;
}
/* Do we have enough bytes? If not, let's just push back the
@@ -261,41 +278,47 @@ public final class UTF8Reader
* input stream) when absolutely necessary.
*/
if ((inBufLen - inPtr) < needed) {
+ // ... unless bytes we do have already make the sequence invalid
+ if (hasInvalidMiddleByte(buf, inPtr, inBufLen)) {
+ invalid = true;
+ break main_loop;
+ }
--inPtr;
break main_loop;
}
- int d = buf[inPtr];
+ int d = buf[inPtr++];
if ((d & 0xC0) != 0x080) {
- reportInvalidOther(d & 0xFF, outPtr-start, 2);
+ invalid = true;
break main_loop;
}
- ++inPtr;
c = (c << 6) | (d & 0x3F);
if (needed > 1) { // needed == 1 means 2 bytes total
- d = buf[inPtr]; // 3rd byte
+ d = buf[inPtr++]; // 3rd byte
if ((d & 0xC0) != 0x080) {
- reportInvalidOther(d & 0xFF, outPtr-start, 3);
+ invalid = true;
break main_loop;
}
- ++inPtr;
c = (c << 6) | (d & 0x3F);
if (needed > 2) { // 4 bytes? (need surrogates)
- d = buf[inPtr];
+ d = buf[inPtr++];
if ((d & 0xC0) != 0x080) {
- reportInvalidOther(d & 0xFF, outPtr-start, 4);
+ invalid = true;
break main_loop;
}
- ++inPtr;
c = (c << 6) | (d & 0x3F);
+ // overlong, or beyond U+10FFFF?
+ if (c < 0x10000 || c > Character.MAX_CODE_POINT) {
+ invalid = true;
+ break main_loop;
+ }
/* Ugh. Need to mess with surrogates. Ok; let's inline them
* there, then, if there's room: if only room for one,
* need to save the surrogate for the rainy day...
*/
c -= 0x10000; // to normalize it starting with 0x0
cbuf[outPtr++] = (char) (0xD800 + (c >> 10));
- // hmmh. can this ever be 0? (not legal, at least?)
c = (0xDC00 | (c & 0x03FF));
// Room for second part?
@@ -304,17 +327,14 @@ public final class UTF8Reader
break main_loop;
}
// sure, let's fall back to normal processing:
+ } else if (c < 0x800 || (c >= 0xD800 && c <= 0xDFFF)) {
+ // overlong, or surrogate (illegal in UTF-8 as per [jackson-core#363])
+ invalid = true;
+ break main_loop;
}
- // Otherwise, should we check that 3-byte chars are
- // legal ones (should not expand to surrogates?
- // For now, let's not...
- /*
- else {
- if (c >= 0xD800 && c < 0xE000) {
- reportInvalid(c, outPtr-start, "(a surrogate character) ");
- }
- }
- */
+ } else if (c < 0x80) { // overlong
+ invalid = true;
+ break main_loop;
}
cbuf[outPtr++] = (char) c;
if (inPtr >= inBufLen) {
@@ -322,6 +342,17 @@ public final class UTF8Reader
}
}
+ if (invalid) {
+ // 25-Aug-2016, tatu: As per [dataformat-csv#132] defer error reporting if
+ // (but only if) some content has been decoded successfully: we then
+ // return that content, and next call starts from the invalid sequence
+ // and reports it.
+ if (outPtr == start) {
+ reportInvalidSequence(seqStart, inBufLen);
+ }
+ inPtr = seqStart;
+ }
+
_inputPtr = inPtr;
final int actualLen = outPtr - start;
_charCount += actualLen;
@@ -402,17 +433,17 @@ public final class UTF8Reader
* @param available Number of "unused" bytes in the input buffer
*
* @return True, if enough bytes were read to allow decoding of at least
- * one full character; false if EOF was encountered instead.
+ * one full character (or to report it invalid); false if EOF was
+ * encountered instead.
*/
private boolean loadMore(int available) throws IOException
{
- _byteCount += (_inputEnd - available);
-
if (available > 0) {
// Should we move bytes to the beginning of buffer?
if (_inputPtr > 0) {
// Can only do so if buffer mutable
if (!_inputBufferReadOnly) {
+ _byteCount += _inputPtr;
for (int i = 0; i < available; ++i) {
_inputBuffer[i] = _inputBuffer[_inputPtr+i];
}
@@ -421,6 +452,7 @@ public final class UTF8Reader
}
}
} else {
+ _byteCount += _inputEnd;
// Ok; here we can actually reasonably expect an EOF, so let's do a separate read right away:
int count = readBytes();
if (count < 1) {
@@ -460,19 +492,37 @@ public final class UTF8Reader
// if an EOF is hit, that'll be an error. But we need not do
// actual decoding here, just load enough bytes.
while ((_inputPtr + needed) > _inputEnd) {
+ // No point in waiting for (or failing on lack of) more bytes if the ones
+ // we have make sequence invalid: let caller report the actual problem
+ if (hasInvalidMiddleByte(_inputBuffer, _inputPtr+1, _inputEnd)) {
+ return true;
+ }
int count = readBytesAt(_inputEnd);
if (count < 1) {
if (count < 0) { // -1, EOF... no good!
- freeBuffers();
- reportUnexpectedEOF(_inputEnd - _inputPtr, needed);
+ // but report sequence as invalid if possible, not as truncated.
+ // Buffers are not freed (left to close()): so that following
+ // reads fail the same way, instead of returning EOF
+ reportInvalidSequence(_inputPtr, _inputEnd);
+ } else {
+ // 0 count is no good; let's err out
+ reportStrangeStream();
}
- // 0 count is no good; let's err out
- reportStrangeStream();
}
}
return true;
}
+ // Whether any byte in buf[start, end) is not a valid continuation byte (10xxxxxx)
+ private static boolean hasInvalidMiddleByte(byte[] buf, int start, int end) {
+ for (int i = start; i < end; ++i) {
+ if ((buf[i] & 0xC0) != 0x080) {
+ return true;
+ }
+ }
+ return false;
+ }
+
protected void reportBounds(char[] cbuf, int start, int len) throws IOException {
throw new ArrayIndexOutOfBoundsException("read(buf,"+start+","+len+"), cbuf["+cbuf.length+"]");
}
@@ -481,62 +531,105 @@ public final class UTF8Reader
throw new IOException("Strange I/O stream, returned 0 bytes on read");
}
- protected void reportInvalidInitial(int mask, int outputDecoded) throws IOException
- {
- // 25-Aug-2016, tatu: As per [dataformat-csv#132] defer error reporting if
- // (but only if) some content has been decoded successfully
- if (_decodeErrorOffset == 0) {
- if (outputDecoded > 0) {
- _decodeErrorOffset = 1;
- return;
- }
- }
-
- // input (byte) ptr has been advanced by one, by now:
- int bytePos = _byteCount + _inputPtr - 1;
- int charPos = _charCount + outputDecoded + 1;
+ private final static String NOT_UTF8 = ": check content encoding, does not look like UTF-8";
- throw new CharConversionException(String.format(
- "Invalid UTF-8 start byte 0x%s (at char #%d, byte #%d): check content encoding, does not look like UTF-8",
- Integer.toHexString(mask), charPos, bytePos));
+ private static String invalidMiddleByte(int b) {
+ return "Invalid UTF-8 middle byte 0x"+Integer.toHexString(b & 0xFF);
}
- protected void reportInvalidOther(int mask, int outputDecoded, int errorPosition) throws IOException
+ // Smallest code point that needs given number of continuation bytes
+ private final static int[] MIN_CODE_POINTS = { 0, 0x80, 0x800, 0x10000 };
+
+ /**
+ * Method called to report invalid (or, at end of input, truncated) multi-byte
+ * sequence that starts at {@code _inputBuffer[seqStart]}, with bytes available up to
+ * (but not including) {@code end}. Kept separate from the decode loop which only
+ * notes that the sequence is invalid: as errors are rare, the specific problem is
+ * only figured out here.
+ *<p>
+ * For truncated sequences, the bytes available may already prove sequence
+ * invalid (start byte like {@code 0xC0} that can only be used for overlong
+ * encodings, for example); if not, sequence is reported as truncated.
+ */
+ private void reportInvalidSequence(int seqStart, int end) throws IOException
{
- // 25-Aug-2016, tatu: As per [dataformat-csv#132] defer error reporting if
- // (but only if) some content has been decoded successfully
- if (_decodeErrorOffset == 0) {
- if (outputDecoded > 0) {
- _decodeErrorOffset = errorPosition;
- return;
+ final byte[] buf = _inputBuffer;
+ int c = buf[seqStart] & 0xFF;
+ int needed;
+ if ((c & 0xE0) == 0xC0) {
+ c &= 0x1F;
+ needed = 1;
+ } else if ((c & 0xF0) == 0xE0) {
+ c &= 0x0F;
+ needed = 2;
+ } else if ((c & 0xF8) == 0xF0) {
+ c &= 0x07;
+ needed = 3;
+ } else {
+ reportInvalid("Invalid UTF-8 start byte 0x"+Integer.toHexString(c), seqStart, true);
+ return;
+ }
+ final int avail = Math.min(needed, end - seqStart - 1);
+ for (int i = seqStart + 1, last = seqStart + avail; i <= last; ++i) {
+ int d = buf[i];
+ if ((d & 0xC0) != 0x080) {
+ reportInvalid(invalidMiddleByte(d), i, true);
}
+ c = (c << 6) | (d & 0x3F);
}
-
- int bytePos = _byteCount + _inputPtr - 1;
- int charPos = _charCount + outputDecoded + 1;
-
- throw new CharConversionException(String.format(
- "Invalid UTF-8 middle byte 0x%s (at char #%d, byte #%d): check content encoding, does not look like UTF-8",
- Integer.toHexString(mask), charPos, bytePos));
+ // Range of values sequence may decode to (single value if complete)
+ final int shift = 6 * (needed - avail);
+ final int min = c << shift;
+ final int max = min | ((1 << shift) - 1);
+ String reason = null;
+ if (max < MIN_CODE_POINTS[needed]) {
+ reason = "overlong encoding";
+ } else if (min > Character.MAX_CODE_POINT || (min >= 0xD800 && max <= 0xDFFF)) {
+ // as per [jackson-core#363], surrogates are illegal in UTF-8
+ reason = "not a valid Unicode scalar value";
+ }
+ if (reason != null) {
+ StringBuilder sb = new StringBuilder("Invalid UTF-8 ");
+ if (avail == needed) {
+ sb.append("character 0x").append(Integer.toHexString(c));
+ } else {
+ sb.append("sequence");
+ for (int i = seqStart, last = seqStart + avail; i <= last; ++i) {
+ sb.append(" 0x").append(Integer.toHexString(buf[i] & 0xFF));
+ }
+ }
+ sb.append(" (").append(reason).append(')');
+ reportInvalid(sb.toString(), seqStart, false);
+ }
+ if (avail < needed) { // only called for truncated sequences at end of input
+ reportUnexpectedEOF(avail + 1, needed + 1, seqStart);
+ }
+ // should never get here; but if we do, fail same way as for invalid content
+ throw new CharConversionException("Internal error: valid UTF-8 sequence reported as invalid"
+ +_position(seqStart));
}
- protected void reportDeferredInvalid() throws IOException
+ // Errors are only reported before anything is decoded by the current read() call
+ // (see [dataformat-csv#132] above), so the offending char is the one after
+ // `_charCount`. `byteIndex` is the index in `_inputBuffer` of the offending byte:
+ // `_inputPtr` is not updated until read() returns, so callers pass it in.
+ private void reportInvalid(String msg, int byteIndex, boolean notUtf8)
+ throws IOException
{
- int ch = _inputBuffer[_inputPtr] & 0xFF;
- if (_decodeErrorOffset == 1) {
- reportInvalidInitial(ch, 0);
- } else {
- reportInvalidOther(ch, 0, _decodeErrorOffset);
- }
+ throw new CharConversionException(msg+_position(byteIndex)
+ +(notUtf8 ? NOT_UTF8 : ""));
}
- protected void reportUnexpectedEOF(int gotBytes, int needed) throws IOException
+ private void reportUnexpectedEOF(int gotBytes, int needed, int byteIndex) throws IOException
{
- int bytePos = _byteCount + gotBytes;
- int charPos = _charCount;
-
throw new CharConversionException(String.format(
- "Unexpected EOF in the middle of a multi-byte UTF-8 character: got %d, needed %d, at char #%d, byte #%d)",
- gotBytes, needed, charPos, bytePos));
+ "Unexpected EOF in the middle of a multi-byte UTF-8 character: got %d, needed %d%s",
+ gotBytes, needed, _position(byteIndex)));
+ }
+
+ // 1-based positions: chars relative to start of content (after BOM, if any),
+ // bytes relative to start of input (including BOM)
+ private String _position(int byteIndex) {
+ return " (at char #"+(_charCount + 1)+", byte #"+(_byteCount + byteIndex + 1)+")";
}
}
=====================================
csv/src/test/java/com/fasterxml/jackson/dataformat/csv/deser/InvalidUTF8Encoding763Test.java
=====================================
@@ -0,0 +1,335 @@
+package com.fasterxml.jackson.dataformat.csv.deser;
+
+import java.io.*;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+import org.junit.jupiter.api.Test;
+
+import com.fasterxml.jackson.core.*;
+import com.fasterxml.jackson.core.io.ContentReference;
+import com.fasterxml.jackson.core.io.IOContext;
+import com.fasterxml.jackson.core.util.BufferRecycler;
+import com.fasterxml.jackson.dataformat.csv.*;
+import com.fasterxml.jackson.dataformat.csv.impl.UTF8Reader;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+// [dataformats-text#763]: invalid UTF-8 (overlong encodings, surrogates,
+// values beyond U+10FFFF) must be rejected, with correct error positions
+public class InvalidUTF8Encoding763Test extends ModuleTestBase
+{
+ private final CsvFactory CSV_FACTORY = new CsvFactory();
+
+ // valid content preceding invalid bytes when testing via parser
+ private final static String PARSER_PREFIX = "a,b\nc,d";
+
+ @Test
+ public void testOverlongEncodings() throws Exception
+ {
+ // all encode '/' (0x2F) in more bytes than needed
+ assertInvalid("Invalid UTF-8 character 0x2f (overlong encoding)", 0xC0, 0xAF);
+ assertInvalid("Invalid UTF-8 character 0x2f (overlong encoding)", 0xE0, 0x80, 0xAF);
+ assertInvalid("Invalid UTF-8 character 0x2f (overlong encoding)", 0xF0, 0x80, 0x80, 0xAF);
+ // and largest values that need fewer bytes
+ assertInvalid("Invalid UTF-8 character 0x7f (overlong encoding)", 0xC1, 0xBF);
+ assertInvalid("Invalid UTF-8 character 0x7ff (overlong encoding)", 0xE0, 0x9F, 0xBF);
+ assertInvalid("Invalid UTF-8 character 0xffff (overlong encoding)", 0xF0, 0x8F, 0xBF, 0xBF);
+ }
+
+ @Test
+ public void testInvalidScalarValues() throws Exception
+ {
+ // surrogates, as per [jackson-core#363]
+ assertInvalid("Invalid UTF-8 character 0xd800 (not a valid Unicode scalar value)",
+ 0xED, 0xA0, 0x80);
+ assertInvalid("Invalid UTF-8 character 0xdfff (not a valid Unicode scalar value)",
+ 0xED, 0xBF, 0xBF);
+ // beyond U+10FFFF
+ assertInvalid("Invalid UTF-8 character 0x110000 (not a valid Unicode scalar value)",
+ 0xF4, 0x90, 0x80, 0x80);
+ assertInvalid("Invalid UTF-8 character 0x140000 (not a valid Unicode scalar value)",
+ 0xF5, 0x80, 0x80, 0x80);
+ }
+
+ @Test
+ public void testValidBoundaries() throws Exception
+ {
+ for (int cp : new int[] { 0x7F, 0x80, 0x7FF, 0x800, 0xD7FF, 0xE000, 0xFFFF,
+ 0x10000, Character.MAX_CODE_POINT }) {
+ String value = new String(Character.toChars(cp));
+ byte[] utf8 = value.getBytes(StandardCharsets.UTF_8);
+ try (UTF8Reader r = new UTF8Reader(null, utf8, 0, utf8.length)) {
+ char[] buf = new char[4];
+ int count = r.read(buf, 0, buf.length);
+ assertEquals(value, new String(buf, 0, count), "U+" + Integer.toHexString(cp));
+ assertEquals(-1, r.read(buf, 0, buf.length));
+ }
+ }
+ }
+
+ // [dataformat-csv#132]: content decoded before invalid sequence is returned first
+ @Test
+ public void testErrorDeferredUntilNextRead() throws Exception
+ {
+ byte[] doc = bytes("abé", 0xC0, 0xAF);
+ try (UTF8Reader r = new UTF8Reader(null, doc, 0, doc.length)) {
+ char[] buf = new char[10];
+ assertEquals(3, r.read(buf, 0, buf.length));
+ assertEquals("abé", new String(buf, 0, 3));
+ CharConversionException e = assertThrows(CharConversionException.class,
+ () -> r.read(buf, 0, buf.length));
+ assertEquals("Invalid UTF-8 character 0x2f (overlong encoding) (at char #4, byte #5)",
+ e.getMessage());
+ }
+ }
+
+ @Test
+ public void testErrorPositionWithOffset() throws Exception
+ {
+ byte[] doc = bytes("abé", 0xE0, 0x80, 0xAF);
+ byte[] padded = new byte[doc.length + 7];
+ Arrays.fill(padded, (byte) 'x');
+ System.arraycopy(doc, 0, padded, 3, doc.length);
+ assertEquals("Invalid UTF-8 character 0x2f (overlong encoding) (at char #4, byte #5)",
+ readFailure(padded, 3, doc.length));
+ }
+
+ @Test
+ public void testErrorPositionStartAndMiddleByte() throws Exception
+ {
+ byte[] doc = bytes("é", 0xFF);
+ assertEquals("Invalid UTF-8 start byte 0xff (at char #2, byte #3)"
+ + ": check content encoding, does not look like UTF-8",
+ readFailure(doc, 0, doc.length));
+ doc = bytes("abc", 0xE2, 0x82, 'A');
+ assertEquals("Invalid UTF-8 middle byte 0x41 (at char #4, byte #6)"
+ + ": check content encoding, does not look like UTF-8",
+ readFailure(doc, 0, doc.length));
+ }
+
+ @Test
+ public void testErrorPositionFromParser() throws Exception
+ {
+ // long enough to need several buffer loads before the bad bytes
+ char[] filler = new char[20000];
+ Arrays.fill(filler, 'x');
+ final String prefix = "a,b\n" + new String(filler) + ",é";
+ byte[] doc = bytes(prefix, 0xF0, 0x80, 0x80, 0xAF, '\n');
+ final int bytesBefore = prefix.getBytes(StandardCharsets.UTF_8).length;
+ final String expected = "Invalid UTF-8 character 0x2f (overlong encoding) (at char #"
+ + (prefix.length() + 1) + ", byte #" + (bytesBefore + 1) + ")";
+
+ assertEquals(expected, parseFailure(CSV_FACTORY.createParser(doc)));
+ assertEquals(expected, parseFailure(CSV_FACTORY.createParser(new ByteArrayInputStream(doc))));
+ // one byte at a time, so that partial sequences get shifted in the buffer
+ assertEquals(expected, parseFailure(CSV_FACTORY.createParser(new OneByteInputStream(doc))));
+
+ // with BOM, char positions are relative to content after it, but byte
+ // positions to start of input (as with jackson-core)
+ byte[] withBom = new byte[doc.length + 3];
+ withBom[0] = (byte) 0xEF;
+ withBom[1] = (byte) 0xBB;
+ withBom[2] = (byte) 0xBF;
+ System.arraycopy(doc, 0, withBom, 3, doc.length);
+ final String expectedWithBom = "Invalid UTF-8 character 0x2f (overlong encoding) (at char #"
+ + (prefix.length() + 1) + ", byte #" + (bytesBefore + 4) + ")";
+ assertEquals(expectedWithBom, parseFailure(CSV_FACTORY.createParser(withBom)));
+ assertEquals(expectedWithBom,
+ parseFailure(CSV_FACTORY.createParser(new ByteArrayInputStream(withBom))));
+ assertEquals(expectedWithBom,
+ parseFailure(CSV_FACTORY.createParser(new OneByteInputStream(withBom))));
+
+ // but start offset of byte[] input is not included
+ byte[] padded = new byte[withBom.length + 5];
+ System.arraycopy(withBom, 0, padded, 5, withBom.length);
+ assertEquals(expectedWithBom,
+ parseFailure(CSV_FACTORY.createParser(padded, 5, withBom.length)));
+ }
+
+ // Error must be reported again by following reads (not EOF), regardless of input source
+ @Test
+ public void testErrorRepeatedOnNextRead() throws Exception
+ {
+ // first truncated sequence (reported when trying to load more), then complete one
+ assertErrorRepeated(bytes("abc", 0xC0),
+ "Invalid UTF-8 sequence 0xc0 (overlong encoding) (at char #4, byte #4)");
+ assertErrorRepeated(bytes("abc", 0xC0, 0xAF),
+ "Invalid UTF-8 character 0x2f (overlong encoding) (at char #4, byte #4)");
+ }
+
+ private void assertErrorRepeated(byte[] doc, String expected) throws Exception
+ {
+ Reader[] readers = new Reader[] {
+ new UTF8Reader(null, doc, 0, doc.length),
+ new UTF8Reader(ioContext(), new ByteArrayInputStream(doc), true),
+ new UTF8Reader(ioContext(), new OneByteInputStream(doc), true)
+ };
+ for (Reader reader : readers) {
+ try (Reader r = reader) {
+ // content before invalid sequence first (one char at a time, for OneByteInputStream)
+ char[] buf = new char[10];
+ StringBuilder sb = new StringBuilder();
+ while (sb.length() < 3) {
+ int count = r.read(buf, 0, 3 - sb.length());
+ assertTrue(count > 0);
+ sb.append(buf, 0, count);
+ }
+ assertEquals("abc", sb.toString());
+ for (int i = 0; i < 2; ++i) {
+ CharConversionException e = assertThrows(CharConversionException.class,
+ () -> r.read(buf, 0, buf.length));
+ assertEquals(expected, e.getMessage());
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testErrorPositionUnexpectedEOF() throws Exception
+ {
+ byte[] doc = bytes("a,é", 0xE2, 0x82);
+ String msg = parseFailure(CSV_FACTORY.createParser(new OneByteInputStream(doc)));
+ assertTrue(msg.contains("got 2, needed 3 (at char #4, byte #5)"), msg);
+ }
+
+ // Truncated sequence at end of input with an invalid middle byte: report the
+ // invalid byte, not EOF
+ @Test
+ public void testInvalidMiddleByteBeforeEOF() throws Exception
+ {
+ assertInvalidMiddleByte(0x41, 2, 0xE2, 'A');
+ assertInvalidMiddleByte(0x41, 2, 0xF0, 'A');
+ assertInvalidMiddleByte(0x41, 3, 0xF0, 0x9F, 'A');
+ assertInvalidMiddleByte(0xc3, 2, 0xE2, 0xC3);
+ }
+
+ // Truncated sequence at end of input that can not be valid whatever follows:
+ // report it as invalid, not EOF
+ @Test
+ public void testInvalidTruncatedSequenceBeforeEOF() throws Exception
+ {
+ assertTruncated("Invalid UTF-8 sequence 0xc0 (overlong encoding)", 0xC0);
+ assertTruncated("Invalid UTF-8 sequence 0xc1 (overlong encoding)", 0xC1);
+ assertTruncated("Invalid UTF-8 sequence 0xe0 0x9f (overlong encoding)", 0xE0, 0x9F);
+ assertTruncated("Invalid UTF-8 sequence 0xf0 0x8f (overlong encoding)", 0xF0, 0x8F);
+ assertTruncated("Invalid UTF-8 sequence 0xf0 0x8f 0xbf (overlong encoding)",
+ 0xF0, 0x8F, 0xBF);
+ assertTruncated("Invalid UTF-8 sequence 0xed 0xa0 (not a valid Unicode scalar value)",
+ 0xED, 0xA0);
+ assertTruncated("Invalid UTF-8 sequence 0xf4 0x90 (not a valid Unicode scalar value)",
+ 0xF4, 0x90);
+ assertTruncated("Invalid UTF-8 sequence 0xf5 (not a valid Unicode scalar value)", 0xF5);
+ }
+
+ // ... but if it could still be valid, report as truncated
+ @Test
+ public void testValidTruncatedSequenceBeforeEOF() throws Exception
+ {
+ assertTruncated("Unexpected EOF in the middle of a multi-byte UTF-8 character: got 1, needed 2",
+ 0xC2);
+ assertTruncated("Unexpected EOF in the middle of a multi-byte UTF-8 character: got 1, needed 3",
+ 0xED);
+ assertTruncated("Unexpected EOF in the middle of a multi-byte UTF-8 character: got 2, needed 3",
+ 0xED, 0x9F);
+ assertTruncated("Unexpected EOF in the middle of a multi-byte UTF-8 character: got 2, needed 4",
+ 0xF0, 0x90);
+ assertTruncated("Unexpected EOF in the middle of a multi-byte UTF-8 character: got 3, needed 4",
+ 0xF4, 0x8F, 0xBF);
+ }
+
+ // Verifies that truncated sequence at end of input is reported with expected
+ // `error` and position (that of its first byte)
+ private void assertTruncated(String error, int... badBytes) throws Exception
+ {
+ byte[] doc = bytes("abc", badBytes);
+ assertEquals(error + " (at char #4, byte #4)", readFailure(doc, 0, doc.length));
+
+ doc = bytes(PARSER_PREFIX, badBytes);
+ final int pos = PARSER_PREFIX.length() + 1;
+ final String expected = error + " (at char #" + pos + ", byte #" + pos + ")";
+ assertEquals(expected, parseFailure(CSV_FACTORY.createParser(doc)));
+ assertEquals(expected, parseFailure(CSV_FACTORY.createParser(new ByteArrayInputStream(doc))));
+ assertEquals(expected, parseFailure(CSV_FACTORY.createParser(new OneByteInputStream(doc))));
+ }
+
+ private void assertInvalidMiddleByte(int badByte, int badByteIndex, int... badBytes)
+ throws Exception
+ {
+ final String error = "Invalid UTF-8 middle byte 0x" + Integer.toHexString(badByte);
+ final String notUtf8 = ": check content encoding, does not look like UTF-8";
+
+ byte[] doc = bytes("abc", badBytes);
+ assertEquals(error + " (at char #4, byte #" + (3 + badByteIndex) + ")" + notUtf8,
+ readFailure(doc, 0, doc.length));
+
+ doc = bytes(PARSER_PREFIX, badBytes);
+ final String expected = error + " (at char #" + (PARSER_PREFIX.length() + 1)
+ + ", byte #" + (PARSER_PREFIX.length() + badByteIndex) + ")" + notUtf8;
+ assertEquals(expected, parseFailure(CSV_FACTORY.createParser(doc)));
+ assertEquals(expected, parseFailure(CSV_FACTORY.createParser(new ByteArrayInputStream(doc))));
+ assertEquals(expected, parseFailure(CSV_FACTORY.createParser(new OneByteInputStream(doc))));
+ }
+
+ // Verifies that invalid sequence is reported with expected `error` and position,
+ // both as the only content and after valid content (via parser)
+ private void assertInvalid(String error, int... badBytes) throws Exception
+ {
+ byte[] doc = bytes("", badBytes);
+ assertEquals(error + " (at char #1, byte #1)", readFailure(doc, 0, doc.length));
+
+ doc = bytes(PARSER_PREFIX, badBytes);
+ final int pos = PARSER_PREFIX.length() + 1;
+ final String expected = error + " (at char #" + pos + ", byte #" + pos + ")";
+ assertEquals(expected, parseFailure(CSV_FACTORY.createParser(doc)));
+ assertEquals(expected, parseFailure(CSV_FACTORY.createParser(new ByteArrayInputStream(doc))));
+ // one byte at a time, so that deferred error follows buffer shifts
+ assertEquals(expected, parseFailure(CSV_FACTORY.createParser(new OneByteInputStream(doc))));
+ }
+
+ private static IOContext ioContext() {
+ return new IOContext(StreamReadConstraints.defaults(),
+ StreamWriteConstraints.defaults(), ErrorReportConfiguration.defaults(),
+ new BufferRecycler(), ContentReference.unknown(), false);
+ }
+
+ private static byte[] bytes(String prefix, int... suffix) {
+ byte[] start = prefix.getBytes(StandardCharsets.UTF_8);
+ byte[] result = Arrays.copyOf(start, start.length + suffix.length);
+ for (int i = 0; i < suffix.length; ++i) {
+ result[start.length + i] = (byte) suffix[i];
+ }
+ return result;
+ }
+
+ private static String readFailure(byte[] buf, int offset, int len) throws IOException {
+ try (UTF8Reader r = new UTF8Reader(null, buf, offset, len)) {
+ // content before invalid sequence is returned first, error by next read()
+ return assertThrows(CharConversionException.class, () -> {
+ char[] chars = new char[100];
+ while (r.read(chars, 0, chars.length) >= 0) { }
+ }).getMessage();
+ }
+ }
+
+ private static String parseFailure(JsonParser p) throws IOException {
+ try (JsonParser parser = p) {
+ return assertThrows(CharConversionException.class, () -> {
+ while (parser.nextToken() != null) {
+ parser.getText();
+ }
+ }).getMessage();
+ }
+ }
+
+ static class OneByteInputStream extends ByteArrayInputStream {
+ OneByteInputStream(byte[] data) {
+ super(data);
+ }
+
+ @Override
+ public synchronized int read(byte[] b, int off, int len) {
+ return super.read(b, off, Math.min(len, 1));
+ }
+ }
+}
=====================================
csv/src/test/java/com/fasterxml/jackson/dataformat/csv/deser/UTF8ReaderTest.java
=====================================
@@ -0,0 +1,54 @@
+package com.fasterxml.jackson.dataformat.csv.deser;
+
+import java.nio.charset.StandardCharsets;
+
+import org.junit.jupiter.api.Test;
+
+import com.fasterxml.jackson.dataformat.csv.ModuleTestBase;
+import com.fasterxml.jackson.dataformat.csv.impl.UTF8Reader;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public class UTF8ReaderTest extends ModuleTestBase
+{
+ // Zero-length read must not consume (or write) buffered second surrogate
+ @Test
+ public void testZeroLengthReadWithPendingSurrogate() throws Exception
+ {
+ final String value = new String(Character.toChars(0x1F600));
+ byte[] utf8 = value.getBytes(StandardCharsets.UTF_8);
+ try (UTF8Reader r = new UTF8Reader(null, utf8, 0, utf8.length)) {
+ char[] buf = new char[2];
+ assertEquals(1, r.read(buf, 0, 1));
+ assertEquals(value.charAt(0), buf[0]);
+
+ buf[1] = 'x';
+ assertEquals(0, r.read(buf, 1, 0));
+ assertEquals('x', buf[1]);
+
+ assertEquals(1, r.read(buf, 1, 1));
+ assertEquals(value.charAt(1), buf[1]);
+ assertEquals(-1, r.read(buf, 0, 2));
+ }
+ }
+
+ @Test
+ public void testInvalidBounds() throws Exception
+ {
+ byte[] utf8 = "abc".getBytes(StandardCharsets.UTF_8);
+ try (UTF8Reader r = new UTF8Reader(null, utf8, 0, utf8.length)) {
+ char[] buf = new char[2];
+ assertThrows(IndexOutOfBoundsException.class, () -> r.read(buf, -1, 1));
+ assertThrows(IndexOutOfBoundsException.class, () -> r.read(buf, 0, -1));
+ assertThrows(IndexOutOfBoundsException.class, () -> r.read(buf, 1, 2));
+ // invalid offset must be caught even if nothing is to be read
+ assertThrows(IndexOutOfBoundsException.class, () -> r.read(buf, -1, 0));
+ assertThrows(IndexOutOfBoundsException.class, () -> r.read(buf, 3, 0));
+ // but end of buffer is a valid offset for empty read
+ assertEquals(0, r.read(buf, 2, 0));
+ // but valid reads still work after
+ assertEquals(2, r.read(buf, 0, 2));
+ assertEquals("ab", new String(buf));
+ }
+ }
+}
=====================================
csv/src/test/java/com/fasterxml/jackson/dataformat/csv/fuzz/FuzzCSVReadTest.java
=====================================
@@ -1,16 +1,18 @@
package com.fasterxml.jackson.dataformat.csv.fuzz;
import java.io.ByteArrayInputStream;
+import java.io.CharConversionException;
import java.io.IOException;
import org.junit.jupiter.api.Test;
-import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.ModuleTestBase;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Collection of OSS-Fuzz found issues for CSV format module.
@@ -53,11 +55,32 @@ public class FuzzCSVReadTest extends ModuleTestBase
public void testReadBoundary50402() throws Exception
{
byte[] input = readResource("/data/fuzz-50402.csv");
+ // Was about buffer reads, but input also has overlong UTF-8 sequences
+ // (like `C0 AD` at byte #2975), rejected since [dataformats-text#763]
try {
CSV_MAPPER.readTree(input);
- // Ok; don't care about content, just buffer reads
- } catch (JacksonException e) {
- verifyException(e, "foo");
+ fail("Should not pass");
+ } catch (CharConversionException e) {
+ verifyException(e, "Invalid UTF-8 character 0x2d (overlong encoding) (at char #2975, byte #2975)");
+ }
+ }
+
+ // ... so to still test buffer reads, replace overlong `C0 AD` sequences (the only
+ // invalid UTF-8 in input) with valid `C2 AD`, keeping buffer boundaries as they were
+ @Test
+ public void testReadBoundary50402Valid() throws Exception
+ {
+ byte[] input = readResource("/data/fuzz-50402.csv");
+ int replaced = 0;
+ for (int i = 0; i < input.length - 1; ++i) {
+ if (input[i] == (byte) 0xC0 && input[i+1] == (byte) 0xAD) {
+ input[i] = (byte) 0xC2;
+ ++replaced;
+ }
}
+ assertEquals(172, replaced);
+ // Ok; don't care about content, just that whole input is read
+ assertNotNull(CSV_MAPPER.readTree(input));
+ assertNotNull(CSV_MAPPER.readTree(new ByteArrayInputStream(input)));
}
}
=====================================
csv/src/test/java/com/fasterxml/jackson/dataformat/csv/schema/CsvSchemaTest.java
=====================================
@@ -253,4 +253,86 @@ public class CsvSchemaTest extends ModuleTestBase
_verifyLinks(pointSchema);
}
+
+ // For [dataformats-text#699]: modify columns in Builder by name
+ @Test
+ public void testModifyColumnsByName()
+ {
+ CsvSchema.Builder b = CsvSchema.builder()
+ .addColumn("a", CsvSchema.ColumnType.STRING)
+ .addColumn("b", CsvSchema.ColumnType.NUMBER)
+ .addColumn("c", CsvSchema.ColumnType.BOOLEAN);
+
+ // rename by name maps to same slot as rename by index
+ b.renameColumn("b", "b2");
+ // replace by name preserves position, changes type; note that index of
+ // the replacement Column is deliberately "wrong" (0, not 2) to verify it
+ // is ignored -- the whole point being caller need not know the index
+ b.replaceColumn("c", new Column(0, "c2", CsvSchema.ColumnType.STRING));
+
+ CsvSchema schema = b.build();
+ assertEquals(3, schema.size());
+ assertEquals("a", schema.column(0).getName());
+ assertEquals("b2", schema.column(1).getName());
+ assertEquals(CsvSchema.ColumnType.NUMBER, schema.column(1).getType());
+ assertEquals("c2", schema.column(2).getName());
+ assertEquals(CsvSchema.ColumnType.STRING, schema.column(2).getType());
+ // ... and index gets renumbered to match actual position
+ assertEquals(2, schema.column(2).getIndex());
+ assertEquals(2, schema.columnIndex("c2"));
+
+ // remove by name drops just that column
+ CsvSchema shrunk = schema.rebuild().removeColumn("a").build();
+ assertEquals(2, shrunk.size());
+ assertEquals("b2", shrunk.column(0).getName());
+ assertEquals("c2", shrunk.column(1).getName());
+ }
+
+ // For [dataformats-text#699]: type and array-element-separator by name too
+ @Test
+ public void testModifyColumnSettingsByName()
+ {
+ CsvSchema.Builder b = CsvSchema.builder()
+ .addColumn("a", CsvSchema.ColumnType.STRING)
+ .addColumn("tags", CsvSchema.ColumnType.ARRAY);
+
+ b.setColumnType("a", CsvSchema.ColumnType.NUMBER);
+ b.setArrayElementSeparator("tags", ";");
+
+ CsvSchema schema = b.build();
+ assertEquals(CsvSchema.ColumnType.NUMBER, schema.column(0).getType());
+ assertEquals(";", schema.column(1).getArrayElementSeparator());
+
+ // and removal of separator, likewise by name
+ assertEquals("", schema.rebuild().removeArrayElementSeparator("tags")
+ .build().column(1).getArrayElementSeparator());
+ }
+
+ // For [dataformats-text#699]: non-throwing index lookup from Builder
+ @Test
+ public void testColumnIndexLookupFromBuilder()
+ {
+ CsvSchema.Builder b = CsvSchema.builder().addColumn("a").addColumn("b");
+ assertEquals(0, b.columnIndex("a"));
+ assertEquals(1, b.columnIndex("b"));
+ assertEquals(-1, b.columnIndex("missing"));
+ // and `hasColumn()` remains consistent with it
+ assertTrue(b.hasColumn("a"));
+ assertFalse(b.hasColumn("missing"));
+ }
+
+ // For [dataformats-text#699]: unknown name should fail fast, and the failure
+ // should name the columns that DO exist (as `CsvSchema.withColumn(String,...)` does)
+ @Test
+ public void testModifyUnknownColumnByName()
+ {
+ CsvSchema.Builder b = CsvSchema.builder().addColumn("a");
+ try {
+ b.removeColumn("missing");
+ fail("Should not pass");
+ } catch (IllegalArgumentException e) {
+ verifyException(e, "No column 'missing' in CsvSchema.Builder");
+ verifyException(e, "known columns: [a]");
+ }
+ }
}
=====================================
debian/changelog
=====================================
@@ -1,3 +1,10 @@
+jackson-dataformats-text (2.23.0-1) unstable; urgency=medium
+
+ * New upstream release
+ - Tightened the dependencies on the other jackson packages
+
+ -- Emmanuel Bourg <ebourg at apache.org> Mon, 09 Nov 2026 17:27:27 +0100
+
jackson-dataformats-text (2.22.4-1) unstable; urgency=medium
* New upstream release
=====================================
debian/control
=====================================
@@ -7,9 +7,9 @@ Build-Depends:
default-jdk,
junit5,
libbuild-helper-maven-plugin-java,
- libjackson2-annotations-java (>= 2.22),
- libjackson2-core-java (>= 2.22.4),
- libjackson2-databind-java (>= 2.22.4),
+ libjackson2-annotations-java (>= 2.23),
+ libjackson2-core-java (>= 2.23.0),
+ libjackson2-databind-java (>= 2.23.0),
libmaven-bundle-plugin-java,
libreplacer-java,
libyaml-snake-java (>= 2.5),
=====================================
pom.xml
=====================================
@@ -3,12 +3,12 @@
<parent>
<groupId>com.fasterxml.jackson</groupId>
<artifactId>jackson-base</artifactId>
- <version>2.22.4</version>
+ <version>2.23.0</version>
</parent>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformats-text</artifactId>
<name>Jackson dataformats: Text</name>
- <version>2.22.4</version>
+ <version>2.23.0</version>
<packaging>pom</packaging>
<description>Parent pom for Jackson text-based dataformats (as opposed to binary).
</description>
@@ -33,7 +33,7 @@
<connection>scm:git:git at github.com:FasterXML/jackson-dataformats-text.git</connection>
<developerConnection>scm:git:git at github.com:FasterXML/jackson-dataformats-text.git</developerConnection>
<url>https://github.com/FasterXML/jackson-dataformats-text</url>
- <tag>jackson-dataformats-text-2.22.4</tag>
+ <tag>jackson-dataformats-text-2.23.0</tag>
</scm>
<issueManagement>
<url>https://github.com/FasterXML/jackson-dataformats-text/issues</url>
@@ -41,7 +41,7 @@
<properties>
<!-- for Reproducible Builds -->
- <project.build.outputTimestamp>2026-10-17T23:22:58Z</project.build.outputTimestamp>
+ <project.build.outputTimestamp>2026-11-08T00:55:39Z</project.build.outputTimestamp>
</properties>
<dependencies>
=====================================
properties/pom.xml
=====================================
@@ -9,7 +9,7 @@
<parent>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformats-text</artifactId>
- <version>2.22.4</version>
+ <version>2.23.0</version>
</parent>
<artifactId>jackson-dataformat-properties</artifactId>
<name>Jackson-dataformat-Properties</name>
=====================================
release-notes/CREDITS-2.x
=====================================
@@ -337,3 +337,35 @@ Dmitry Bufistov (@dmitry-workato)
* Requested #601: (csv) Reader should allow separating plain `nullValue`
and quoted value `"nullValue"`
(2.22.0)
+
+EverNife (@EverNife)
+
+* Reported #696: (toml) Write non-finite floating-point values as TOML tokens
+ (`nan`/`inf`/`-inf`) instead of Java tokens (`NaN`/`Infinity`)
+ (2.23.0)
+
+seonwoojung (@seonwooj0810)
+
+* Fixed #696: (toml) Write non-finite floating-point values as TOML tokens
+ (`nan`/`inf`/`-inf`) instead of Java tokens (`NaN`/`Infinity`)
+ (2.23.0)
+
+James Howe (@OrangeDog)
+
+* Requested #699: (csv) Ability to modify columns in `CsvSchema.Builder` by name
+ (2.23.0)
+
+seonwoojung (@seonwooj0810)
+
+* Fixed #699: (csv) Ability to modify columns in `CsvSchema.Builder` by name
+ (2.23.0)
+
+ at rajulbhatnagar
+
+* Reported #663: (toml) TOML parser: int64 max value parsed as truncated long
+ (2.23.0)
+
+Jonas Konrad (@yawkat)
+
+* Fixed #663: (toml) TOML parser: int64 max value parsed as truncated long
+ (2.23.0)
=====================================
release-notes/VERSION-2.x
=====================================
@@ -14,6 +14,32 @@ Active Maintainers:
=== Releases ===
------------------------------------------------------------------------
+2.23.0 (07-Nov-2026)
+
+#663: (toml) TOML parser: int64 max value parsed as truncated long
+ (reported by @rajulbhatnagar)
+ (fix by @yawkat)
+#696: (toml) Write non-finite floating-point values as TOML tokens
+ (`nan`/`inf`/`-inf`) instead of Java tokens (`NaN`/`Infinity`)
+ (reported by @EverNife)
+ (fix by @seonwooj0810)
+#699: (csv) Ability to modify columns in `CsvSchema.Builder` by name
+ (requested by @OrangeDog)
+ (fix by @seonwooj0810)
+#746: (toml) Fix multiple `TomlGenerator` value-writing issues: `writeUTF8String()`
+ writes an extra empty line; `writeRawValue()` writes no line feed after value;
+ `writeBinary()` silently pads invalid ranges with zero bytes; `writeString()`,
+ `writeRaw()` do not validate offset/length; String value with unsupported
+ characters fails after key is written, with misleading "Key contains ..." message
+#763: (csv) Overlong UTF-8 sequences, encoded surrogates and values beyond U+10FFFF
+ not rejected; wrong char/byte positions in invalid UTF-8 error messages
+ (NOTE: CESU-8 / "Modified UTF-8" content is now also rejected)
+ (fix by @pjfanning)
+#764: (yaml) Overlong UTF-8 sequences, encoded surrogates and values beyond U+10FFFF
+ not rejected; wrong char/byte positions in invalid UTF-8 error messages
+ (NOTE: CESU-8 / "Modified UTF-8" content is now also rejected)
+ (fix by @pjfanning)
+
2.22.4 (17-Oct-2026)
#726: (toml) `TomlGenerator.writeString(char[], int, int)` writes wrong characters
=====================================
toml/pom.xml
=====================================
@@ -9,7 +9,7 @@
<parent>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformats-text</artifactId>
- <version>2.22.4</version>
+ <version>2.23.0</version>
</parent>
<artifactId>jackson-dataformat-toml</artifactId>
<packaging>jar</packaging>
=====================================
toml/src/main/java/com/fasterxml/jackson/dataformat/toml/Parser.java
=====================================
@@ -3,6 +3,7 @@ package com.fasterxml.jackson.dataformat.toml;
import java.io.IOException;
import java.io.Reader;
import java.math.BigDecimal;
+import java.math.BigInteger;
import java.time.*;
import java.time.temporal.Temporal;
@@ -383,8 +384,16 @@ class Parser {
return factory.numberNode(v);
}
if (length <= 18 || NumberInput.inLongRange(buffer, start, length, negative)) {
- long v = NumberInput.parseLong(buffer, start, length);
- if (negative) v = -v;
+ long v;
+ if (length <= 18) {
+ v = NumberInput.parseLong(buffer, start, length);
+ if (negative) {
+ v = -v;
+ }
+ } else {
+ // [dataformats-text#663]: 19-digit values need separate handling
+ v = NumberInput.parseLong19(buffer, start, negative);
+ }
// Might still fit in int, need to check
if ((int) v == v) {
return factory.numberNode((int) v);
@@ -400,9 +409,11 @@ class Parser {
: new String(buffer, start, MAX_CHARS_TO_REPORT) + " [truncated]";
throw errorContext.atPosition(lexer).invalidNumber(e, reportNum);
}
- return factory.numberNode(NumberInput.parseBigInteger(
+ BigInteger big = NumberInput.parseBigInteger(
new String(buffer, start, length),
- tomlFactory.isEnabled(StreamReadFeature.USE_FAST_BIG_NUMBER_PARSER)));
+ tomlFactory.isEnabled(StreamReadFeature.USE_FAST_BIG_NUMBER_PARSER));
+ // sign was skipped above, need to re-apply
+ return factory.numberNode(negative ? big.negate() : big);
}
private JsonNode parseFloat(int nextState) throws IOException {
=====================================
toml/src/main/java/com/fasterxml/jackson/dataformat/toml/TomlGenerator.java
=====================================
@@ -319,7 +319,7 @@ final class TomlGenerator extends GeneratorBase
if (_streamWriteContext.hasCurrentIndex()) {
_writeRaw(", ");
}
- _writeStringImpl(StringOutputUtil.MASK_SIMPLE_KEY, name);
+ _writeStringImpl(StringOutputUtil.categorize(name) & StringOutputUtil.MASK_SIMPLE_KEY, name);
} else {
// Ok; append to base path at this point.
// First: ensure possibly preceding property name is removed:
@@ -418,15 +418,21 @@ final class TomlGenerator extends GeneratorBase
writeNull();
return;
}
+ // validate before writing anything (key, separator)
+ final int cat = _stringValueCategories(StringOutputUtil.categorize(text));
_verifyValueWrite("write String value");
- _writeStringImpl(StringOutputUtil.MASK_STRING, text);
+ _writeStringImpl(cat, text);
writeValueEnd();
}
@Override
public void writeString(char[] text, int offset, int len) throws IOException {
+ // NOTE: also reports `null` array as error
+ _checkRangeBoundsForCharArray(text, offset, len);
+ // validate before writing anything (key, separator)
+ final int cat = _stringValueCategories(StringOutputUtil.categorize(text, offset, len));
_verifyValueWrite("write String value");
- _writeStringImpl(StringOutputUtil.MASK_STRING, text, offset, len);
+ _writeStringImpl(cat, text, offset, len);
writeValueEnd();
}
@@ -437,8 +443,10 @@ final class TomlGenerator extends GeneratorBase
@Override
public void writeUTF8String(byte[] text, int offset, int len) throws IOException {
+ // NOTE: also reports `null` array as error
+ _checkRangeBoundsForByteArray(text, offset, len);
+ // NOTE: writeString() already calls writeValueEnd()
writeString(new String(text, offset, len, StandardCharsets.UTF_8));
- writeValueEnd();
}
/*
@@ -454,11 +462,13 @@ final class TomlGenerator extends GeneratorBase
@Override
public void writeRaw(String text, int offset, int len) throws IOException {
+ _checkRangeBoundsForString(text, offset, len);
_writeRaw(text.substring(offset, offset + len));
}
@Override
public void writeRaw(char[] text, int offset, int len) throws IOException {
+ _checkRangeBoundsForCharArray(text, offset, len);
_writeRaw(text, offset, len);
}
@@ -472,6 +482,36 @@ final class TomlGenerator extends GeneratorBase
writeRaw(text.toString());
}
+ // Overridden since `GeneratorBase` implementations do not call `writeValueEnd()`
+
+ @Override
+ public void writeRawValue(String text) throws IOException {
+ _verifyValueWrite("write raw value");
+ _writeRaw(text);
+ writeValueEnd();
+ }
+
+ @Override
+ public void writeRawValue(String text, int offset, int len) throws IOException {
+ _checkRangeBoundsForString(text, offset, len);
+ _verifyValueWrite("write raw value");
+ _writeRaw(text.substring(offset, offset + len));
+ writeValueEnd();
+ }
+
+ @Override
+ public void writeRawValue(char[] text, int offset, int len) throws IOException {
+ _checkRangeBoundsForCharArray(text, offset, len);
+ _verifyValueWrite("write raw value");
+ _writeRaw(text, offset, len);
+ writeValueEnd();
+ }
+
+ @Override
+ public void writeRawValue(SerializableString text) throws IOException {
+ writeRawValue(text.getValue());
+ }
+
/*
/**********************************************************************
/* Output method implementations, base64-encoded binary
@@ -485,6 +525,7 @@ final class TomlGenerator extends GeneratorBase
writeNull();
return;
}
+ _checkRangeBoundsForByteArray(data, offset, len);
_verifyValueWrite("write Binary value");
// ok, better just Base64 encode as a String...
if (offset > 0 || (offset + len) != data.length) {
@@ -546,17 +587,37 @@ final class TomlGenerator extends GeneratorBase
@Override
public void writeNumber(double d) throws IOException {
_verifyValueWrite("write number");
- _writeRaw(String.valueOf(d));
+ _writeRaw(_nonFiniteTomlToken(d, String.valueOf(d)));
writeValueEnd();
}
@Override
public void writeNumber(float f) throws IOException {
_verifyValueWrite("write number");
- _writeRaw(String.valueOf(f));
+ _writeRaw(_nonFiniteTomlToken(f, String.valueOf(f)));
writeValueEnd();
}
+ /**
+ * Maps a non-finite floating-point value to the TOML float token
+ * ({@code nan}, {@code inf} or {@code -inf}); finite values are written
+ * using the supplied Java text form. {@code String.valueOf(...)} would
+ * otherwise emit {@code NaN} / {@code Infinity} / {@code -Infinity}, which
+ * are not valid TOML and cannot be read back by the parser.
+ */
+ private static String _nonFiniteTomlToken(double d, String finiteForm) {
+ if (Double.isNaN(d)) {
+ return "nan";
+ }
+ if (d == Double.POSITIVE_INFINITY) {
+ return "inf";
+ }
+ if (d == Double.NEGATIVE_INFINITY) {
+ return "-inf";
+ }
+ return finiteForm;
+ }
+
@Override
public void writeNumber(BigDecimal dec) throws IOException {
if (dec == null) {
@@ -586,7 +647,7 @@ final class TomlGenerator extends GeneratorBase
throw new TomlStreamWriteException("TOML null writing disabled (TomlWriteFeature.FAIL_ON_NULL_WRITE)", this);
}
_verifyValueWrite("write null value");
- _writeStringImpl(StringOutputUtil.MASK_STRING, "");
+ _writeStringImpl(_stringValueCategories(StringOutputUtil.categorize("")), "");
writeValueEnd();
}
@@ -661,13 +722,16 @@ final class TomlGenerator extends GeneratorBase
}
path.append('"');
} else {
- throw new TomlStreamWriteException("Key contains unsupported characters", this);
+ _reportUnsupportedKeyCharacters();
}
// NOTE: we do NOT yet write the key; wait until we have value; just append to path
}
- private void _writeStringImpl(int categoryMask, String name) throws IOException {
- int cat = StringOutputUtil.categorize(name) & categoryMask;
+ /**
+ * @param cat Categories of {@code name} (see {@link StringOutputUtil}), already masked
+ * for the context (key or value)
+ */
+ private void _writeStringImpl(int cat, String name) throws IOException {
if ((cat & StringOutputUtil.UNQUOTED_KEY) != 0) {
_writeRaw(name);
} else if ((cat & StringOutputUtil.LITERAL_STRING) != 0) {
@@ -691,12 +755,13 @@ final class TomlGenerator extends GeneratorBase
}
_writeRaw('"');
} else {
- throw new TomlStreamWriteException("Key contains unsupported characters", this);
+ // String values are validated before writing (see _stringValueCategories()),
+ // so only keys can get here
+ _reportUnsupportedKeyCharacters();
}
}
- private void _writeStringImpl(int categoryMask, char[] text, int offset, int len) throws IOException {
- int cat = StringOutputUtil.categorize(text, offset, len) & categoryMask;
+ private void _writeStringImpl(int cat, char[] text, int offset, int len) throws IOException {
if ((cat & StringOutputUtil.UNQUOTED_KEY) != 0) {
_writeRaw(text, offset, len);
} else if ((cat & StringOutputUtil.LITERAL_STRING) != 0) {
@@ -720,8 +785,27 @@ final class TomlGenerator extends GeneratorBase
}
_writeRaw('"');
} else {
- throw new TomlStreamWriteException("Key contains unsupported characters", this);
+ // String values are validated before writing (see _stringValueCategories()),
+ // so only keys can get here
+ _reportUnsupportedKeyCharacters();
+ }
+ }
+
+ private void _reportUnsupportedKeyCharacters() throws IOException {
+ throw new TomlStreamWriteException("Key contains unsupported characters", this);
+ }
+
+ /**
+ * Masks categories of a String value and verifies it can be written; to be called
+ * before {@link #_verifyValueWrite} so that nothing is written for invalid values.
+ */
+ private int _stringValueCategories(int cat) throws IOException {
+ cat &= StringOutputUtil.MASK_STRING;
+ if ((cat & (StringOutputUtil.LITERAL_STRING | StringOutputUtil.BASIC_STRING
+ | StringOutputUtil.BASIC_STRING_NO_ESCAPE)) == 0) {
+ throw new TomlStreamWriteException("String value contains unsupported characters", this);
}
+ return cat;
}
/*
=====================================
toml/src/test/java/com/fasterxml/jackson/dataformat/toml/ComplianceValidTest.java
=====================================
@@ -117,7 +117,7 @@ public class ComplianceValidTest extends TomlMapperTestBase {
}
} else {
ObjectNode object = expected.objectNode();
- for (Map.Entry<String, JsonNode> field : (Iterable<? extends Map.Entry<String, JsonNode>>) expected::fields) {
+ for (Map.Entry<String, JsonNode> field : expected.properties()) {
object.set(field.getKey(), mapFromComplianceNode((ObjectNode) field.getValue()));
}
return object;
=====================================
toml/src/test/java/com/fasterxml/jackson/dataformat/toml/TomlGeneratorTest.java
=====================================
@@ -1,15 +1,20 @@
package com.fasterxml.jackson.dataformat.toml;
import java.io.*;
+import java.nio.charset.StandardCharsets;
import java.time.*;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.exc.StreamWriteException;
+import com.fasterxml.jackson.core.io.SerializedString;
+import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class TomlGeneratorTest extends TomlMapperTestBase {
@Test
@@ -52,6 +57,207 @@ public class TomlGeneratorTest extends TomlMapperTestBase {
assertEquals(value, newTomlMapper().readTree(w.toString()).get("abc").textValue());
}
+ // [#726]: long value (exceeds output buffer) with escapes, sliced from the middle
+ // of a larger array, so both index-bound directions are exercised
+ @Test
+ public void longStringFromCharArrayNeedingEscapes() throws IOException {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < 2000; ++i) {
+ sb.append("line \"").append(i).append("\"\n");
+ }
+ final String value = sb.toString();
+ char[] padded = ("<<<" + value + ">>>").toCharArray();
+ StringWriter w = new StringWriter();
+ try (JsonGenerator generator = newTomlMapper().createGenerator(w)) {
+ generator.writeStartObject();
+ generator.writeFieldName("abc");
+ generator.writeString(padded, 3, value.length());
+ generator.writeEndObject();
+ }
+ StringWriter w2 = new StringWriter();
+ try (JsonGenerator generator = newTomlMapper().createGenerator(w2)) {
+ generator.writeStartObject();
+ generator.writeFieldName("abc");
+ generator.writeString(value);
+ generator.writeEndObject();
+ }
+ assertEquals(w2.toString(), w.toString());
+ assertEquals(value, newTomlMapper().readTree(w.toString()).get("abc").textValue());
+ }
+
+ // `null` arrays are caller errors (as with JSON generators), not TOML nulls
+ @Test
+ public void nullArraysAsStrings() throws IOException {
+ StringWriter w = new StringWriter();
+ try (JsonGenerator generator = newTomlMapper().createGenerator(w)) {
+ generator.writeStartObject();
+ generator.writeFieldName("abc");
+ StreamWriteException e = assertThrows(StreamWriteException.class,
+ () -> generator.writeString((char[]) null, 0, 0));
+ assertTrue(e.getMessage().contains("null"), e.getMessage());
+ e = assertThrows(StreamWriteException.class,
+ () -> generator.writeUTF8String(null, 0, 0));
+ assertTrue(e.getMessage().contains("null"), e.getMessage());
+ // nothing written, generator still usable
+ generator.writeNull();
+ generator.writeEndObject();
+ }
+ assertEquals("abc = \'\'\n", w.toString());
+ }
+
+ @Test
+ public void invalidUTF8StringRange() throws IOException {
+ StringWriter w = new StringWriter();
+ try (JsonGenerator generator = newTomlMapper().createGenerator(w)) {
+ generator.writeStartObject();
+ generator.writeFieldName("abc");
+ final byte[] utf8 = "abc".getBytes(StandardCharsets.UTF_8);
+ assertThrows(StreamWriteException.class,
+ () -> generator.writeUTF8String(utf8, 2, 5));
+ assertThrows(StreamWriteException.class,
+ () -> generator.writeUTF8String(utf8, -1, 1));
+ assertThrows(StreamWriteException.class,
+ () -> generator.writeUTF8String(utf8, 0, -1));
+ // nothing written, generator still usable
+ generator.writeUTF8String(utf8, 1, 2);
+ generator.writeEndObject();
+ }
+ assertEquals("abc = 'bc'\n", w.toString());
+ }
+
+ // Invalid String values must fail before anything (key, separator) is written,
+ // leaving generator usable
+ @Test
+ public void unsupportedCharsInStringValue() throws IOException {
+ StringWriter w = new StringWriter();
+ try (JsonGenerator generator = newTomlMapper().createGenerator(w)) {
+ generator.writeStartObject();
+ generator.writeFieldName("abc");
+ TomlStreamWriteException e = assertThrows(TomlStreamWriteException.class,
+ () -> generator.writeString(new char[] { '\uD800', 'x' }, 0, 2));
+ assertTrue(e.getMessage().startsWith("String value contains unsupported characters"),
+ e.getMessage());
+ e = assertThrows(TomlStreamWriteException.class,
+ () -> generator.writeString("\uD800x"));
+ assertTrue(e.getMessage().startsWith("String value contains unsupported characters"),
+ e.getMessage());
+ generator.writeString("ok");
+ generator.writeEndObject();
+ }
+ assertEquals("abc = 'ok'\n", w.toString());
+ }
+
+ @Test
+ public void unsupportedCharsInInlineKey() throws IOException {
+ StringWriter w = new StringWriter();
+ try (JsonGenerator generator = newTomlMapper().createGenerator(w)) {
+ generator.writeStartObject();
+ generator.writeFieldName("abc");
+ generator.writeStartArray();
+ generator.writeStartObject();
+ TomlStreamWriteException e = assertThrows(TomlStreamWriteException.class,
+ () -> generator.writeFieldName("\uD800x"));
+ assertTrue(e.getMessage().startsWith("Key contains unsupported characters"),
+ e.getMessage());
+ }
+ }
+
+ @Test
+ public void invalidCharArrayRange() throws IOException {
+ StringWriter w = new StringWriter();
+ try (JsonGenerator generator = newTomlMapper().createGenerator(w)) {
+ generator.writeStartObject();
+ generator.writeFieldName("abc");
+ final char[] chars = "ab\"c".toCharArray();
+ StreamWriteException e = assertThrows(StreamWriteException.class,
+ () -> generator.writeString(chars, 2, 10));
+ assertTrue(e.getMessage().contains("Invalid 'offset'"), e.getMessage());
+ assertThrows(StreamWriteException.class,
+ () -> generator.writeString(chars, 0, -1));
+ // nothing written, generator still usable
+ generator.writeString(chars, 2, 2);
+ generator.writeEndObject();
+ }
+ assertEquals("abc = '\"c'\n", w.toString());
+ }
+
+ @Test
+ public void invalidBinaryRange() throws IOException {
+ StringWriter w = new StringWriter();
+ try (JsonGenerator generator = newTomlMapper().createGenerator(w)) {
+ generator.writeStartObject();
+ generator.writeFieldName("abc");
+ final byte[] data = new byte[] { 1, 2 };
+ // used to silently pad with zero bytes
+ assertThrows(StreamWriteException.class,
+ () -> generator.writeBinary(data, 1, 5));
+ assertThrows(StreamWriteException.class,
+ () -> generator.writeBinary(data, -1, 1));
+ generator.writeBinary(data, 1, 1);
+ generator.writeEndObject();
+ }
+ assertEquals("abc = 'Ag=='\n", w.toString());
+ }
+
+ // `writeRawValue()` variants did not call `writeValueEnd()`: no line feed after value
+ @Test
+ public void rawValue() throws IOException {
+ StringWriter w = new StringWriter();
+ try (JsonGenerator generator = newTomlMapper().createGenerator(w)) {
+ generator.writeStartObject();
+ generator.writeFieldName("a");
+ generator.writeRawValue("1");
+ generator.writeFieldName("b");
+ generator.writeRawValue("<<2>>", 2, 1);
+ generator.writeFieldName("c");
+ generator.writeRawValue("<<3>>".toCharArray(), 2, 1);
+ generator.writeFieldName("d");
+ generator.writeRawValue(new SerializedString("4"));
+ generator.writeFieldName("e");
+ generator.writeStartArray();
+ generator.writeRawValue("5");
+ generator.writeRawValue("6");
+ generator.writeEndArray();
+ generator.writeEndObject();
+ }
+ assertEquals("a = 1\nb = 2\nc = 3\nd = 4\ne = [5, 6]\n", w.toString());
+ assertThrows(StreamWriteException.class,
+ () -> newTomlMapper().createGenerator(new StringWriter()).writeRawValue("abc", 2, 5));
+ }
+
+ @Test
+ public void invalidRawRange() throws IOException {
+ StringWriter w = new StringWriter();
+ try (JsonGenerator generator = newTomlMapper().createGenerator(w)) {
+ assertThrows(StreamWriteException.class,
+ () -> generator.writeRaw("abc", 2, 5));
+ assertThrows(StreamWriteException.class,
+ () -> generator.writeRaw("abc".toCharArray(), 2, 5));
+ assertThrows(StreamWriteException.class,
+ () -> generator.writeRaw("abc".toCharArray(), -1, 1));
+ generator.writeRaw("abc", 1, 2);
+ generator.writeRaw("xyz".toCharArray(), 0, 1);
+ }
+ assertEquals("bcx", w.toString());
+ }
+
+ // `writeUTF8String()` used to call `writeValueEnd()` twice, producing
+ // an extra empty line after the value
+ @Test
+ public void utf8String() throws IOException {
+ StringWriter w = new StringWriter();
+ try (JsonGenerator generator = newTomlMapper().createGenerator(w)) {
+ generator.writeStartObject();
+ generator.writeFieldName("abc");
+ final byte[] utf8 = "<<x\"y>>".getBytes(StandardCharsets.UTF_8);
+ generator.writeUTF8String(utf8, 2, 3);
+ generator.writeFieldName("def");
+ generator.writeNumber(1);
+ generator.writeEndObject();
+ }
+ assertEquals("abc = 'x\"y'\ndef = 1\n", w.toString());
+ }
+
// `writeNumber(short)` used to call `writeValueEnd()` twice, producing
// an extra empty line after every short value
@Test
@@ -92,6 +298,61 @@ public class TomlGeneratorTest extends TomlMapperTestBase {
assertEquals("abc = 1.23\n", w.toString());
}
+ // [dataformats-text#696]: non-finite floats must be written as the TOML
+ // tokens `nan` / `inf` / `-inf` (not Java's `NaN` / `Infinity`) so the
+ // writer's own output can be parsed back.
+ @Test
+ public void nonFiniteDoubles() throws IOException {
+ assertEquals("abc = nan\n", _writeDouble(Double.NaN));
+ assertEquals("abc = inf\n", _writeDouble(Double.POSITIVE_INFINITY));
+ assertEquals("abc = -inf\n", _writeDouble(Double.NEGATIVE_INFINITY));
+ }
+
+ @Test
+ public void nonFiniteFloats() throws IOException {
+ assertEquals("abc = nan\n", _writeFloat(Float.NaN));
+ assertEquals("abc = inf\n", _writeFloat(Float.POSITIVE_INFINITY));
+ assertEquals("abc = -inf\n", _writeFloat(Float.NEGATIVE_INFINITY));
+ }
+
+ // Written non-finite values must round-trip through the same mapper.
+ @Test
+ public void nonFiniteRoundTrip() throws IOException {
+ TomlMapper mapper = newTomlMapper();
+ for (double d : new double[] {
+ Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY }) {
+ String toml = mapper.writeValueAsString(java.util.Collections.singletonMap("x", d));
+ JsonNode node = mapper.readTree(toml).get("x");
+ if (Double.isNaN(d)) {
+ assertTrue(Double.isNaN(node.doubleValue()), "expected NaN from: " + toml);
+ } else {
+ assertEquals(d, node.doubleValue(), 0.0, "round-trip failed for: " + toml);
+ }
+ }
+ }
+
+ private String _writeDouble(double d) throws IOException {
+ StringWriter w = new StringWriter();
+ try (JsonGenerator generator = newTomlMapper().createGenerator(w)) {
+ generator.writeStartObject();
+ generator.writeFieldName("abc");
+ generator.writeNumber(d);
+ generator.writeEndObject();
+ }
+ return w.toString();
+ }
+
+ private String _writeFloat(float f) throws IOException {
+ StringWriter w = new StringWriter();
+ try (JsonGenerator generator = newTomlMapper().createGenerator(w)) {
+ generator.writeStartObject();
+ generator.writeFieldName("abc");
+ generator.writeNumber(f);
+ generator.writeEndObject();
+ }
+ return w.toString();
+ }
+
@Test
public void stringNormal() throws IOException {
StringWriter w = new StringWriter();
=====================================
toml/src/test/java/com/fasterxml/jackson/dataformat/toml/TomlParserTest.java
=====================================
@@ -498,6 +498,49 @@ public class TomlParserTest extends TomlMapperTestBase {
);
}
+ // [dataformats-text#663]
+ @Test
+ public void integerLongBoundaries() throws Exception {
+ assertEquals(
+ JsonNodeFactory.instance.objectNode()
+ .put("max", Long.MAX_VALUE)
+ .put("min", Long.MIN_VALUE),
+ toml("max = 9223372036854775807\n" +
+ "min = -9223372036854775808")
+ );
+ }
+
+ // [dataformats-text#663]: 19-digit values within `long` range must not be truncated
+ @Test
+ public void integerLong19Digits() throws Exception {
+ assertEquals(
+ JsonNodeFactory.instance.objectNode()
+ .put("a", 1234567890123456789L)
+ .put("b", 1000000000000000000L)
+ .put("c", -1234567890123456789L)
+ .put("d", 1234567890123456789L)
+ .put("e", 123456789012345678L),
+ toml("a = 1234567890123456789\n" +
+ "b = 1000000000000000000\n" +
+ "c = -1234567890123456789\n" +
+ "d = 1_234_567_890_123_456_789\n" +
+ "e = 123456789012345678")
+ );
+ }
+
+ // [dataformats-text#663]: 19-digit values just outside `long` range must
+ // become `BigInteger`, not wrap around
+ @Test
+ public void integerJustOutsideLongRange() throws Exception {
+ assertEquals(
+ JsonNodeFactory.instance.objectNode()
+ .put("over", new BigInteger("9223372036854775808"))
+ .put("under", new BigInteger("-9223372036854775809")),
+ toml("over = 9223372036854775808\n" +
+ "under = -9223372036854775809")
+ );
+ }
+
@Test
public void floats() throws Exception {
ObjectNode json = json("{\"flt1\": 1.0, \"flt2\": 3.1415, \"flt3\": -0.01, \"flt4\": 5.0e22, \"flt5\": 1e06, \"flt6\": -2e-2, \"flt7\": 6.626e-34}");
=====================================
yaml/pom.xml
=====================================
@@ -9,7 +9,7 @@
<parent>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformats-text</artifactId>
- <version>2.22.4</version>
+ <version>2.23.0</version>
</parent>
<artifactId>jackson-dataformat-yaml</artifactId>
<packaging>jar</packaging>
=====================================
yaml/src/main/java/com/fasterxml/jackson/dataformat/yaml/UTF8Reader.java
=====================================
@@ -59,12 +59,13 @@ public final class UTF8Reader
/**
* Total read character count; used for error reporting purposes
*/
- int _charCount = 0;
+ private long _charCount = 0;
/**
- * Total read byte count; used for error reporting purposes
+ * Number of input bytes that precede {@code _inputBuffer[0]};
+ * used for error reporting purposes
*/
- int _byteCount = 0;
+ private long _byteCount;
/*
/**********************************************************************
@@ -102,6 +103,8 @@ public final class UTF8Reader
_inputEnd = ptr+len;
_autoClose = autoClose;
_bufferHolder = null;
+ // so that byte positions are relative to start of content, not of buffer
+ _byteCount = -ptr;
}
private static byte[][] _findBufferHolder()
@@ -165,6 +168,13 @@ public final class UTF8Reader
@Override
public int read(final char[] cbuf, final int start, int len) throws IOException
{
+ if (start < 0 || len <= 0 || len > cbuf.length - start) {
+ // Nothing to read? (must not write buffered surrogate, if any)
+ if (len == 0 && start >= 0 && start <= cbuf.length) {
+ return 0;
+ }
+ reportBounds(cbuf, start, len);
+ }
// Already EOF?
if (_inputBuffer == null) {
return -1;
@@ -188,16 +198,12 @@ public final class UTF8Reader
// we'll only require decoding of a single char
int left = (_inputEnd - _inputPtr);
- /* So; only need to load more if we can't provide at least
- * one more character. We need not do thorough check here,
- * but let's check the common cases here: either completely
- * empty buffer (left == 0), or one with less than max. byte
- * count for a single char, and starting of a multi-byte
- * encoding (this leaves possibility of a 2/3-byte char
- * that is still fully accessible... but that can be checked
- * by the load method)
- */
-
+ // So; only need to load more if we can't provide at least one more character.
+ // We need not do thorough check here, but let's check the common cases here:
+ // either completely empty buffer (left == 0), or one with less than max. byte
+ // count for a single char, and starting of a multi-byte encoding (this leaves
+ // possibility of a 2/3-byte char that is still fully accessible...
+ // but that can be checked by the load method)
if (left < 4) {
// Need to load more?
if (left < 1 || _inputBuffer[_inputPtr] < 0) {
@@ -210,11 +216,15 @@ public final class UTF8Reader
final byte[] buf = _inputBuffer;
int inPtr = _inputPtr;
final int inBufLen = _inputEnd;
+ // start of current multi-byte sequence, and whether it is invalid: details are
+ // only figured out if (and when) error is reported
+ int seqStart = 0;
+ boolean invalid = false;
main_loop:
while (outPtr < len) {
// At this point we have at least one byte available
- int c = (int) buf[inPtr++];
+ int c = buf[inPtr++];
// Let's first do the quickie loop for common case; 7-bit ASCII
if (c >= 0) { // ASCII? can probably loop, then
@@ -240,22 +250,21 @@ public final class UTF8Reader
}
int needed;
+ seqStart = inPtr - 1;
// Ok; if we end here, we got multi-byte combination
- if ((c & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF)
+ if ((c & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF), from 110xxxxx
c = (c & 0x1F);
needed = 1;
- } else if ((c & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF)
+ } else if ((c & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF), from 1110xxxx
c = (c & 0x0F);
needed = 2;
- } else if ((c & 0xF8) == 0xF0) {
- // 4 bytes; double-char BS, with surrogates and all...
- c = (c & 0x0F);
+ } else if ((c & 0xF8) == 0xF0) { // 4 bytes from 11110xxx (double-char w/ surrogates and all)
+ c = (c & 0x07);
needed = 3;
} else {
- reportInvalidInitial(c & 0xFF, outPtr-start);
- // never gets here...
- needed = 1;
+ invalid = true;
+ break main_loop;
}
/* Do we have enough bytes? If not, let's just push back the
* byte and leave, since we have already gotten at least one
@@ -263,35 +272,47 @@ public final class UTF8Reader
* input stream) when absolutely necessary.
*/
if ((inBufLen - inPtr) < needed) {
+ // ... unless bytes we do have already make the sequence invalid
+ if (hasInvalidMiddleByte(buf, inPtr, inBufLen)) {
+ invalid = true;
+ break main_loop;
+ }
--inPtr;
break main_loop;
}
- int d = (int) buf[inPtr++];
+ int d = buf[inPtr++];
if ((d & 0xC0) != 0x080) {
- reportInvalidOther(d & 0xFF, outPtr-start);
+ invalid = true;
+ break main_loop;
}
c = (c << 6) | (d & 0x3F);
if (needed > 1) { // needed == 1 means 2 bytes total
d = buf[inPtr++]; // 3rd byte
if ((d & 0xC0) != 0x080) {
- reportInvalidOther(d & 0xFF, outPtr-start);
+ invalid = true;
+ break main_loop;
}
c = (c << 6) | (d & 0x3F);
if (needed > 2) { // 4 bytes? (need surrogates)
d = buf[inPtr++];
if ((d & 0xC0) != 0x080) {
- reportInvalidOther(d & 0xFF, outPtr-start);
+ invalid = true;
+ break main_loop;
}
c = (c << 6) | (d & 0x3F);
+ // overlong, or beyond U+10FFFF?
+ if (c < 0x10000 || c > Character.MAX_CODE_POINT) {
+ invalid = true;
+ break main_loop;
+ }
/* Ugh. Need to mess with surrogates. Ok; let's inline them
* there, then, if there's room: if only room for one,
* need to save the surrogate for the rainy day...
*/
c -= 0x10000; // to normalize it starting with 0x0
cbuf[outPtr++] = (char) (0xD800 + (c >> 10));
- // hmmh. can this ever be 0? (not legal, at least?)
c = (0xDC00 | (c & 0x03FF));
// Room for second part?
@@ -300,17 +321,14 @@ public final class UTF8Reader
break main_loop;
}
// sure, let's fall back to normal processing:
+ } else if (c < 0x800 || (c >= 0xD800 && c <= 0xDFFF)) {
+ // overlong, or surrogate (illegal in UTF-8 as per [jackson-core#363])
+ invalid = true;
+ break main_loop;
}
- // Otherwise, should we check that 3-byte chars are
- // legal ones (should not expand to surrogates?
- // For now, let's not...
- /*
- else {
- if (c >= 0xD800 && c < 0xE000) {
- reportInvalid(c, outPtr-start, "(a surrogate character) ");
- }
- }
- */
+ } else if (c < 0x80) { // overlong
+ invalid = true;
+ break main_loop;
}
cbuf[outPtr++] = (char) c;
if (inPtr >= inBufLen) {
@@ -318,6 +336,17 @@ public final class UTF8Reader
}
}
+ if (invalid) {
+ // 25-Aug-2016, tatu: As per [dataformat-csv#132] defer error reporting if
+ // (but only if) some content has been decoded successfully: we then
+ // return that content, and next call starts from the invalid sequence
+ // and reports it.
+ if (outPtr == start) {
+ reportInvalidSequence(seqStart, inBufLen);
+ }
+ inPtr = seqStart;
+ }
+
_inputPtr = inPtr;
final int actualLen = outPtr - start;
_charCount += actualLen;
@@ -394,62 +423,21 @@ public final class UTF8Reader
/**********************************************************************
*/
- private void reportInvalidInitial(int mask, int offset) throws IOException
- {
- // input (byte) ptr has been advanced by one, by now:
- int bytePos = _byteCount + _inputPtr - 1;
- int charPos = _charCount + offset + 1;
-
- throw new CharConversionException("Invalid UTF-8 start byte 0x"+Integer.toHexString(mask)
- +" (at char #"+charPos+", byte #"+bytePos+")");
- }
-
- private void reportInvalidOther(int mask, int offset)
- throws IOException
- {
- int bytePos = _byteCount + _inputPtr - 1;
- int charPos = _charCount + offset;
-
- throw new CharConversionException("Invalid UTF-8 middle byte 0x"+Integer.toHexString(mask)
- +" (at char #"+charPos+", byte #"+bytePos+")");
- }
-
- private void reportUnexpectedEOF(int gotBytes, int needed)
- throws IOException
- {
- int bytePos = _byteCount + gotBytes;
- int charPos = _charCount;
-
- throw new CharConversionException("Unexpected EOF in the middle of a multi-byte char: got "
- +gotBytes+", needed "+needed +", at char #"+charPos+", byte #"+bytePos+")");
- }
-
- /*
- private void reportInvalid(int value, int offset, String msg) throws IOException
- {
- int bytePos = _byteCount + _inputPtr - 1;
- int charPos = _charCount + offset;
-
- throw new CharConversionException("Invalid UTF-8 character 0x"+Integer.toHexString(value)+msg
- +" at char #"+charPos+", byte #"+bytePos+")");
- }
- */
-
/**
* @param available Number of "unused" bytes in the input buffer
*
* @return True, if enough bytes were read to allow decoding of at least
- * one full character; false if EOF was encountered instead.
+ * one full character (or to report it invalid); false if EOF was
+ * encountered instead.
*/
private boolean loadMore(int available) throws IOException
{
- _byteCount += (_inputEnd - available);
-
if (available > 0) {
// Should we move bytes to the beginning of buffer?
if (_inputPtr > 0) {
// Can only do so if buffer mutable
if (!_inputBufferReadOnly) {
+ _byteCount += _inputPtr;
for (int i = 0; i < available; ++i) {
_inputBuffer[i] = _inputBuffer[_inputPtr+i];
}
@@ -458,6 +446,7 @@ public final class UTF8Reader
}
}
} else {
+ _byteCount += _inputEnd;
// Ok; here we can actually reasonably expect an EOF, so let's do a separate read right away:
int count = readBytes();
if (count < 1) {
@@ -497,19 +486,37 @@ public final class UTF8Reader
// if an EOF is hit, that'll be an error. But we need not do
// actual decoding here, just load enough bytes.
while ((_inputPtr + needed) > _inputEnd) {
+ // No point in waiting for (or failing on lack of) more bytes if the ones
+ // we have make sequence invalid: let caller report the actual problem
+ if (hasInvalidMiddleByte(_inputBuffer, _inputPtr+1, _inputEnd)) {
+ return true;
+ }
int count = readBytesAt(_inputEnd);
if (count < 1) {
if (count < 0) { // -1, EOF... no good!
- freeBuffers();
- reportUnexpectedEOF(_inputEnd - _inputPtr, needed);
+ // but report sequence as invalid if possible, not as truncated.
+ // Buffers are not freed (left to close()): so that following
+ // reads fail the same way, instead of returning EOF
+ reportInvalidSequence(_inputPtr, _inputEnd);
+ } else {
+ // 0 count is no good; let's err out
+ reportStrangeStream();
}
- // 0 count is no good; let's err out
- reportStrangeStream();
}
}
return true;
}
+ // Whether any byte in buf[start, end) is not a valid continuation byte (10xxxxxx)
+ private static boolean hasInvalidMiddleByte(byte[] buf, int start, int end) {
+ for (int i = start; i < end; ++i) {
+ if ((buf[i] & 0xC0) != 0x080) {
+ return true;
+ }
+ }
+ return false;
+ }
+
protected void reportBounds(char[] cbuf, int start, int len) throws IOException {
throw new ArrayIndexOutOfBoundsException("read(buf,"+start+","+len+"), cbuf["+cbuf.length+"]");
}
@@ -517,5 +524,105 @@ public final class UTF8Reader
protected void reportStrangeStream() throws IOException {
throw new IOException("Strange I/O stream, returned 0 bytes on read");
}
-}
+ private final static String NOT_UTF8 = ": check content encoding, does not look like UTF-8";
+
+ private static String invalidMiddleByte(int b) {
+ return "Invalid UTF-8 middle byte 0x"+Integer.toHexString(b & 0xFF);
+ }
+
+ // Smallest code point that needs given number of continuation bytes
+ private final static int[] MIN_CODE_POINTS = { 0, 0x80, 0x800, 0x10000 };
+
+ /**
+ * Method called to report invalid (or, at end of input, truncated) multi-byte
+ * sequence that starts at {@code _inputBuffer[seqStart]}, with bytes available up to
+ * (but not including) {@code end}. Kept separate from the decode loop which only
+ * notes that the sequence is invalid: as errors are rare, the specific problem is
+ * only figured out here.
+ *<p>
+ * For truncated sequences, the bytes available may already prove sequence
+ * invalid (start byte like {@code 0xC0} that can only be used for overlong
+ * encodings, for example); if not, sequence is reported as truncated.
+ */
+ private void reportInvalidSequence(int seqStart, int end) throws IOException
+ {
+ final byte[] buf = _inputBuffer;
+ int c = buf[seqStart] & 0xFF;
+ int needed;
+ if ((c & 0xE0) == 0xC0) {
+ c &= 0x1F;
+ needed = 1;
+ } else if ((c & 0xF0) == 0xE0) {
+ c &= 0x0F;
+ needed = 2;
+ } else if ((c & 0xF8) == 0xF0) {
+ c &= 0x07;
+ needed = 3;
+ } else {
+ reportInvalid("Invalid UTF-8 start byte 0x"+Integer.toHexString(c), seqStart, true);
+ return;
+ }
+ final int avail = Math.min(needed, end - seqStart - 1);
+ for (int i = seqStart + 1, last = seqStart + avail; i <= last; ++i) {
+ int d = buf[i];
+ if ((d & 0xC0) != 0x080) {
+ reportInvalid(invalidMiddleByte(d), i, true);
+ }
+ c = (c << 6) | (d & 0x3F);
+ }
+ // Range of values sequence may decode to (single value if complete)
+ final int shift = 6 * (needed - avail);
+ final int min = c << shift;
+ final int max = min | ((1 << shift) - 1);
+ String reason = null;
+ if (max < MIN_CODE_POINTS[needed]) {
+ reason = "overlong encoding";
+ } else if (min > Character.MAX_CODE_POINT || (min >= 0xD800 && max <= 0xDFFF)) {
+ // as per [jackson-core#363], surrogates are illegal in UTF-8
+ reason = "not a valid Unicode scalar value";
+ }
+ if (reason != null) {
+ StringBuilder sb = new StringBuilder("Invalid UTF-8 ");
+ if (avail == needed) {
+ sb.append("character 0x").append(Integer.toHexString(c));
+ } else {
+ sb.append("sequence");
+ for (int i = seqStart, last = seqStart + avail; i <= last; ++i) {
+ sb.append(" 0x").append(Integer.toHexString(buf[i] & 0xFF));
+ }
+ }
+ sb.append(" (").append(reason).append(')');
+ reportInvalid(sb.toString(), seqStart, false);
+ }
+ if (avail < needed) { // only called for truncated sequences at end of input
+ reportUnexpectedEOF(avail + 1, needed + 1, seqStart);
+ }
+ // should never get here; but if we do, fail same way as for invalid content
+ throw new CharConversionException("Internal error: valid UTF-8 sequence reported as invalid"
+ +_position(seqStart));
+ }
+
+ // Errors are only reported before anything is decoded by the current read() call
+ // (see [dataformat-csv#132] above), so the offending char is the one after
+ // `_charCount`. `byteIndex` is the index in `_inputBuffer` of the offending byte:
+ // `_inputPtr` is not updated until read() returns, so callers pass it in.
+ private void reportInvalid(String msg, int byteIndex, boolean notUtf8)
+ throws IOException
+ {
+ throw new CharConversionException(msg+_position(byteIndex)
+ +(notUtf8 ? NOT_UTF8 : ""));
+ }
+
+ private void reportUnexpectedEOF(int gotBytes, int needed, int byteIndex) throws IOException
+ {
+ throw new CharConversionException(String.format(
+ "Unexpected EOF in the middle of a multi-byte UTF-8 character: got %d, needed %d%s",
+ gotBytes, needed, _position(byteIndex)));
+ }
+
+ // 1-based positions, relative to start of content
+ private String _position(int byteIndex) {
+ return " (at char #"+(_charCount + 1)+", byte #"+(_byteCount + byteIndex + 1)+")";
+ }
+}
=====================================
yaml/src/test/java/com/fasterxml/jackson/dataformat/yaml/FormatDetectionTest.java
=====================================
@@ -1,5 +1,7 @@
package com.fasterxml.jackson.dataformat.yaml;
+import org.junit.jupiter.api.Test;
+
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.format.*;
@@ -12,6 +14,7 @@ public class FormatDetectionTest extends ModuleTestBase
* One nifty thing YAML has is the "---" start-doc indicator, which
* makes it possible to auto-detect format...
*/
+ @Test
public void testFormatDetection() throws Exception
{
YAMLFactory yamlF = new YAMLFactory();
=====================================
yaml/src/test/java/com/fasterxml/jackson/dataformat/yaml/deser/InvalidUTF8Encoding764Test.java
=====================================
@@ -0,0 +1,361 @@
+package com.fasterxml.jackson.dataformat.yaml.deser;
+
+import java.io.*;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Collections;
+
+import org.junit.jupiter.api.Test;
+
+import com.fasterxml.jackson.databind.MappingIterator;
+import com.fasterxml.jackson.dataformat.yaml.ModuleTestBase;
+import com.fasterxml.jackson.dataformat.yaml.UTF8Reader;
+import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+// [dataformats-text#764]: invalid UTF-8 (overlong encodings, surrogates,
+// values beyond U+10FFFF) must be rejected, with correct error positions
+public class InvalidUTF8Encoding764Test extends ModuleTestBase
+{
+ private final YAMLMapper MAPPER = new YAMLMapper();
+
+ // valid content preceding invalid bytes when testing via parser
+ private final static String PARSER_PREFIX = "a: b\nc: d";
+
+ private final static String NOT_UTF8 = ": check content encoding, does not look like UTF-8";
+
+ @Test
+ public void testOverlongEncodings() throws Exception
+ {
+ // all encode '/' (0x2F) in more bytes than needed
+ assertInvalid("Invalid UTF-8 character 0x2f (overlong encoding)", 0xC0, 0xAF);
+ assertInvalid("Invalid UTF-8 character 0x2f (overlong encoding)", 0xE0, 0x80, 0xAF);
+ assertInvalid("Invalid UTF-8 character 0x2f (overlong encoding)", 0xF0, 0x80, 0x80, 0xAF);
+ // and largest values that need fewer bytes
+ assertInvalid("Invalid UTF-8 character 0x7f (overlong encoding)", 0xC1, 0xBF);
+ assertInvalid("Invalid UTF-8 character 0x7ff (overlong encoding)", 0xE0, 0x9F, 0xBF);
+ assertInvalid("Invalid UTF-8 character 0xffff (overlong encoding)", 0xF0, 0x8F, 0xBF, 0xBF);
+ }
+
+ @Test
+ public void testInvalidScalarValues() throws Exception
+ {
+ // surrogates, as per [jackson-core#363]
+ assertInvalid("Invalid UTF-8 character 0xd800 (not a valid Unicode scalar value)",
+ 0xED, 0xA0, 0x80);
+ assertInvalid("Invalid UTF-8 character 0xdfff (not a valid Unicode scalar value)",
+ 0xED, 0xBF, 0xBF);
+ // beyond U+10FFFF
+ assertInvalid("Invalid UTF-8 character 0x110000 (not a valid Unicode scalar value)",
+ 0xF4, 0x90, 0x80, 0x80);
+ assertInvalid("Invalid UTF-8 character 0x140000 (not a valid Unicode scalar value)",
+ 0xF5, 0x80, 0x80, 0x80);
+ }
+
+ @Test
+ public void testValidBoundaries() throws Exception
+ {
+ for (int cp : new int[] { 0x7F, 0x80, 0x7FF, 0x800, 0xD7FF, 0xE000, 0xFFFF,
+ 0x10000, Character.MAX_CODE_POINT }) {
+ String value = new String(Character.toChars(cp));
+ byte[] utf8 = value.getBytes(StandardCharsets.UTF_8);
+ try (UTF8Reader r = new UTF8Reader(utf8, 0, utf8.length, true)) {
+ char[] buf = new char[4];
+ int count = r.read(buf, 0, buf.length);
+ assertEquals(value, new String(buf, 0, count), "U+" + Integer.toHexString(cp));
+ assertEquals(-1, r.read(buf, 0, buf.length));
+ }
+ }
+ }
+
+ // keys go through the same decoding as values
+ @Test
+ public void testOverlongInKey() throws Exception
+ {
+ byte[] doc = bytes("a", 0xC0, 0xAF, 'b', ':', ' ', 'v', '\n');
+ String msg = parseFailure(doc);
+ assertTrue(msg.contains("Invalid UTF-8 character 0x2f (overlong encoding) (at char #2, byte #2)"), msg);
+ }
+
+ // [dataformat-csv#132]: content decoded before invalid sequence is returned first
+ @Test
+ public void testErrorDeferredUntilNextRead() throws Exception
+ {
+ byte[] doc = bytes("abé", 0xC0, 0xAF);
+ try (UTF8Reader r = new UTF8Reader(doc, 0, doc.length, true)) {
+ char[] buf = new char[10];
+ assertEquals(3, r.read(buf, 0, buf.length));
+ assertEquals("abé", new String(buf, 0, 3));
+ CharConversionException e = assertThrows(CharConversionException.class,
+ () -> r.read(buf, 0, buf.length));
+ assertEquals("Invalid UTF-8 character 0x2f (overlong encoding) (at char #4, byte #5)",
+ e.getMessage());
+ }
+ }
+
+ // Invalid content in a later document must not prevent reading earlier ones
+ @Test
+ public void testErrorDeferredToLaterDocument() throws Exception
+ {
+ byte[] doc = bytes("a: 1\n---\nb: ", 0xC0, 0xAF, '\n');
+ try (MappingIterator<Object> it
+ = MAPPER.readerFor(Object.class).readValues(doc)) {
+ assertEquals(Collections.singletonMap("a", 1), it.nextValue());
+ Exception e = assertThrows(Exception.class, it::nextValue);
+ assertTrue(fullMessage(e).contains("Invalid UTF-8 character 0x2f (overlong encoding)"),
+ fullMessage(e));
+ }
+ }
+
+ @Test
+ public void testErrorPositionWithOffset() throws Exception
+ {
+ byte[] doc = bytes("abé", 0xE0, 0x80, 0xAF);
+ byte[] padded = new byte[doc.length + 7];
+ Arrays.fill(padded, (byte) 'x');
+ System.arraycopy(doc, 0, padded, 3, doc.length);
+ assertEquals("Invalid UTF-8 character 0x2f (overlong encoding) (at char #4, byte #5)",
+ readFailure(padded, 3, doc.length));
+ }
+
+ @Test
+ public void testErrorPositionStartAndMiddleByte() throws Exception
+ {
+ byte[] doc = bytes("é", 0xFF);
+ assertEquals("Invalid UTF-8 start byte 0xff (at char #2, byte #3)" + NOT_UTF8,
+ readFailure(doc, 0, doc.length));
+ doc = bytes("abc", 0xE2, 0x82, 'A');
+ assertEquals("Invalid UTF-8 middle byte 0x41 (at char #4, byte #6)" + NOT_UTF8,
+ readFailure(doc, 0, doc.length));
+ }
+
+ @Test
+ public void testErrorPositionFromParser() throws Exception
+ {
+ // long enough to need several buffer loads before the bad bytes
+ char[] filler = new char[20000];
+ Arrays.fill(filler, 'x');
+ final String prefix = "a: " + new String(filler) + "\nb: é";
+ byte[] doc = bytes(prefix, 0xF0, 0x80, 0x80, 0xAF, '\n');
+ final int bytesBefore = prefix.getBytes(StandardCharsets.UTF_8).length;
+ final String expected = "Invalid UTF-8 character 0x2f (overlong encoding) (at char #"
+ + (prefix.length() + 1) + ", byte #" + (bytesBefore + 1) + ")";
+
+ assertParseFailure(expected, doc);
+ }
+
+ // Error must be reported again by following reads (not EOF), regardless of input source
+ @Test
+ public void testErrorRepeatedOnNextRead() throws Exception
+ {
+ // first truncated sequence (reported when trying to load more), then complete one
+ assertErrorRepeated(bytes("abc", 0xC0),
+ "Invalid UTF-8 sequence 0xc0 (overlong encoding) (at char #4, byte #4)");
+ assertErrorRepeated(bytes("abc", 0xC0, 0xAF),
+ "Invalid UTF-8 character 0x2f (overlong encoding) (at char #4, byte #4)");
+ assertErrorRepeated(bytes("abc", 0xE2, 0x82),
+ "Unexpected EOF in the middle of a multi-byte UTF-8 character: got 2, needed 3"
+ + " (at char #4, byte #4)");
+ }
+
+ private void assertErrorRepeated(byte[] doc, String expected) throws Exception
+ {
+ Reader[] readers = new Reader[] {
+ new UTF8Reader(doc, 0, doc.length, true),
+ new UTF8Reader(new ByteArrayInputStream(doc), true),
+ new UTF8Reader(new OneByteInputStream(doc), true)
+ };
+ for (Reader reader : readers) {
+ try (Reader r = reader) {
+ // content before invalid sequence first (one char at a time, for OneByteInputStream)
+ char[] buf = new char[10];
+ StringBuilder sb = new StringBuilder();
+ while (sb.length() < 3) {
+ int count = r.read(buf, 0, 3 - sb.length());
+ assertTrue(count > 0);
+ sb.append(buf, 0, count);
+ }
+ assertEquals("abc", sb.toString());
+ for (int i = 0; i < 2; ++i) {
+ CharConversionException e = assertThrows(CharConversionException.class,
+ () -> r.read(buf, 0, buf.length));
+ assertEquals(expected, e.getMessage());
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testErrorPositionUnexpectedEOF() throws Exception
+ {
+ byte[] doc = bytes("a: é", 0xE2, 0x82);
+ String msg = parseFailure(new OneByteInputStream(doc));
+ assertTrue(msg.contains("got 2, needed 3 (at char #5, byte #6)"), msg);
+ }
+
+ // Truncated sequence at end of input with an invalid middle byte: report the
+ // invalid byte, not EOF
+ @Test
+ public void testInvalidMiddleByteBeforeEOF() throws Exception
+ {
+ assertInvalidMiddleByte(0x41, 2, 0xE2, 'A');
+ assertInvalidMiddleByte(0x41, 2, 0xF0, 'A');
+ assertInvalidMiddleByte(0x41, 3, 0xF0, 0x9F, 'A');
+ assertInvalidMiddleByte(0xc3, 2, 0xE2, 0xC3);
+ }
+
+ // Truncated sequence at end of input that can not be valid whatever follows:
+ // report it as invalid, not EOF
+ @Test
+ public void testInvalidTruncatedSequenceBeforeEOF() throws Exception
+ {
+ assertTruncated("Invalid UTF-8 sequence 0xc0 (overlong encoding)", 0xC0);
+ assertTruncated("Invalid UTF-8 sequence 0xc1 (overlong encoding)", 0xC1);
+ assertTruncated("Invalid UTF-8 sequence 0xe0 0x9f (overlong encoding)", 0xE0, 0x9F);
+ assertTruncated("Invalid UTF-8 sequence 0xf0 0x8f (overlong encoding)", 0xF0, 0x8F);
+ assertTruncated("Invalid UTF-8 sequence 0xf0 0x8f 0xbf (overlong encoding)",
+ 0xF0, 0x8F, 0xBF);
+ assertTruncated("Invalid UTF-8 sequence 0xed 0xa0 (not a valid Unicode scalar value)",
+ 0xED, 0xA0);
+ assertTruncated("Invalid UTF-8 sequence 0xf4 0x90 (not a valid Unicode scalar value)",
+ 0xF4, 0x90);
+ assertTruncated("Invalid UTF-8 sequence 0xf5 (not a valid Unicode scalar value)", 0xF5);
+ }
+
+ // ... but if it could still be valid, report as truncated
+ @Test
+ public void testValidTruncatedSequenceBeforeEOF() throws Exception
+ {
+ assertTruncated("Unexpected EOF in the middle of a multi-byte UTF-8 character: got 1, needed 2",
+ 0xC2);
+ assertTruncated("Unexpected EOF in the middle of a multi-byte UTF-8 character: got 1, needed 3",
+ 0xED);
+ assertTruncated("Unexpected EOF in the middle of a multi-byte UTF-8 character: got 2, needed 3",
+ 0xED, 0x9F);
+ assertTruncated("Unexpected EOF in the middle of a multi-byte UTF-8 character: got 2, needed 4",
+ 0xF0, 0x90);
+ assertTruncated("Unexpected EOF in the middle of a multi-byte UTF-8 character: got 3, needed 4",
+ 0xF4, 0x8F, 0xBF);
+ }
+
+ @Test
+ public void testReadBounds() throws Exception
+ {
+ // 4-byte char into 1-char buffer, so that low surrogate is pending
+ byte[] doc = bytes("", 0xF0, 0x9F, 0x98, 0x80);
+ try (UTF8Reader r = new UTF8Reader(doc, 0, doc.length, true)) {
+ char[] buf = new char[2];
+ assertEquals(1, r.read(buf, 0, 1));
+ assertEquals('\uD83D', buf[0]);
+ // zero-length reads must not consume (or write) the pending surrogate
+ assertEquals(0, r.read(buf, buf.length, 0));
+ assertEquals(0, r.read(buf, 0, 0));
+ assertThrows(IndexOutOfBoundsException.class, () -> r.read(buf, 1, 2));
+ assertThrows(IndexOutOfBoundsException.class, () -> r.read(buf, -1, 1));
+ assertEquals(1, r.read(buf, 1, 1));
+ assertEquals('\uDE00', buf[1]);
+ assertEquals(-1, r.read(buf, 0, buf.length));
+ }
+ // and zero-length read does not block on (or read from) stream
+ try (UTF8Reader r = new UTF8Reader(new ByteArrayInputStream(doc), true)) {
+ assertEquals(0, r.read(new char[2], 0, 0));
+ }
+ }
+
+ // Verifies that truncated sequence at end of input is reported with expected
+ // `error` and position (that of its first byte)
+ private void assertTruncated(String error, int... badBytes) throws Exception
+ {
+ byte[] doc = bytes("abc", badBytes);
+ assertEquals(error + " (at char #4, byte #4)", readFailure(doc, 0, doc.length));
+
+ doc = bytes(PARSER_PREFIX, badBytes);
+ final int pos = PARSER_PREFIX.length() + 1;
+ assertParseFailure(error + " (at char #" + pos + ", byte #" + pos + ")", doc);
+ }
+
+ private void assertInvalidMiddleByte(int badByte, int badByteIndex, int... badBytes)
+ throws Exception
+ {
+ final String error = "Invalid UTF-8 middle byte 0x" + Integer.toHexString(badByte);
+
+ byte[] doc = bytes("abc", badBytes);
+ assertEquals(error + " (at char #4, byte #" + (3 + badByteIndex) + ")" + NOT_UTF8,
+ readFailure(doc, 0, doc.length));
+
+ doc = bytes(PARSER_PREFIX, badBytes);
+ assertParseFailure(error + " (at char #" + (PARSER_PREFIX.length() + 1)
+ + ", byte #" + (PARSER_PREFIX.length() + badByteIndex) + ")" + NOT_UTF8, doc);
+ }
+
+ // Verifies that invalid sequence is reported with expected `error` and position,
+ // both as the only content and after valid content (via parser)
+ private void assertInvalid(String error, int... badBytes) throws Exception
+ {
+ byte[] doc = bytes("", badBytes);
+ assertEquals(error + " (at char #1, byte #1)", readFailure(doc, 0, doc.length));
+
+ doc = bytes(PARSER_PREFIX, badBytes);
+ final int pos = PARSER_PREFIX.length() + 1;
+ assertParseFailure(error + " (at char #" + pos + ", byte #" + pos + ")", doc);
+ }
+
+ // Verifies parse failure via byte[], InputStream and (so that partial sequences
+ // get shifted in the buffer) one byte at a time
+ private void assertParseFailure(String expected, byte[] doc)
+ {
+ String msg = parseFailure(doc);
+ assertTrue(msg.contains(expected), msg);
+ msg = parseFailure(new ByteArrayInputStream(doc));
+ assertTrue(msg.contains(expected), msg);
+ msg = parseFailure(new OneByteInputStream(doc));
+ assertTrue(msg.contains(expected), msg);
+ }
+
+ private static byte[] bytes(String prefix, int... suffix) {
+ byte[] start = prefix.getBytes(StandardCharsets.UTF_8);
+ byte[] result = Arrays.copyOf(start, start.length + suffix.length);
+ for (int i = 0; i < suffix.length; ++i) {
+ result[start.length + i] = (byte) suffix[i];
+ }
+ return result;
+ }
+
+ private static String readFailure(byte[] buf, int offset, int len) throws IOException {
+ try (UTF8Reader r = new UTF8Reader(buf, offset, len, true)) {
+ // content before invalid sequence is returned first, error by next read()
+ return assertThrows(CharConversionException.class, () -> {
+ char[] chars = new char[100];
+ while (r.read(chars, 0, chars.length) >= 0) { }
+ }).getMessage();
+ }
+ }
+
+ private String parseFailure(byte[] doc) {
+ return fullMessage(assertThrows(IOException.class, () -> MAPPER.readTree(doc)));
+ }
+
+ private String parseFailure(InputStream in) {
+ return fullMessage(assertThrows(IOException.class, () -> MAPPER.readTree(in)));
+ }
+
+ private static String fullMessage(Throwable t) {
+ StringBuilder sb = new StringBuilder();
+ for (; t != null; t = t.getCause()) {
+ sb.append(t.getMessage()).append('\n');
+ }
+ return sb.toString();
+ }
+
+ static class OneByteInputStream extends ByteArrayInputStream {
+ OneByteInputStream(byte[] data) {
+ super(data);
+ }
+
+ @Override
+ public synchronized int read(byte[] b, int off, int len) {
+ return super.read(b, off, Math.min(len, 1));
+ }
+ }
+}
=====================================
yaml/src/test/java/com/fasterxml/jackson/dataformat/yaml/fuzz/FuzzYAMLReadTest.java
=====================================
@@ -30,7 +30,7 @@ public class FuzzYAMLReadTest extends ModuleTestBase
YAML_MAPPER.readTree(INPUT);
fail("Should not pass");
} catch (JacksonException e) {
- verifyException(e, "Unexpected EOF in the middle of a multi-byte char");
+ verifyException(e, "Unexpected EOF in the middle of a multi-byte UTF-8 character");
verifyException(e, "got 1, needed 2");
}
}
=====================================
yaml/src/test/java/com/fasterxml/jackson/dataformat/yaml/misc/PolymorphicDeductionTest.java
=====================================
@@ -1,5 +1,7 @@
package com.fasterxml.jackson.dataformat.yaml.misc;
+import org.junit.jupiter.api.Test;
+
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.MapperFeature;
@@ -57,6 +59,7 @@ public class PolymorphicDeductionTest extends ModuleTestBase
private final ObjectMapper MAPPER = newObjectMapper();
+ @Test
public void testSimpleInference() throws Exception
{
Cat cat = MAPPER.readValue(LIVE_CAT_DOC, Cat.class);
@@ -72,11 +75,13 @@ public class PolymorphicDeductionTest extends ModuleTestBase
assertEquals("entropy", ((DeadCat)cat).causeOfDeath);
}
+ @Test
public void testSimpleInferenceOfEmptySubtypeDoesntMatchNull() throws Exception {
Feline feline = MAPPER.readValue("null", Feline.class);
assertNull(feline);
}
+ @Test
public void testCaseInsensitiveInference() throws Exception
{
Cat cat = mapperBuilder()
@@ -90,6 +95,7 @@ public class PolymorphicDeductionTest extends ModuleTestBase
}
// [dataformats-text#404]:
+ @Test
public void testSerializationOfInferred() throws Exception
{
assertEquals("name: \"Grizabella\"",
View it on GitLab: https://salsa.debian.org/java-team/jackson-dataformats-text/-/compare/30ce6161f172df8ef010aa93fe1a830e1e004d98...3ae8e131d30cba883c8c0c77bdc6ab64340f1a63
--
View it on GitLab: https://salsa.debian.org/java-team/jackson-dataformats-text/-/compare/30ce6161f172df8ef010aa93fe1a830e1e004d98...3ae8e131d30cba883c8c0c77bdc6ab64340f1a63
You're receiving this email because of your account on salsa.debian.org. Manage all notifications: https://salsa.debian.org/-/profile/notifications | Help: https://salsa.debian.org/help
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://alioth-lists.debian.net/pipermail/pkg-java-commits/attachments/20261109/c132786f/attachment.htm>
More information about the pkg-java-commits
mailing list