ppkarwasz commented on code in PR #4073:
URL: https://github.com/apache/logging-log4j2/pull/4073#discussion_r2983913920
##########
log4j-core/src/main/java/org/apache/logging/log4j/core/layout/Rfc5424Layout.java:
##########
@@ -579,14 +581,70 @@ private void appendMap(
if (prefix != null) {
sb.append(prefix);
}
- final String safeKey =
escapeNewlines(escapeSDParams(entry.getKey()), escapeNewLine);
- final String safeValue =
escapeNewlines(escapeSDParams(entry.getValue()), escapeNewLine);
+ // No need to escape new lines, since parameter names cannot
contain them.
+ final String safeKey = sanitizeParamName(entry.getKey());
+ final String safeValue =
escapeNewlines(escapeParamValue(entry.getValue()), escapeNewLine);
StringBuilders.appendKeyDqValue(sb, safeKey, safeValue);
}
}
}
- private String escapeSDParams(final String value) {
+ /**
+ * Sanitizes an RFC 5424 {@code PARAM-NAME}
+ *
+ * <p>Invalid characters are replaced with {@code '?'} and the result is
truncated to
+ * {@value #SD_PARAM_NAME_MAX_LENGTH}.</p>
+ *
+ * @param key the original parameter name
+ * @return a sanitized parameter name compliant with RFC 5424
+ */
+ private String sanitizeParamName(final String key) {
+ final int length = key.length();
+ if (length == 0) {
+ return "?";
+ }
+ if (length > SD_PARAM_NAME_MAX_LENGTH) {
+ return sanitizeParamNameSlowPath(key);
+ }
+ for (int i = 0; i < length; i++) {
+ if (!isParamNameCharacterValid(key.charAt(i))) {
+ return sanitizeParamNameSlowPath(key);
+ }
+ }
+ return key;
+ }
+
+ private String sanitizeParamNameSlowPath(final String key) {
+ final StringBuilder sb = new StringBuilder();
+ final int maxLength = Math.min(key.length(), SD_PARAM_NAME_MAX_LENGTH);
+ for (int i = 0; i < maxLength; i++) {
+ final char c = key.charAt(i);
+ sb.append(isParamNameCharacterValid(c) ? c : '?');
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Checks whether a character is allowed in an RFC 5424 {@code PARAM-NAME}.
+ *
+ * <p>Valid characters are printable US-ASCII characters
+ * ({@code 0x20-0x7E}) excluding:
+ *
+ * <ul>
+ * <li>{@code '='} – parameter delimiter</li>
+ * <li>{@code ' '} – not permitted in SD-NAME</li>
+ * <li>{@code ']'} – structured data terminator</li>
+ * <li>{@code '"'} – quoting delimiter</li>
+ * </ul>
+ *
+ * @param c the character to test
+ * @return {@code true} if the character is allowed in an {@code SD-NAME}
+ */
+ private static boolean isParamNameCharacterValid(final char c) {
+ return c >= 32 && c <= 126 && c != '=' && c != ' ' && c != ']' && c !=
'"';
Review Comment:
Added in
https://github.com/apache/logging-log4j2/pull/4073/commits/a0e7a201064c68b6ffc0b7bd887c0f7f786b6e13
Thanks! :100:
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]