/** * Create a canonical URI from a given URI. A canonical URI is a URI with:<ul> * <li>the host part of the authority lower-case since URI semantics dictate that hostnames are case insensitive * <li>(optionally, NOT appropriate for Origin headers) the path part set to "/" if there was no path in the * input URI (this conforms to the WebSocket and HTTP protocol specifications and avoids us having to do special * handling for path throughout the server code). * </ul> * @param uriString the URI to canonicalize, in string form * @param canonicalizePath if true, append trailing '/' when missing * @return a URI with the host part of the authority lower-case and (optionally) trailing / added, or null if the uri is null * @throws IllegalArgumentException if the uriString is not valid syntax */ public static URI getCanonicalURI(String uriString, boolean canonicalizePath) { if ((uriString != null) && !"".equals(uriString)) { return getCanonicalURI(URI.create(uriString), canonicalizePath); } return null; }
private void canonicalizeURIHeaders(Map<String, List<String>> headers, String... headerNames) { for (String headerName : headerNames) { List<String> headerValues = headers.get(headerName); if (headerValues != null) { int size = headerValues.size(); for (int i = 0; i<size; i++) { String value = headerValues.get(i); if (value.isEmpty()) continue; // KG-11212: NullPointerException when header value is empty, effect: client // connection closed abruptly String valueLC = HttpUtils.getCanonicalURI(value, false).toString(); if (!valueLC.equals(value)) { headerValues.set(i, valueLC); headers.put(headerName, headerValues); } } } } }
private String getEmulatedOriginIfRequestMatchesOrigin(HttpRequestMessage httpRequest, String candidateOrigin) { String emulatedOrigin = null; String origin = httpRequest.getHeader("Origin"); URI requestURI = HttpUtils.getCanonicalURI(httpRequest.getRequestURI(), false); if (origin != null && requestURI != null) { URI originURI = HttpUtils.getCanonicalURI(origin, false); String originScheme = originURI.getScheme(); String originAuthority = originURI.getAuthority(); if (originAuthority != null && originAuthority.indexOf(':') == -1) { int port = "https".equals(originScheme) ? 443 : 80; originAuthority += ":" + port; } boolean isSecure = httpRequest.isSecure(); String scheme = isSecure ? "https" : "http"; String authority = HttpUtils.getHostAndPort(httpRequest, isSecure); if (scheme.equals(originScheme) && authority.equals(originAuthority)) { // cross-origin request emulated via same-origin request, // use .ko query parameter for Origin emulatedOrigin = candidateOrigin; } } return emulatedOrigin; } }
} else { try { String emulatedOriginLC = HttpUtils.getCanonicalURI(emulatedOrigin, false).toString(); httpRequest.setHeader("Origin", emulatedOriginLC); } catch (Exception e) {