1   /**
2    * Copyright (c) 2000-2007 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.servlet.filters.virtualhost;
24  
25  import com.liferay.portal.LayoutFriendlyURLException;
26  import com.liferay.portal.kernel.util.ContentTypes;
27  import com.liferay.portal.kernel.util.GetterUtil;
28  import com.liferay.portal.kernel.util.StringMaker;
29  import com.liferay.portal.kernel.util.StringPool;
30  import com.liferay.portal.kernel.util.StringUtil;
31  import com.liferay.portal.kernel.util.Validator;
32  import com.liferay.portal.model.Group;
33  import com.liferay.portal.model.LayoutSet;
34  import com.liferay.portal.model.impl.LayoutImpl;
35  import com.liferay.portal.service.GroupLocalServiceUtil;
36  import com.liferay.portal.util.PortalInstances;
37  import com.liferay.portal.util.PortalUtil;
38  import com.liferay.portal.util.WebKeys;
39  import com.liferay.util.SystemProperties;
40  
41  import java.io.IOException;
42  
43  import javax.servlet.Filter;
44  import javax.servlet.FilterChain;
45  import javax.servlet.FilterConfig;
46  import javax.servlet.RequestDispatcher;
47  import javax.servlet.ServletContext;
48  import javax.servlet.ServletException;
49  import javax.servlet.ServletRequest;
50  import javax.servlet.ServletResponse;
51  import javax.servlet.http.HttpServletRequest;
52  import javax.servlet.http.HttpServletResponse;
53  import javax.servlet.http.HttpSession;
54  
55  import org.apache.commons.logging.Log;
56  import org.apache.commons.logging.LogFactory;
57  
58  /**
59   * <a href="VirtualHostFilter.java.html"><b><i>View Source</i></b></a>
60   *
61   * <p>
62   * This filter is used to provide virtual host functionality. However, this
63   * filter is still required even if you do not use virtual hosting because it
64   * sets the company id in the request so that subsequent calls in the thread
65   * have the company id properly set. This filter must also always be the first
66   * filter in the list of filters.
67   * </p>
68   *
69   * @author Joel Kozikowski
70   * @author Brian Wing Shun Chan
71   *
72   */
73  public class VirtualHostFilter implements Filter {
74  
75      public static final boolean USE_FILTER = GetterUtil.getBoolean(
76          SystemProperties.get(VirtualHostFilter.class.getName()), true);
77  
78      public static final String ENCODING = GetterUtil.getString(
79          SystemProperties.get("file.encoding"), "UTF-8");
80  
81      public void init(FilterConfig config) throws ServletException {
82          _ctx = config.getServletContext();
83      }
84  
85      public void doFilter(
86              ServletRequest req, ServletResponse res, FilterChain chain)
87          throws IOException, ServletException {
88  
89          if (_log.isDebugEnabled()) {
90              if (USE_FILTER) {
91                  _log.debug("Virtual host is enabled");
92              }
93              else {
94                  _log.debug("Virtual host is disabled");
95              }
96          }
97  
98          HttpServletRequest httpReq = (HttpServletRequest)req;
99          HttpServletResponse httpRes = (HttpServletResponse)res;
100 
101         httpReq.setCharacterEncoding(ENCODING);
102         httpRes.setContentType(ContentTypes.TEXT_HTML_UTF8);
103 
104         // Company id needs to always be called here so that it's properly set
105         // in subsequent calls
106 
107         long companyId = PortalInstances.getCompanyId(httpReq);
108 
109         if (_log.isDebugEnabled()) {
110             _log.debug("Company id " + companyId);
111         }
112 
113         PortalUtil.getCurrentURL(httpReq);
114 
115         HttpSession ses = httpReq.getSession();
116 
117         Boolean httpsInitial = (Boolean)ses.getAttribute(WebKeys.HTTPS_INITIAL);
118 
119         if (httpsInitial == null) {
120             httpsInitial = Boolean.valueOf(httpReq.isSecure());
121 
122             ses.setAttribute(WebKeys.HTTPS_INITIAL, httpsInitial);
123 
124             if (_log.isDebugEnabled()) {
125                 _log.debug("Setting httpsInitial to " + httpsInitial);
126             }
127         }
128 
129         if (!USE_FILTER) {
130             chain.doFilter(req, res);
131 
132             return;
133         }
134 
135         StringBuffer requestURL = httpReq.getRequestURL();
136 
137         if (_log.isDebugEnabled()) {
138             _log.debug("Received " + requestURL);
139         }
140 
141         if (!isValidRequestURL(requestURL)) {
142             chain.doFilter(req, res);
143 
144             return;
145         }
146 
147         String contextPath = PortalUtil.getPathContext();
148 
149         String friendlyURL = httpReq.getRequestURI().toLowerCase();
150 
151         if ((!contextPath.equals(StringPool.SLASH)) &&
152             (friendlyURL.indexOf(contextPath) != -1)) {
153 
154             friendlyURL = friendlyURL.substring(
155                 contextPath.length(), friendlyURL.length());
156         }
157 
158         friendlyURL = StringUtil.replace(
159             friendlyURL, StringPool.DOUBLE_SLASH, StringPool.SLASH);
160 
161         if (_log.isDebugEnabled()) {
162             _log.debug("Friendly URL " + friendlyURL);
163         }
164 
165         if (!isValidFriendlyURL(friendlyURL)) {
166             chain.doFilter(req, res);
167 
168             return;
169         }
170 
171         LayoutSet layoutSet = (LayoutSet)req.getAttribute(
172             WebKeys.VIRTUAL_HOST_LAYOUT_SET);
173 
174         if (layoutSet != null) {
175             try {
176                 StringMaker prefix = new StringMaker();
177 
178                 if (layoutSet.isPrivateLayout()) {
179                     prefix.append(PortalUtil.getPathFriendlyURLPrivateGroup());
180                 }
181                 else {
182                     prefix.append(PortalUtil.getPathFriendlyURLPublic());
183                 }
184 
185                 Group group = GroupLocalServiceUtil.getGroup(
186                     layoutSet.getGroupId());
187 
188                 if (Validator.isNotNull(group.getFriendlyURL())) {
189                     prefix.append(group.getFriendlyURL());
190                 }
191                 else {
192                     prefix.append(
193                         group.getDefaultFriendlyURL(
194                             layoutSet.isPrivateLayout()));
195                 }
196 
197                 StringMaker redirect = new StringMaker();
198 
199                 redirect.append(prefix);
200                 redirect.append(friendlyURL);
201 
202                 String query = httpReq.getQueryString();
203 
204                 if (query != null) {
205                     redirect.append(StringPool.QUESTION);
206                     redirect.append(query);
207                 }
208 
209                 if (_log.isDebugEnabled()) {
210                     _log.debug("Redirect to " + redirect);
211                 }
212 
213                 RequestDispatcher rd =
214                     _ctx.getRequestDispatcher(redirect.toString());
215 
216                 rd.forward(req, res);
217 
218                 return;
219             }
220             catch (Exception e) {
221                 _log.error(e, e);
222             }
223         }
224 
225         chain.doFilter(req, res);
226     }
227 
228     public void destroy() {
229     }
230 
231     protected boolean isValidFriendlyURL(String friendlyURL) {
232         if (PortalInstances.isIgnorePath(friendlyURL) ||
233             friendlyURL.startsWith(
234                 PortalUtil.getPathFriendlyURLPrivateGroup()) ||
235             friendlyURL.startsWith(PortalUtil.getPathFriendlyURLPublic()) ||
236             friendlyURL.startsWith(
237                 PortalUtil.getPathFriendlyURLPrivateUser()) ||
238             friendlyURL.startsWith(_PATH_C) ||
239             friendlyURL.startsWith(_PATH_DELEGATE) ||
240             friendlyURL.startsWith(_PATH_HTML) ||
241             friendlyURL.startsWith(_PATH_IMAGE) ||
242             friendlyURL.startsWith(_PATH_LANGUAGE) ||
243             friendlyURL.startsWith(_PATH_SITEMAP_XML) ||
244             friendlyURL.startsWith(_PATH_SOFTWARE_CATALOG) ||
245             friendlyURL.startsWith(_PATH_WAP) ||
246             friendlyURL.startsWith(_PATH_WSRP)) {
247 
248             return false;
249         }
250 
251         int code = LayoutImpl.validateFriendlyURL(friendlyURL);
252 
253         if ((code > -1) &&
254             (code != LayoutFriendlyURLException.ENDS_WITH_SLASH)) {
255 
256             return false;
257         }
258 
259         return true;
260     }
261 
262     protected boolean isValidRequestURL(StringBuffer requestURL) {
263         if (requestURL == null) {
264             return false;
265         }
266 
267         String url = requestURL.toString();
268 
269         if (url.endsWith(_EXT_C) || url.endsWith(_EXT_CSS) ||
270             url.endsWith(_EXT_GIF) || url.endsWith(_EXT_IMAGE_COMPANY_LOGO) ||
271             url.endsWith(_EXT_ICO) || url.endsWith(_EXT_JS) ||
272             url.endsWith(_EXT_JPEG) || url.endsWith(_EXT_PORTAL_CSS_CACHED) ||
273             url.endsWith(_EXT_PORTAL_JAVASCRIPT_CACHED) ||
274             url.endsWith(_EXT_PORTAL_LAYOUT) ||
275             url.endsWith(_EXT_PORTAL_LOGIN) ||
276             url.endsWith(_EXT_PORTAL_LOGOUT) || url.endsWith(_EXT_PNG)) {
277 
278             return false;
279         }
280         else {
281             return true;
282         }
283     }
284 
285     private static Log _log = LogFactory.getLog(VirtualHostFilter.class);
286 
287     private static String _EXT_C = "/c";
288 
289     private static String _EXT_CSS = ".css";
290 
291     private static String _EXT_GIF = ".gif";
292 
293     private static String _EXT_IMAGE_COMPANY_LOGO = "/image/company_logo";
294 
295     private static String _EXT_ICO = ".ico";
296 
297     private static String _EXT_JS = ".js";
298 
299     private static String _EXT_JPEG = ".jpeg";
300 
301     private static String _EXT_PORTAL_CSS_CACHED = "/portal/css_cached";
302 
303     private static String _EXT_PORTAL_JAVASCRIPT_CACHED =
304         "/portal/javascript_cached";
305 
306     private static String _EXT_PORTAL_LAYOUT = "/portal/layout";
307 
308     private static String _EXT_PORTAL_LOGIN = "/portal/login";
309 
310     private static String _EXT_PORTAL_LOGOUT = "/portal/logout";
311 
312     private static String _EXT_PNG = ".png";
313 
314     private static String _PATH_C = "/c/";
315 
316     private static String _PATH_DELEGATE = "/delegate/";
317 
318     private static String _PATH_HTML = "/html/";
319 
320     private static String _PATH_IMAGE = "/image/";
321 
322     private static String _PATH_LANGUAGE = "/language/";
323 
324     private static String _PATH_SITEMAP_XML = "/sitemap.xml";
325 
326     private static String _PATH_SOFTWARE_CATALOG = "/software_catalog/";
327 
328     private static String _PATH_WAP = "/wap/";
329 
330     private static String _PATH_WSRP = "/wsrp/";
331 
332     private ServletContext _ctx;
333 
334 }