1 25 package org.ofbiz.webapp.control; 26 27 import java.io.IOException ; 28 import java.net.MalformedURLException ; 29 import java.net.URL ; 30 import java.util.ArrayList ; 31 import java.util.Collection ; 32 import java.util.Enumeration ; 33 import java.util.Iterator ; 34 import java.util.List ; 35 import java.util.Map ; 36 import javax.servlet.Filter ; 37 import javax.servlet.FilterChain ; 38 import javax.servlet.FilterConfig ; 39 import javax.servlet.ServletException ; 40 import javax.servlet.ServletRequest ; 41 import javax.servlet.ServletResponse ; 42 import javax.servlet.http.HttpServletRequest ; 43 import javax.servlet.http.HttpServletResponse ; 44 import javax.servlet.http.HttpServletResponseWrapper ; 45 46 import org.ofbiz.base.container.ContainerLoader; 47 import org.ofbiz.base.start.StartupException; 48 import org.ofbiz.base.util.CachedClassLoader; 49 import org.ofbiz.base.util.Debug; 50 import org.ofbiz.base.util.StringUtil; 51 import org.ofbiz.base.util.UtilHttp; 52 import org.ofbiz.base.util.UtilValidate; 53 import org.ofbiz.base.util.UtilObject; 54 import org.ofbiz.entity.GenericDelegator; 55 import org.ofbiz.security.Security; 56 import org.ofbiz.security.SecurityConfigurationException; 57 import org.ofbiz.security.SecurityFactory; 58 import org.ofbiz.service.LocalDispatcher; 59 import org.ofbiz.service.WebAppDispatcher; 60 61 68 public class ContextFilter implements Filter { 69 70 public static final String module = ContextFilter.class.getName(); 71 public static final String CONTAINER_CONFIG = "limited-containers.xml"; 72 public static final String FORWARDED_FROM_SERVLET = "_FORWARDED_FROM_SERVLET_"; 73 74 protected ClassLoader localCachedClassLoader = null; 75 protected FilterConfig config = null; 76 protected boolean debug = false; 77 78 81 public void init(FilterConfig config) throws ServletException { 82 this.config = config; 83 84 this.putAllInitParametersInAttributes(); 86 87 ClassLoader loader = Thread.currentThread().getContextClassLoader(); 89 localCachedClassLoader = new CachedClassLoader(loader, (String ) config.getServletContext().getAttribute("webSiteId")); 90 91 this.debug = "true".equalsIgnoreCase(config.getInitParameter("debug")); 93 if (!debug) { 94 debug = Debug.verboseOn(); 95 } 96 97 getContainers(); 99 getServerId(); 101 getDelegator(); 103 getSecurity(); 105 getDispatcher(); 107 108 new java.security.SecureRandom ().nextLong(); 110 } 111 112 115 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException , ServletException { 116 HttpServletRequest httpRequest = (HttpServletRequest ) request; 117 HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper ((HttpServletResponse ) response); 118 119 121 Thread.currentThread().setContextClassLoader(localCachedClassLoader); 124 125 httpRequest.getSession().setAttribute("webSiteId", config.getServletContext().getAttribute("webSiteId")); 127 128 request.setAttribute("servletContext", config.getServletContext()); 130 131 request.setAttribute("_CONTEXT_ROOT_", config.getServletContext().getRealPath("/")); 133 134 StringBuffer serverRootUrl = UtilHttp.getServerRootUrl(httpRequest); 136 request.setAttribute("_SERVER_ROOT_URL_", serverRootUrl.toString()); 137 138 String reqAttrMapHex = (String ) httpRequest.getSession().getAttribute("_REQ_ATTR_MAP_"); 140 if (UtilValidate.isNotEmpty(reqAttrMapHex)) { 141 byte[] reqAttrMapBytes = StringUtil.fromHexString(reqAttrMapHex); 142 Map reqAttrMap = (Map ) UtilObject.getObject(reqAttrMapBytes); 143 if (reqAttrMap != null) { 144 Iterator i = reqAttrMap.keySet().iterator(); 145 while (i.hasNext()) { 146 String key = (String ) i.next(); 147 request.setAttribute(key, reqAttrMap.get(key)); 148 } 149 } 150 httpRequest.getSession().removeAttribute("_REQ_ATTR_MAP_"); 151 } 152 153 String disableSecurity = config.getInitParameter("disableContextSecurity"); 156 if (disableSecurity != null && "Y".equals(disableSecurity)) { 157 chain.doFilter(request, response); 158 return; 159 } 160 161 String redirectAllTo = config.getInitParameter("forceRedirectAll"); 163 if (redirectAllTo != null && redirectAllTo.length() > 0) { 164 if (httpRequest.getSession().getAttribute("_FORCE_REDIRECT_") == null) { 166 httpRequest.getSession().setAttribute("_FORCE_REDIRECT_", "true"); 167 Debug.logWarning("Redirecting user to: " + redirectAllTo, module); 168 169 if (!redirectAllTo.toLowerCase().startsWith("http")) { 170 redirectAllTo = httpRequest.getContextPath() + redirectAllTo; 171 } 172 wrapper.sendRedirect(redirectAllTo); 173 return; 174 } else { 175 httpRequest.getSession().removeAttribute("_FORCE_REDIRECT_"); 176 chain.doFilter(request, response); 177 return; 178 } 179 } 180 181 if (request.getAttribute(ContextFilter.FORWARDED_FROM_SERVLET) == null) { 183 String allowedPath = config.getInitParameter("allowedPaths"); 185 String redirectPath = config.getInitParameter("redirectPath"); 186 String errorCode = config.getInitParameter("errorCode"); 187 188 List allowList = StringUtil.split(allowedPath, ":"); 189 allowList.add("/"); allowList.add(""); 192 if (debug) Debug.log("[Request]: " + httpRequest.getRequestURI(), module); 193 194 String requestPath = httpRequest.getServletPath(); 195 if (requestPath == null) requestPath = ""; 196 if (requestPath.lastIndexOf("/") > 0) { 197 if (requestPath.indexOf("/") == 0) { 198 requestPath = "/" + requestPath.substring(1, requestPath.indexOf("/", 1)); 199 } else { 200 requestPath = requestPath.substring(1, requestPath.indexOf("/")); 201 } 202 } 203 204 String requestInfo = httpRequest.getServletPath(); 205 if (requestInfo == null) requestInfo = ""; 206 if (requestInfo.lastIndexOf("/") >= 0) { 207 requestInfo = requestInfo.substring(0, requestInfo.lastIndexOf("/")) + "/*"; 208 } 209 210 StringBuffer contextUriBuffer = new StringBuffer (); 211 if (httpRequest.getContextPath() != null) { 212 contextUriBuffer.append(httpRequest.getContextPath()); 213 } 214 if (httpRequest.getServletPath() != null) { 215 contextUriBuffer.append(httpRequest.getServletPath()); 216 } 217 if (httpRequest.getPathInfo() != null) { 218 contextUriBuffer.append(httpRequest.getPathInfo()); 219 } 220 String contextUri = contextUriBuffer.toString(); 221 222 if (Debug.verboseOn()) { 224 for (int i = 0; i < allowList.size(); i++) { 225 Debug.logVerbose("[Allow]: " + allowList.get(i), module); 226 } 227 Debug.logVerbose("[Request path]: " + requestPath, module); 228 Debug.logVerbose("[Request info]: " + requestInfo, module); 229 Debug.logVerbose("[Servlet path]: " + httpRequest.getServletPath(), module); 230 } 231 232 if (!allowList.contains(requestPath) && !allowList.contains(requestInfo) && !allowList.contains(httpRequest.getServletPath())) { 234 String filterMessage = "[Filtered request]: " + contextUri; 235 236 if (redirectPath == null) { 237 int error = 404; 238 try { 239 error = Integer.parseInt(errorCode); 240 } catch (NumberFormatException nfe) { 241 Debug.logWarning(nfe, "Error code specified would not parse to Integer : " + errorCode, module); 242 } 243 filterMessage = filterMessage + " (" + error + ")"; 244 wrapper.sendError(error, contextUri); 245 } else { 246 filterMessage = filterMessage + " (" + redirectPath + ")"; 247 if (!redirectPath.toLowerCase().startsWith("http")) { 248 redirectPath = httpRequest.getContextPath() + redirectPath; 249 } 250 wrapper.sendRedirect(redirectPath); 251 } 252 Debug.logWarning(filterMessage, module); 253 return; 254 } 255 } 256 257 chain.doFilter(request, response); 259 } 260 261 264 public void destroy() { 265 getDispatcher().deregister(); 266 config = null; 267 } 268 269 protected LocalDispatcher getDispatcher() { 270 LocalDispatcher dispatcher = (LocalDispatcher) config.getServletContext().getAttribute("dispatcher"); 271 if (dispatcher == null) { 272 GenericDelegator delegator = getDelegator(); 273 274 if (delegator == null) { 275 Debug.logError("[ContextFilter.init] ERROR: delegator not defined.", module); 276 return null; 277 } 278 Collection readers = null; 279 String readerFiles = config.getServletContext().getInitParameter("serviceReaderUrls"); 280 281 if (readerFiles != null) { 282 readers = new ArrayList (); 283 List readerList = StringUtil.split(readerFiles, ";"); 284 Iterator i = readerList.iterator(); 285 286 while (i.hasNext()) { 287 try { 288 String name = (String ) i.next(); 289 URL readerURL = config.getServletContext().getResource(name); 290 291 if (readerURL != null) 292 readers.add(readerURL); 293 } catch (NullPointerException npe) { 294 Debug.logInfo(npe, "[ContextFilter.init] ERROR: Null pointer exception thrown.", module); 295 } catch (MalformedURLException e) { 296 Debug.logError(e, "[ContextFilter.init] ERROR: cannot get URL from String.", module); 297 } 298 } 299 } 300 String dispatcherName = config.getServletContext().getInitParameter("localDispatcherName"); 302 303 if (dispatcherName == null) 304 Debug.logError("No localDispatcherName specified in the web.xml file", module); 305 dispatcher = new WebAppDispatcher(dispatcherName, delegator, readers); 306 config.getServletContext().setAttribute("dispatcher", dispatcher); 307 if (dispatcher == null) 308 Debug.logError("[ContextFilter.init] ERROR: dispatcher could not be initialized.", module); 309 } 310 return dispatcher; 311 } 312 313 protected GenericDelegator getDelegator() { 314 GenericDelegator delegator = (GenericDelegator) config.getServletContext().getAttribute("delegator"); 315 if (delegator == null) { 316 String delegatorName = config.getServletContext().getInitParameter("entityDelegatorName"); 317 318 if (delegatorName == null || delegatorName.length() <= 0) { 319 delegatorName = "default"; 320 } 321 if (Debug.infoOn()) Debug.logInfo("[ContextFilter.init] Getting Entity Engine Delegator with delegator name " + delegatorName, module); 322 delegator = GenericDelegator.getGenericDelegator(delegatorName); 323 config.getServletContext().setAttribute("delegator", delegator); 324 if (delegator == null) { 325 Debug.logError("[ContextFilter.init] ERROR: delegator factory returned null for delegatorName \"" + delegatorName + "\"", module); 326 } 327 } 328 return delegator; 329 } 330 331 protected Security getSecurity() { 332 Security security = (Security) config.getServletContext().getAttribute("security"); 333 if (security == null) { 334 GenericDelegator delegator = (GenericDelegator) config.getServletContext().getAttribute("delegator"); 335 336 if (delegator != null) { 337 try { 338 security = SecurityFactory.getInstance(delegator); 339 } catch (SecurityConfigurationException e) { 340 Debug.logError(e, "[ServiceDispatcher.init] : No instance of security imeplemtation found.", module); 341 } 342 } 343 config.getServletContext().setAttribute("security", security); 344 if (security == null) { 345 Debug.logError("[ContextFilter.init] ERROR: security create failed.", module); 346 } 347 } 348 return security; 349 } 350 351 protected void putAllInitParametersInAttributes() { 352 Enumeration initParamEnum = config.getServletContext().getInitParameterNames(); 353 while (initParamEnum.hasMoreElements()) { 354 String initParamName = (String ) initParamEnum.nextElement(); 355 String initParamValue = config.getServletContext().getInitParameter(initParamName); 356 if (Debug.infoOn()) Debug.logInfo("Adding web.xml context-param to application attribute with name [" + initParamName + "] and value [" + initParamValue + "]", module); 357 config.getServletContext().setAttribute(initParamName, initParamValue); 358 } 359 } 360 361 protected String getServerId() { 362 String serverId = (String ) config.getServletContext().getAttribute("_serverId"); 363 if (serverId == null) { 364 serverId = config.getServletContext().getInitParameter("ofbizServerName"); 365 config.getServletContext().setAttribute("_serverId", serverId); 366 } 367 return serverId; 368 } 369 370 protected boolean getContainers() throws ServletException { 371 try { 372 ContainerLoader.loadContainers(CONTAINER_CONFIG, null); 373 } catch (StartupException e) { 374 Debug.logError(e, module); 375 throw new ServletException ("Unable to load containers; cannot start ContextFilter"); 376 } 377 return true; 378 } 379 } 380 | Popular Tags |