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 org.apache.commons.lang3.StringUtils; 022import org.apache.logging.log4j.LogManager; 023import org.apache.logging.log4j.Logger; 024 025import javax.servlet.ServletResponse; 026import javax.servlet.http.Cookie; 027import javax.servlet.http.HttpServletRequest; 028import javax.servlet.http.HttpServletResponse; 029import java.nio.charset.Charset; 030import java.nio.charset.StandardCharsets; 031import java.text.DateFormat; 032import java.text.ParseException; 033import java.text.SimpleDateFormat; 034import java.util.Date; 035 036 037/** 038 * Contains useful utilities for some common HTTP tasks. 039 * 040 * @since 2.1.61. 041 */ 042public final class HttpUtil { 043 044 private static final Logger LOG = LogManager.getLogger( HttpUtil.class ); 045 private static final int ONE = 48; 046 private static final int NINE = 57; 047 private static final int DOT = 46; 048 049 /** Private constructor to prevent direct instantiation. */ 050 private HttpUtil() { 051 } 052 053 /** 054 * returns the remote address by looking into {@code x-forwarded-for} header or, if unavailable, 055 * into {@link HttpServletRequest#getRemoteAddr()}. 056 * 057 * @param req http request 058 * @return remote address associated to the request. 059 */ 060 public static String getRemoteAddress( final HttpServletRequest req ) { 061 return StringUtils.isNotEmpty ( req.getHeader( "X-Forwarded-For" ) ) ? req.getHeader( "X-Forwarded-For" ) : 062 req.getRemoteAddr(); 063 } 064 065 /** 066 * Attempts to retrieve the given cookie value from the request. Returns the string value (which may or may not be decoded 067 * correctly, depending on browser!), or null if the cookie is not found. The algorithm will automatically trim leading 068 * and trailing double quotes, if found. 069 * 070 * @param request The current request 071 * @param cookieName The name of the cookie to fetch. 072 * @return Value of the cookie, or null, if there is no such cookie. 073 */ 074 public static String retrieveCookieValue( final HttpServletRequest request, final String cookieName ) { 075 final Cookie[] cookies = request.getCookies(); 076 if( cookies != null ) { 077 for( final Cookie cookie : cookies ) { 078 if( cookie.getName().equals( cookieName ) ) { 079 String value = cookie.getValue(); 080 if( value == null || value.isEmpty() ) { 081 return null; 082 } 083 if( value.charAt( 0 ) == '"' && value.charAt( value.length() - 1 ) == '"' ) { 084 value = value.substring( 1, value.length() - 1 ); 085 } 086 return value; 087 } 088 } 089 } 090 091 return null; 092 } 093 094 /** 095 * 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 096 * changed. Do not assume that the ETag is in any particular format. 097 * 098 * @param pageName The page name for which the ETag should be created. 099 * @param lastModified The page last modified date for which the ETag should be created. 100 * @return A String depiction of an ETag. 101 */ 102 public static String createETag( final String pageName, final Date lastModified ) { 103 return Long.toString( pageName.hashCode() ^ lastModified.getTime() ); 104 } 105 106 /** 107 * If returns true, then should return a 304 (HTTP_NOT_MODIFIED) 108 * 109 * @param req the HTTP request 110 * @param pageName the wiki page name to check for 111 * @param lastModified the last modified date of the wiki page to check for 112 * @return the result of the check 113 */ 114 public static boolean checkFor304( final HttpServletRequest req, final String pageName, final Date lastModified ) { 115 // 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. 116 // pragma: no-cache 117 // cache-control: no-cache 118 if( "no-cache".equalsIgnoreCase( req.getHeader( "Pragma" ) ) 119 || "no-cache".equalsIgnoreCase( req.getHeader( "cache-control" ) ) ) { 120 // Wants specifically a fresh copy 121 } else { 122 // HTTP 1.1 ETags go first 123 final String thisTag = createETag( pageName, lastModified ); 124 final String eTag = req.getHeader( "If-None-Match" ); 125 126 if( eTag != null && eTag.equals(thisTag) ) { 127 return true; 128 } 129 130 // Next, try if-modified-since 131 final DateFormat rfcDateFormat = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss z" ); 132 133 try { 134 final long ifModifiedSince = req.getDateHeader( "If-Modified-Since" ); 135 136 if( ifModifiedSince != -1 ) { 137 final long lastModifiedTime = lastModified.getTime(); 138 if( lastModifiedTime <= ifModifiedSince ) { 139 return true; 140 } 141 } else { 142 try { 143 final String s = req.getHeader("If-Modified-Since"); 144 if( s != null ) { 145 final Date ifModifiedSinceDate = rfcDateFormat.parse( s ); 146 if( lastModified.before( ifModifiedSinceDate ) ) { 147 return true; 148 } 149 } 150 } catch( final ParseException e ) { 151 LOG.warn( e.getLocalizedMessage(), e ); 152 } 153 } 154 } catch( final IllegalArgumentException e ) { 155 // Illegal date/time header format. We fail quietly, and return false. 156 // FIXME: Should really move to ETags. 157 } 158 } 159 160 return false; 161 } 162 163 /** 164 * Attempts to form a valid URI based on the string given. Currently it can guess email addresses (mailto:). If nothing else is given, 165 * it assumes it to be an http:// url. 166 * 167 * @param uri URI to take a poke at 168 * @return Possibly a valid URI 169 * @since 2.2.8 170 */ 171 public static String guessValidURI( String uri ) { 172 if( uri.indexOf( '@' ) != -1 ) { 173 if( !uri.startsWith( "mailto:" ) ) { 174 // Assume this is an email address 175 uri = "mailto:" + uri; 176 } 177 } else if( notBeginningWithHttpOrHttps( uri ) ) { 178 uri = "http://" + uri; 179 } 180 181 return uri; 182 } 183 184 static boolean notBeginningWithHttpOrHttps( final String uri ) { 185 return !uri.isEmpty() && !( uri.startsWith("http://" ) || uri.startsWith( "https://" ) ); 186 } 187 188 /** 189 * Returns the query string (the portion after the question mark). 190 * 191 * @param request The HTTP request to parse. 192 * @return The query string. If the query string is null, returns an empty string. 193 * @since 2.1.3 (method moved from WikiEngine on 2.11.0.M6) 194 */ 195 public static String safeGetQueryString( final HttpServletRequest request, final Charset contentEncoding ) { 196 if( request == null ) { 197 return ""; 198 } 199 200 String res = request.getQueryString(); 201 if( res != null ) { 202 res = new String( res.getBytes( StandardCharsets.ISO_8859_1 ), contentEncoding ); 203 204 // 205 // Ensure that the 'page=xyz' attribute is removed 206 // FIXME: Is it really the mandate of this routine to do that? 207 // 208 final int pos1 = res.indexOf( "page=" ); 209 if( pos1 >= 0 ) { 210 String tmpRes = res.substring( 0, pos1 ); 211 final int pos2 = res.indexOf( '&', pos1 ) + 1; 212 if( ( pos2 > 0 ) && ( pos2 < res.length() ) ) { 213 tmpRes = tmpRes + res.substring( pos2 ); 214 } 215 res = tmpRes; 216 } 217 } 218 219 return res; 220 } 221 222 /** 223 * Verifies whether a String represents an IPv4 address. The algorithm is extremely efficient and does not allocate any objects. 224 * 225 * @param name the address to test 226 * @return the result 227 */ 228 public static boolean isIPV4Address( final String name ) { 229 if( StringUtils.isEmpty( name ) || name.charAt( 0 ) == DOT || name.charAt( name.length() - 1 ) == DOT ) { 230 return false; 231 } 232 233 final int[] addr = new int[] { 0, 0, 0, 0 }; 234 int currentOctet = 0; 235 for( int i = 0; i < name.length(); i++ ) { 236 if( currentOctet > 3 ) { 237 return false; 238 } 239 final int ch = name.charAt( i ); 240 final boolean isDigit = ch >= ONE && ch <= NINE; 241 final boolean isDot = ch == DOT; 242 if( !isDigit && !isDot ) { 243 return false; 244 } 245 if( isDigit ) { 246 addr[ currentOctet ] = 10 * addr[ currentOctet ] + ( ch - ONE ); 247 if( addr[ currentOctet ] > 255 ) { 248 return false; 249 } 250 } else if( name.charAt( i - 1 ) == DOT ) { 251 return false; 252 } else { 253 currentOctet++; 254 } 255 } 256 return currentOctet == 3; 257 } 258 259 public static void clearCookie( final HttpServletResponse response, final String cookieName ) { 260 final Cookie cookie = new Cookie( cookieName, "" ); 261 cookie.setMaxAge( 0 ); 262 response.addCookie( cookie ); 263 } 264 265 /** 266 * Generates an absolute URL based on the given HttpServletRequest and a relative URL. 267 * This method takes into account various headers like X-Forwarded-Host, X-Forwarded-Proto, 268 * and X-Forwarded-Server to construct the absolute URL. 269 * 270 * @param request The HttpServletRequest object, used to obtain scheme, server name, and port. 271 * @param relativeUrl The relative URL to be appended to the base URL. Can be null. 272 * @return The absolute URL as a String. 273 * @since 2.12.2 274 */ 275 public static String getAbsoluteUrl(final HttpServletRequest request, final String relativeUrl) { 276 StringBuilder baseUrl = new StringBuilder(); 277 278 // Check for proxy headers 279 final String forwardedHost = request.getHeader("X-Forwarded-Host"); 280 final String forwardedProto = request.getHeader("X-Forwarded-Proto"); 281 final String forwardedServer = request.getHeader("X-Forwarded-Server"); 282 283 if (forwardedHost != null && forwardedProto != null) { 284 baseUrl.append(forwardedProto).append("://").append(forwardedHost); 285 } else if (forwardedServer != null && forwardedProto != null) { 286 baseUrl.append(forwardedProto).append("://").append(forwardedServer); 287 } else { 288 // Fallback to HttpServletRequest 289 final String scheme = request.getScheme(); 290 final String serverName = request.getServerName(); 291 final int port = request.getServerPort(); 292 293 baseUrl.append(scheme).append("://").append(serverName); 294 295 // Include port only if it's not the default port for the scheme 296 if ((URIScheme.HTTP.same(scheme) && port != 80) 297 || (URIScheme.HTTPS.same(scheme) && port != 443)) { 298 baseUrl.append(':'); 299 baseUrl.append(port); 300 } 301 } 302 303 if (relativeUrl != null) { 304 baseUrl.append(relativeUrl); 305 } 306 307 return baseUrl.toString(); 308 } 309 310 311 /** 312 * Generate an absolute URL based solely on the given HttpServletRequest. 313 * This is a convenience method that calls {@link #getAbsoluteUrl(HttpServletRequest, String)} 314 * with a null relative URL. 315 * 316 * @param request The HttpServletRequest object, used to obtain scheme, server name, and port. 317 * @return The absolute URL as a String. 318 * @see #getAbsoluteUrl(HttpServletRequest, String) 319 * @since 2.12.2 320 */ 321 public static String getAbsoluteUrl(final HttpServletRequest request) { 322 return getAbsoluteUrl(request, null); 323 } 324 325 /** 326 * Add's a header to the response 327 * 328 * @param response servlet response in which the header is added 329 * @param headerName header's name 330 * @param headerValue header's value 331 * @since 2.12.6 332 */ 333 public static void addHeader( final ServletResponse response, final String headerName, final String headerValue ) { 334 final HttpServletResponse res = ( HttpServletResponse )response; 335 res.addHeader( headerName, headerValue ); 336 } 337 338}