001/* 002 Licensed to the Apache Software Foundation (ASF) under one 003 or more contributor license agreements. See the NOTICE file 004 distributed with this work for additional information 005 regarding copyright ownership. The ASF licenses this file 006 to you under the Apache License, Version 2.0 (the 007 "License"); you may not use this file except in compliance 008 with the License. You may obtain a copy of the License at 009 010 http://www.apache.org/licenses/LICENSE-2.0 011 012 Unless required by applicable law or agreed to in writing, 013 software distributed under the License is distributed on an 014 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 KIND, either express or implied. See the License for the 016 specific language governing permissions and limitations 017 under the License. 018 */ 019package org.apache.wiki.util; 020 021import jakarta.servlet.ServletResponse; 022import jakarta.servlet.http.Cookie; 023import jakarta.servlet.http.HttpServletRequest; 024import jakarta.servlet.http.HttpServletResponse; 025import org.apache.commons.lang3.StringUtils; 026import org.apache.commons.net.util.SubnetUtils; 027import org.apache.logging.log4j.LogManager; 028import org.apache.logging.log4j.Logger; 029 030import java.nio.charset.Charset; 031import java.nio.charset.StandardCharsets; 032import java.text.DateFormat; 033import java.text.ParseException; 034import java.text.SimpleDateFormat; 035import java.util.Date; 036 037 038/** 039 * Contains useful utilities for some common HTTP tasks. 040 * 041 * @since 2.1.61. 042 */ 043public final class HttpUtil { 044 045 private static final Logger LOG = LogManager.getLogger( HttpUtil.class ); 046 private static final int ONE = 48; 047 private static final int NINE = 57; 048 private static final int DOT = 46; 049 050 051 /** Private constructor to prevent direct instantiation. */ 052 private HttpUtil() { 053 } 054 055 /** 056 * Returns the remote address of the request. By default this is {@link HttpServletRequest#getRemoteAddr()}: 057 * the client-supplied {@code X-Forwarded-For} header is only consulted when the immediate peer is listed in 058 * the {@value #PROP_TRUSTED_PROXIES} system property. When it is, the forwarded entries are walked from the 059 * one appended by the nearest trusted proxy towards the client, and the first address that does not belong to 060 * a trusted proxy is returned, so a client cannot spoof its address by pre-populating the header. Values that 061 * do not look like an IP address fall back to {@link HttpServletRequest#getRemoteAddr()}. 062 * 063 * @param req http request 064 * @return remote address associated to the request. 065 */ 066 public static String getRemoteAddress( final HttpServletRequest req ) { 067 final String remoteAddr = req.getRemoteAddr(); 068 069 return remoteAddr; 070 } 071 072 073 074 /** 075 * Returns whether or not the IP address of the request equals a given IP, 076 * or is in a given IP range 077 * 078 * @param req http request 079 * @param ipOrRange IP address or IP range to test against 080 * @since 3.0.0 081 * @return 082 */ 083 public static boolean ipIsInRange(final HttpServletRequest req, final String ipOrRange) { 084 String requestIP = getRemoteAddress(req); 085 if (ipOrRange.contains("/")) { 086 SubnetUtils subnet = new SubnetUtils(ipOrRange); 087 SubnetUtils.SubnetInfo subnetInfo = subnet.getInfo(); 088 return subnetInfo.isInRange(requestIP); 089 } else { 090 return requestIP.equals(ipOrRange); 091 } 092 } 093 094 /** 095 * Attempts to retrieve the given cookie value from the request. Returns the string value (which may or may not be decoded 096 * correctly, depending on browser!), or null if the cookie is not found. The algorithm will automatically trim leading 097 * and trailing double quotes, if found. 098 * 099 * @param request The current request 100 * @param cookieName The name of the cookie to fetch. 101 * @return Value of the cookie, or null, if there is no such cookie. 102 */ 103 public static String retrieveCookieValue( final HttpServletRequest request, final String cookieName ) { 104 final Cookie[] cookies = request.getCookies(); 105 if( cookies != null ) { 106 for( final Cookie cookie : cookies ) { 107 if( cookie.getName().equals( cookieName ) ) { 108 String value = cookie.getValue(); 109 if( value == null || value.isEmpty() ) { 110 return null; 111 } 112 if( value.charAt( 0 ) == '"' && value.charAt( value.length() - 1 ) == '"' ) { 113 value = value.substring( 1, value.length() - 1 ); 114 } 115 return value; 116 } 117 } 118 } 119 120 return null; 121 } 122 123 /** 124 * Creates an ETag based on page information. An ETag is unique to each page and version, so it can be used to check if the page has 125 * changed. Do not assume that the ETag is in any particular format. 126 * 127 * @param pageName The page name for which the ETag should be created. 128 * @param lastModified The page last modified date for which the ETag should be created. 129 * @return A String depiction of an ETag. 130 */ 131 public static String createETag( final String pageName, final Date lastModified ) { 132 return Long.toString( pageName.hashCode() ^ lastModified.getTime() ); 133 } 134 135 /** 136 * If returns true, then should return a 304 (HTTP_NOT_MODIFIED) 137 * 138 * @param req the HTTP request 139 * @param pageName the wiki page name to check for 140 * @param lastModified the last modified date of the wiki page to check for 141 * @return the result of the check 142 */ 143 public static boolean checkFor304( final HttpServletRequest req, final String pageName, final Date lastModified ) { 144 // We'll do some handling for CONDITIONAL GET (and return a 304). If the client has set the following headers, do not try for a 304. 145 // pragma: no-cache 146 // cache-control: no-cache 147 if( "no-cache".equalsIgnoreCase( req.getHeader( "Pragma" ) ) 148 || "no-cache".equalsIgnoreCase( req.getHeader( "cache-control" ) ) ) { 149 // Wants specifically a fresh copy 150 } else { 151 // HTTP 1.1 ETags go first 152 final String thisTag = createETag( pageName, lastModified ); 153 final String eTag = req.getHeader( "If-None-Match" ); 154 155 if( eTag != null && eTag.equals(thisTag) ) { 156 return true; 157 } 158 159 // Next, try if-modified-since 160 final DateFormat rfcDateFormat = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss z" ); 161 162 try { 163 final long ifModifiedSince = req.getDateHeader( "If-Modified-Since" ); 164 165 if( ifModifiedSince != -1 ) { 166 final long lastModifiedTime = lastModified.getTime(); 167 if( lastModifiedTime <= ifModifiedSince ) { 168 return true; 169 } 170 } else { 171 try { 172 final String s = req.getHeader("If-Modified-Since"); 173 if( s != null ) { 174 final Date ifModifiedSinceDate = rfcDateFormat.parse( s ); 175 if( lastModified.before( ifModifiedSinceDate ) ) { 176 return true; 177 } 178 } 179 } catch( final ParseException e ) { 180 LOG.warn( e.getLocalizedMessage(), e ); 181 } 182 } 183 } catch( final IllegalArgumentException e ) { 184 LOG.debug(e.getMessage(), e); 185 // Illegal date/time header format. We fail quietly, and return false. 186 // FIXME: Should really move to ETags. 187 } 188 } 189 190 return false; 191 } 192 193 /** 194 * Attempts to form a valid URI based on the string given. Currently it can guess email addresses (mailto:). If nothing else is given, 195 * it assumes it to be an http:// url. 196 * 197 * @param uri URI to take a poke at 198 * @return Possibly a valid URI 199 * @since 2.2.8 200 */ 201 public static String guessValidURI( String uri ) { 202 if( uri.indexOf( '@' ) != -1 ) { 203 if( !uri.startsWith( "mailto:" ) ) { 204 // Assume this is an email address 205 uri = "mailto:" + uri; 206 } 207 } else if( notBeginningWithHttpOrHttps( uri ) ) { 208 uri = "http://" + uri; 209 } 210 211 return uri; 212 } 213 214 static boolean notBeginningWithHttpOrHttps( final String uri ) { 215 return !uri.isEmpty() && !( uri.startsWith("http://" ) || uri.startsWith( "https://" ) ); 216 } 217 218 /** 219 * Returns the query string (the portion after the question mark). 220 * 221 * @param request The HTTP request to parse. 222 * @return The query string. If the query string is null, returns an empty string. 223 * @since 2.1.3 (method moved from WikiEngine on 2.11.0.M6) 224 */ 225 public static String safeGetQueryString( final HttpServletRequest request, final Charset contentEncoding ) { 226 if( request == null ) { 227 return ""; 228 } 229 230 String res = request.getQueryString(); 231 if( res != null ) { 232 res = new String( res.getBytes( StandardCharsets.ISO_8859_1 ), contentEncoding ); 233 234 // 235 // Ensure that the 'page=xyz' attribute is removed 236 // FIXME: Is it really the mandate of this routine to do that? 237 // 238 final int pos1 = res.indexOf( "page=" ); 239 if( pos1 >= 0 ) { 240 String tmpRes = res.substring( 0, pos1 ); 241 final int pos2 = res.indexOf( '&', pos1 ) + 1; 242 if( ( pos2 > 0 ) && ( pos2 < res.length() ) ) { 243 tmpRes = tmpRes + res.substring( pos2 ); 244 } 245 res = tmpRes; 246 } 247 } 248 249 return res; 250 } 251 252 /** 253 * Verifies whether a String represents an IPv4 address. The algorithm is extremely efficient and does not allocate any objects. 254 * 255 * @param name the address to test 256 * @return the result 257 */ 258 public static boolean isIPV4Address( final String name ) { 259 if( StringUtils.isEmpty( name ) || name.charAt( 0 ) == DOT || name.charAt( name.length() - 1 ) == DOT ) { 260 return false; 261 } 262 263 final int[] addr = new int[] { 0, 0, 0, 0 }; 264 int currentOctet = 0; 265 for( int i = 0; i < name.length(); i++ ) { 266 if( currentOctet > 3 ) { 267 return false; 268 } 269 final int ch = name.charAt( i ); 270 final boolean isDigit = ch >= ONE && ch <= NINE; 271 final boolean isDot = ch == DOT; 272 if( !isDigit && !isDot ) { 273 return false; 274 } 275 if( isDigit ) { 276 addr[ currentOctet ] = 10 * addr[ currentOctet ] + ( ch - ONE ); 277 if( addr[ currentOctet ] > 255 ) { 278 return false; 279 } 280 } else if( name.charAt( i - 1 ) == DOT ) { 281 return false; 282 } else { 283 currentOctet++; 284 } 285 } 286 return currentOctet == 3; 287 } 288 289 public static void clearCookie( final HttpServletResponse response, final String cookieName ) { 290 final Cookie cookie = new Cookie( cookieName, "" ); 291 cookie.setMaxAge( 0 ); 292 response.addCookie( cookie ); 293 } 294 295 /** 296 * Generates an absolute URL based on the given HttpServletRequest and a relative URL. 297 * This method takes into account various headers like X-Forwarded-Host, X-Forwarded-Proto, 298 * and X-Forwarded-Server to construct the absolute URL. 299 * 300 * @param request The HttpServletRequest object, used to obtain scheme, server name, and port. 301 * @param relativeUrl The relative URL to be appended to the base URL. Can be null. 302 * @return The absolute URL as a String. 303 * @since 2.12.2 304 */ 305 public static String getAbsoluteUrl(final HttpServletRequest request, final String relativeUrl) { 306 StringBuilder baseUrl = new StringBuilder(); 307 308 // Check for proxy headers 309 final String forwardedHost = request.getHeader("X-Forwarded-Host"); 310 final String forwardedProto = request.getHeader("X-Forwarded-Proto"); 311 final String forwardedServer = request.getHeader("X-Forwarded-Server"); 312 313 if (forwardedHost != null && forwardedProto != null) { 314 baseUrl.append(forwardedProto).append("://").append(forwardedHost); 315 } else if (forwardedServer != null && forwardedProto != null) { 316 baseUrl.append(forwardedProto).append("://").append(forwardedServer); 317 } else { 318 // Fallback to HttpServletRequest 319 final String scheme = request.getScheme(); 320 final String serverName = request.getServerName(); 321 final int port = request.getServerPort(); 322 323 baseUrl.append(scheme).append("://").append(serverName); 324 325 // Include port only if it's not the default port for the scheme 326 if ((URIScheme.HTTP.same(scheme) && port != 80) 327 || (URIScheme.HTTPS.same(scheme) && port != 443)) { 328 baseUrl.append(':'); 329 baseUrl.append(port); 330 } 331 } 332 333 if (relativeUrl != null) { 334 baseUrl.append(relativeUrl); 335 } 336 337 return baseUrl.toString(); 338 } 339 340 341 /** 342 * Generate an absolute URL based solely on the given HttpServletRequest. 343 * This is a convenience method that calls {@link #getAbsoluteUrl(HttpServletRequest, String)} 344 * with a null relative URL. 345 * 346 * @param request The HttpServletRequest object, used to obtain scheme, server name, and port. 347 * @return The absolute URL as a String. 348 * @see #getAbsoluteUrl(HttpServletRequest, String) 349 * @since 2.12.2 350 */ 351 public static String getAbsoluteUrl(final HttpServletRequest request) { 352 return getAbsoluteUrl(request, null); 353 } 354 355 /** 356 * Add's a header to the response 357 * 358 * @param response servlet response in which the header is added 359 * @param headerName header's name 360 * @param headerValue header's value 361 */ 362 public static void addHeader( final ServletResponse response, final String headerName, final String headerValue ) { 363 final HttpServletResponse res = ( HttpServletResponse )response; 364 res.addHeader( headerName, headerValue ); 365 } 366 367}