|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. Licensed under the Elastic License |
| 4 | + * 2.0; you may not use this file except in compliance with the Elastic License |
| 5 | + * 2.0. |
| 6 | + */ |
| 7 | + |
| 8 | +package org.elasticsearch.xpack.sql.proto.xcontent; |
| 9 | + |
| 10 | +import java.util.Collections; |
| 11 | +import java.util.HashMap; |
| 12 | +import java.util.Locale; |
| 13 | +import java.util.Map; |
| 14 | +import java.util.regex.Pattern; |
| 15 | +import java.util.stream.Collectors; |
| 16 | + |
| 17 | +/** |
| 18 | + * NB: Light-clone from XContent library to keep JDBC driver independent. |
| 19 | + * |
| 20 | + * A raw result of parsing media types from Accept or Content-Type headers. |
| 21 | + * It follow parsing and validates as per rules defined in https://tools.ietf.org/html/rfc7231#section-3.1.1.1 |
| 22 | + * Can be resolved to <code>MediaType</code> |
| 23 | + * @see MediaType |
| 24 | + * @see MediaTypeRegistry |
| 25 | + */ |
| 26 | +public class ParsedMediaType { |
| 27 | + private final String originalHeaderValue; |
| 28 | + private final String type; |
| 29 | + private final String subType; |
| 30 | + private final Map<String, String> parameters; |
| 31 | + // tchar pattern as defined by RFC7230 section 3.2.6 |
| 32 | + private static final Pattern TCHAR_PATTERN = Pattern.compile("[a-zA-z0-9!#$%&'*+\\-.\\^_`|~]+"); |
| 33 | + |
| 34 | + private ParsedMediaType(String originalHeaderValue, String type, String subType, Map<String, String> parameters) { |
| 35 | + this.originalHeaderValue = originalHeaderValue; |
| 36 | + this.type = type; |
| 37 | + this.subType = subType; |
| 38 | + this.parameters = Collections.unmodifiableMap(parameters); |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * The parsed mime type without the associated parameters. Will always return lowercase. |
| 43 | + */ |
| 44 | + public String mediaTypeWithoutParameters() { |
| 45 | + return type + "/" + subType; |
| 46 | + } |
| 47 | + |
| 48 | + public Map<String, String> getParameters() { |
| 49 | + return parameters; |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Parses a header value into it's parts. |
| 54 | + * follows https://tools.ietf.org/html/rfc7231#section-3.1.1.1 |
| 55 | + * but allows only single media type. Media ranges will be ignored (treated as not provided) |
| 56 | + * Note: parsing can return null, but it will throw exceptions once https://github.com/elastic/elasticsearch/issues/63080 is done |
| 57 | + * TODO Do not rely on nulls |
| 58 | + * |
| 59 | + * @return a {@link ParsedMediaType} if the header could be parsed. |
| 60 | + * @throws IllegalArgumentException if the header is malformed |
| 61 | + */ |
| 62 | + public static ParsedMediaType parseMediaType(String headerValue) { |
| 63 | + if (headerValue != null) { |
| 64 | + if (isMediaRange(headerValue) || "*/*".equals(headerValue)) { |
| 65 | + return null; |
| 66 | + } |
| 67 | + final String[] elements = headerValue.toLowerCase(Locale.ROOT).split("[\\s\\t]*;"); |
| 68 | + |
| 69 | + final String[] splitMediaType = elements[0].split("/"); |
| 70 | + if ((splitMediaType.length == 2 |
| 71 | + && TCHAR_PATTERN.matcher(splitMediaType[0].trim()).matches() |
| 72 | + && TCHAR_PATTERN.matcher(splitMediaType[1].trim()).matches()) == false) { |
| 73 | + throw new IllegalArgumentException("invalid media-type [" + headerValue + "]"); |
| 74 | + } |
| 75 | + if (elements.length == 1) { |
| 76 | + return new ParsedMediaType(headerValue, splitMediaType[0].trim(), splitMediaType[1].trim(), new HashMap<>()); |
| 77 | + } else { |
| 78 | + Map<String, String> parameters = new HashMap<>(); |
| 79 | + for (int i = 1; i < elements.length; i++) { |
| 80 | + String paramsAsString = elements[i].trim(); |
| 81 | + if (paramsAsString.isEmpty()) { |
| 82 | + continue; |
| 83 | + } |
| 84 | + // spaces are allowed between parameters, but not between '=' sign |
| 85 | + String[] keyValueParam = paramsAsString.split("="); |
| 86 | + if (keyValueParam.length != 2 || hasTrailingSpace(keyValueParam[0]) || hasLeadingSpace(keyValueParam[1])) { |
| 87 | + throw new IllegalArgumentException("invalid parameters for header [" + headerValue + "]"); |
| 88 | + } |
| 89 | + String parameterName = keyValueParam[0].toLowerCase(Locale.ROOT).trim(); |
| 90 | + String parameterValue = keyValueParam[1].toLowerCase(Locale.ROOT).trim(); |
| 91 | + parameters.put(parameterName, parameterValue); |
| 92 | + } |
| 93 | + return new ParsedMediaType( |
| 94 | + headerValue, |
| 95 | + splitMediaType[0].trim().toLowerCase(Locale.ROOT), |
| 96 | + splitMediaType[1].trim().toLowerCase(Locale.ROOT), |
| 97 | + parameters |
| 98 | + ); |
| 99 | + } |
| 100 | + } |
| 101 | + return null; |
| 102 | + } |
| 103 | + |
| 104 | + // simplistic check for media ranges. do not validate if this is a correct header |
| 105 | + private static boolean isMediaRange(String headerValue) { |
| 106 | + return headerValue.contains(","); |
| 107 | + } |
| 108 | + |
| 109 | + private static boolean hasTrailingSpace(String s) { |
| 110 | + return s.length() == 0 || Character.isWhitespace(s.charAt(s.length() - 1)); |
| 111 | + } |
| 112 | + |
| 113 | + private static boolean hasLeadingSpace(String s) { |
| 114 | + return s.length() == 0 || Character.isWhitespace(s.charAt(0)); |
| 115 | + } |
| 116 | + |
| 117 | + /** |
| 118 | + * Resolves this instance to a MediaType instance defined in given MediaTypeRegistry. |
| 119 | + * Performs validation against parameters. |
| 120 | + * @param mediaTypeRegistry a registry where a mapping between a raw media type to an instance MediaType is defined |
| 121 | + * @return a MediaType instance or null if no media type could be found or if a known parameter do not passes validation |
| 122 | + */ |
| 123 | + public <T extends MediaType> T toMediaType(MediaTypeRegistry<T> mediaTypeRegistry) { |
| 124 | + T someType = mediaTypeRegistry.typeWithSubtypeToMediaType(mediaTypeWithoutParameters()); |
| 125 | + |
| 126 | + if (someType != null) { |
| 127 | + Map<String, Pattern> registeredParams = mediaTypeRegistry.parametersFor(mediaTypeWithoutParameters()); |
| 128 | + for (Map.Entry<String, String> givenParamEntry : parameters.entrySet()) { |
| 129 | + if (isValidParameter(givenParamEntry.getKey(), givenParamEntry.getValue(), registeredParams) == false) { |
| 130 | + return null; |
| 131 | + } |
| 132 | + } |
| 133 | + return someType; |
| 134 | + } |
| 135 | + return null; |
| 136 | + } |
| 137 | + |
| 138 | + private boolean isValidParameter(String paramName, String value, Map<String, Pattern> registeredParams) { |
| 139 | + if (registeredParams.containsKey(paramName)) { |
| 140 | + Pattern regex = registeredParams.get(paramName); |
| 141 | + return regex.matcher(value).matches(); |
| 142 | + } |
| 143 | + // TODO undefined parameters are allowed until https://github.com/elastic/elasticsearch/issues/63080 |
| 144 | + return true; |
| 145 | + } |
| 146 | + |
| 147 | + @Override |
| 148 | + public String toString() { |
| 149 | + return originalHeaderValue; |
| 150 | + } |
| 151 | + |
| 152 | + public String responseContentTypeHeader() { |
| 153 | + return mediaTypeWithoutParameters() + formatParameters(parameters); |
| 154 | + } |
| 155 | + |
| 156 | + // used in testing |
| 157 | + public String responseContentTypeHeader(Map<String, String> params) { |
| 158 | + return mediaTypeWithoutParameters() + formatParameters(params); |
| 159 | + } |
| 160 | + |
| 161 | + private String formatParameters(Map<String, String> params) { |
| 162 | + String joined = params.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining(";")); |
| 163 | + return joined.isEmpty() ? "" : ";" + joined; |
| 164 | + } |
| 165 | + |
| 166 | +} |
0 commit comments