PluginServlet.java 22.7 KB
Newer Older
1 2 3 4
/**
 * $Revision: 3067 $
 * $Date: 2005-11-12 22:29:01 -0300 (Sat, 12 Nov 2005) $
 *
5
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
6
 *
7 8 9 10 11 12 13 14 15 16 17
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
18 19
 */

20
package org.jivesoftware.openfire.container;
21

22 23 24 25 26 27 28 29 30 31
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
32

33 34 35 36 37 38 39
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
40 41 42 43 44 45 46 47 48 49 50

import org.apache.jasper.JasperException;
import org.apache.jasper.JspC;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
51

52 53 54
/**
 * The plugin servlet acts as a proxy for web requests (in the admin console)
 * to plugins. Since plugins can be dynamically loaded and live in a different place
55
 * than normal Openfire admin console files, it's not possible to have them
56 57
 * added to the normal Openfire admin console web app directory.
 * <p>
58
 * The servlet listens for requests in the form <tt>/plugins/[pluginName]/[JSP File]</tt>
59 60 61 62
 * (e.g. <tt>/plugins/foo/example.jsp</tt>). It also listens for non JSP requests in the
 * form like <tt>/plugins/[pluginName]/images/*.png|gif</tt>,
 * <tt>/plugins/[pluginName]/scripts/*.js|css</tt> or
 * <tt>/plugins/[pluginName]/styles/*.css</tt> (e.g.
63 64
 * <tt>/plugins/foo/images/example.gif</tt>).
 * </p>
65 66 67 68 69 70 71 72 73 74
 * JSP files must be compiled and available via the plugin's class loader. The mapping
 * between JSP name and servlet class files is defined in [pluginName]/web/web.xml.
 * Typically, this file is auto-generated by the JSP compiler when packaging the plugin.
 * Alternatively, if development mode is enabled for the plugin then the the JSP file
 * will be dynamically compiled using JSPC.
 *
 * @author Matt Tucker
 */
public class PluginServlet extends HttpServlet {

75 76
	private static final Logger Log = LoggerFactory.getLogger(PluginServlet.class);

77 78 79 80 81 82 83
    private static Map<String, GenericServlet> servlets;
    private static PluginManager pluginManager;
    private static ServletConfig servletConfig;

    static {
        servlets = new ConcurrentHashMap<String, GenericServlet>();
    }
84 85
	
	public static final String PLUGINS_WEBROOT = "/plugins/";
86

87 88
    @Override
	public void init(ServletConfig config) throws ServletException {
89 90 91 92
        super.init(config);
        servletConfig = config;
    }

93 94
    @Override
	public void service(HttpServletRequest request, HttpServletResponse response)
95
        throws ServletException, IOException {
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
        else {
            try {
                // Handle JSP requests.
                if (pathInfo.endsWith(".jsp")) {
                    if (handleDevJSP(pathInfo, request, response)) {
                        return;
                    }
                    handleJSP(pathInfo, request, response);
                }
                // Handle servlet requests.
                else if (getServlet(pathInfo) != null) {
                    handleServlet(pathInfo, request, response);
                }
                // Handle image/other requests.
                else {
                    handleOtherRequest(pathInfo, response);
                }
            }
            catch (Exception e) {
119
                Log.error(e.getMessage(), e);
120 121 122 123 124 125 126 127 128
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        }
    }

    /**
     * Registers all JSP page servlets for a plugin.
     *
     * @param manager the plugin manager.
129 130 131
     * @param plugin the plugin.
     * @param webXML the web.xml file containing JSP page names to servlet class file
     *      mappings.
132 133 134 135 136
     */
    public static void registerServlets(PluginManager manager, Plugin plugin, File webXML) {
        pluginManager = manager;
        if (!webXML.exists()) {
            Log.error("Could not register plugin servlets, file " + webXML.getAbsolutePath() +
137
                " does not exist.");
138 139 140 141 142 143 144 145 146 147 148
            return;
        }
        // Find the name of the plugin directory given that the webXML file
        // lives in plugins/[pluginName]/web/web.xml
        String pluginName = webXML.getParentFile().getParentFile().getParentFile().getName();
        try {
            // Make the reader non-validating so that it doesn't try to resolve external
            // DTD's. Trying to resolve external DTD's can break on some firewall configurations.
            SAXReader saxReader = new SAXReader(false);
            try {
                saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",
149
                    false);
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
            }
            catch (SAXException e) {
                Log.warn("Error setting SAXReader feature", e);
            }
            Document doc = saxReader.read(webXML);
            // Find all <servlet> entries to discover name to class mapping.
            List classes = doc.selectNodes("//servlet");
            Map<String, Class> classMap = new HashMap<String, Class>();
            for (int i = 0; i < classes.size(); i++) {
                Element servletElement = (Element)classes.get(i);
                String name = servletElement.element("servlet-name").getTextTrim();
                String className = servletElement.element("servlet-class").getTextTrim();
                classMap.put(name, manager.loadClass(plugin, className));
            }
            // Find all <servelt-mapping> entries to discover name to URL mapping.
            List names = doc.selectNodes("//servlet-mapping");
            for (int i = 0; i < names.size(); i++) {
                Element nameElement = (Element)names.get(i);
                String name = nameElement.element("servlet-name").getTextTrim();
                String url = nameElement.element("url-pattern").getTextTrim();
                // Register the servlet for the URL.
                Class servletClass = classMap.get(name);
172 173 174 175
                if(servletClass == null) {
                    Log.error("Unable to load servlet, " + name + ", servlet-class not found.");
                    continue;
                }
176 177 178 179 180 181 182 183 184 185 186 187
                Object instance = servletClass.newInstance();
                if (instance instanceof GenericServlet) {
                    // Initialize the servlet then add it to the map..
                    ((GenericServlet)instance).init(servletConfig);
                    servlets.put(pluginName + url, (GenericServlet)instance);
                }
                else {
                    Log.warn("Could not load " + (pluginName + url) + ": not a servlet.");
                }
            }
        }
        catch (Throwable e) {
188
            Log.error(e.getMessage(), e);
189 190 191 192 193 194 195 196 197 198 199 200
        }
    }

    /**
     * Unregisters all JSP page servlets for a plugin.
     *
     * @param webXML the web.xml file containing JSP page names to servlet class file
     *               mappings.
     */
    public static void unregisterServlets(File webXML) {
        if (!webXML.exists()) {
            Log.error("Could not unregister plugin servlets, file " + webXML.getAbsolutePath() +
201
                " does not exist.");
202 203 204 205 206 207 208 209
            return;
        }
        // Find the name of the plugin directory given that the webXML file
        // lives in plugins/[pluginName]/web/web.xml
        String pluginName = webXML.getParentFile().getParentFile().getParentFile().getName();
        try {
            SAXReader saxReader = new SAXReader(false);
            saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",
210
                false);
211 212 213 214 215 216 217 218
            Document doc = saxReader.read(webXML);
            // Find all <servelt-mapping> entries to discover name to URL mapping.
            List names = doc.selectNodes("//servlet-mapping");
            for (int i = 0; i < names.size(); i++) {
                Element nameElement = (Element)names.get(i);
                String url = nameElement.element("url-pattern").getTextTrim();
                // Destroy the servlet than remove from servlets map.
                GenericServlet servlet = servlets.get(pluginName + url);
219 220 221
                if (servlet != null) {
                    servlet.destroy();
                }
222 223 224 225 226
                servlets.remove(pluginName + url);
                servlet = null;
            }
        }
        catch (Throwable e) {
227
            Log.error(e.getMessage(), e);
228 229 230
        }
    }

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

	/**
	 * Registers a live servlet for a plugin programmatically, does not
	 * initialize the servlet.
	 * 
	 * @param pluginManager the plugin manager
	 * @param plugin the owner of the servlet
	 * @param servlet the servlet.
	 * @param relativeUrl the relative url where the servlet should be bound
	 * @return the effective url that can be used to initialize the servlet
	 */
	public static String registerServlet(PluginManager pluginManager,
			Plugin plugin, GenericServlet servlet, String relativeUrl)
			throws ServletException {

		String pluginName = pluginManager.getPluginDirectory(plugin).getName();
		PluginServlet.pluginManager = pluginManager;
		if (servlet == null) {
			throw new ServletException("Servlet is missing");
		}
		String pluginServletUrl = pluginName + relativeUrl;
		servlets.put(pluginName + relativeUrl, servlet);
		return PLUGINS_WEBROOT + pluginServletUrl;
		
	}

	/**
	 * Unregister a live servlet for a plugin programmatically. Does not call
	 * the servlet destroy method.
	 * 
	 * @param plugin the owner of the servlet
262
	 * @param url the relative url where servlet has been bound
263 264 265 266 267 268 269 270 271 272 273 274 275
	 * @return the unregistered servlet, so that it can be destroyed
	 */
	public static GenericServlet unregisterServlet(Plugin plugin, String url)
			throws ServletException {
		String pluginName = pluginManager.getPluginDirectory(plugin).getName();
		if (url == null) {
			throw new ServletException("Servlet URL is missing");
		}
		String fullUrl = pluginName + url;
		GenericServlet servlet = servlets.remove(fullUrl);
		return servlet;
	}
    
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    /**
     * Handles a request for a JSP page. It checks to see if a servlet is mapped
     * for the JSP URL. If one is found, request handling is passed to it. If no
     * servlet is found, a 404 error is returned.
     *
     * @param pathInfo the extra path info.
     * @param request  the request object.
     * @param response the response object.
     * @throws ServletException if a servlet exception occurs while handling the request.
     * @throws IOException      if an IOException occurs while handling the request.
     */
    private void handleJSP(String pathInfo, HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {
        // Strip the starting "/" from the path to find the JSP URL.
        String jspURL = pathInfo.substring(1);

        GenericServlet servlet = servlets.get(jspURL);
        if (servlet != null) {
            servlet.service(request, response);
        }
        else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    /**
     * Handles a request for a Servlet. If one is found, request handling is passed to it.
     * If no servlet is found, a 404 error is returned.
     *
     * @param pathInfo the extra path info.
     * @param request  the request object.
     * @param response the response object.
     * @throws ServletException if a servlet exception occurs while handling the request.
     * @throws IOException      if an IOException occurs while handling the request.
     */
    private void handleServlet(String pathInfo, HttpServletRequest request,
                               HttpServletResponse response) throws ServletException, IOException {
        // Strip the starting "/" from the path to find the JSP URL.
        GenericServlet servlet = getServlet(pathInfo);
        if (servlet != null) {
            servlet.service(request, response);
        }
        else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    /**
     * Returns the correct servlet with mapping checks.
     *
     * @param pathInfo the pathinfo to map to the servlet.
     * @return the mapped servlet, or null if no servlet was found.
     */
    private GenericServlet getServlet(String pathInfo) {
        pathInfo = pathInfo.substring(1).toLowerCase();

        GenericServlet servlet = servlets.get(pathInfo);
        if (servlet == null) {
            for (String key : servlets.keySet()) {
                int index = key.indexOf("/*");
                String searchkey = key;
                if (index != -1) {
                    searchkey = key.substring(0, index);
                }
                if (searchkey.startsWith(pathInfo) || pathInfo.startsWith(searchkey)) {
                    servlet = servlets.get(key);
                    break;
                }
            }
        }
        return servlet;
    }


    /**
     * Handles a request for other web items (images, flash, applets, etc.)
     *
     * @param pathInfo the extra path info.
     * @param response the response object.
     * @throws IOException if an IOException occurs while handling the request.
     */
    private void handleOtherRequest(String pathInfo, HttpServletResponse response) throws IOException {
        String[] parts = pathInfo.split("/");
        // Image request must be in correct format.
        if (parts.length < 3) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        String contextPath = "";
        int index = pathInfo.indexOf(parts[1]);
        if (index != -1) {
            contextPath = pathInfo.substring(index + parts[1].length());
        }

        File pluginDirectory = new File(JiveGlobals.getHomeDirectory(), "plugins");
        File file = new File(pluginDirectory, parts[1] + File.separator + "web" + contextPath);

        // When using dev environment, the images dir may be under something other that web.
        Plugin plugin = pluginManager.getPlugin(parts[1]);
        PluginDevEnvironment environment = pluginManager.getDevEnvironment(plugin);

        if (environment != null) {
            file = new File(environment.getWebRoot(), contextPath);
        }
        if (!file.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        else {
            // Content type will be GIF or PNG.
            String contentType = "image/gif";
            if (pathInfo.endsWith(".png")) {
                contentType = "image/png";
            }
            else if (pathInfo.endsWith(".swf")) {
                contentType = "application/x-shockwave-flash";
            }
394 395 396 397 398 399
            else if (pathInfo.endsWith(".css")) {
                contentType = "text/css";
            }
            else if (pathInfo.endsWith(".js")) {
                contentType = "text/javascript";
            }
400 401 402
            else if (pathInfo.endsWith(".html") || pathInfo.endsWith(".htm")) {
                contentType = "text/html";
            }
403 404 405

            // setting the content-disposition header breaks IE when downloading CSS
            // response.setHeader("Content-disposition", "filename=\"" + file + "\";");
406
            response.setContentType(contentType);
407
            // Write out the resource to the user.
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
            InputStream in = null;
            ServletOutputStream out = null;
            try {
                in = new BufferedInputStream(new FileInputStream(file));
                out = response.getOutputStream();

                // Set the size of the file.
                response.setContentLength((int)file.length());

                // Use a 1K buffer.
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) != -1) {
                    out.write(buf, 0, len);
                }
            }
            finally {
                try {
                    in.close();
                }
                catch (Exception ignored) {
                    // Ignore.
                }
                try {
                    out.close();
                }
                catch (Exception ignored) {
                    // Ignore.
                }
            }
        }
    }


    /**
     * Handles a request for a JSP page in development mode. If development mode is
     * not enabled, this method returns false so that normal JSP handling can be performed.
     * If development mode is enabled, this method tries to locate the JSP, compile
     * it using JSPC, and then return the output.
     *
     * @param pathInfo the extra path info.
     * @param request  the request object.
     * @param response the response object.
     * @return true if this page request was handled; false if the request was not handled.
     */
    private boolean handleDevJSP(String pathInfo, HttpServletRequest request,
                                 HttpServletResponse response) {
        String jspURL = pathInfo.substring(1);

        // Handle pre-existing pages and fail over to pre-compiled pages.
        int fileSeperator = jspURL.indexOf("/");
        if (fileSeperator != -1) {
            String pluginName = jspURL.substring(0, fileSeperator);
            Plugin plugin = pluginManager.getPlugin(pluginName);

            PluginDevEnvironment environment = pluginManager.getDevEnvironment(plugin);
            // If development mode not turned on for plugin, return false.
            if (environment == null) {
                return false;
            }
            File webDir = environment.getWebRoot();
            if (webDir == null || !webDir.exists()) {
                return false;
            }

            File pluginDirectory = pluginManager.getPluginDirectory(plugin);

            File compilationDir = new File(pluginDirectory, "classes");
            compilationDir.mkdirs();

            String jsp = jspURL.substring(fileSeperator + 1);

            int indexOfLastSlash = jsp.lastIndexOf("/");
            String relativeDir = "";
            if (indexOfLastSlash != -1) {
                relativeDir = jsp.substring(0, indexOfLastSlash);
                relativeDir = relativeDir.replaceAll("//", ".") + '.';
            }

            File jspFile = new File(webDir, jsp);
            String filename = jspFile.getName();
            int indexOfPeriod = filename.indexOf(".");
            if (indexOfPeriod != -1) {
                filename = "dev" + StringUtils.randomString(4);
            }

            JspC jspc = new JspC();
            if (!jspFile.exists()) {
                return false;
            }
            try {
                jspc.setJspFiles(jspFile.getCanonicalPath());
            }
            catch (IOException e) {
502
                Log.error(e.getMessage(), e);
503 504 505 506 507 508 509 510 511 512 513
            }
            jspc.setOutputDir(compilationDir.getAbsolutePath());
            jspc.setClassName(filename);
            jspc.setCompile(true);

            jspc.setClassPath(getClasspathForPlugin(plugin));
            try {
                jspc.execute();

                try {
                    Object servletInstance = pluginManager.loadClass(plugin, "org.apache.jsp." +
514
                        relativeDir + filename).newInstance();
515 516 517 518 519 520
                    HttpServlet servlet = (HttpServlet)servletInstance;
                    servlet.init(servletConfig);
                    servlet.service(request, response);
                    return true;
                }
                catch (Exception e) {
521
                    Log.error(e.getMessage(), e);
522 523 524 525
                }

            }
            catch (JasperException e) {
526
                Log.error(e.getMessage(), e);
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
            }
        }
        return false;
    }

    /**
     * Returns the classpath to use for the JSPC Compiler.
     *
     * @param plugin the plugin the jspc will handle.
     * @return the classpath needed to compile a single jsp in a plugin.
     */
    private static String getClasspathForPlugin(Plugin plugin) {
        final StringBuilder classpath = new StringBuilder();

        File pluginDirectory = pluginManager.getPluginDirectory(plugin);

        PluginDevEnvironment pluginEnv = pluginManager.getDevEnvironment(plugin);

        PluginClassLoader pluginClassloader = pluginManager.getPluginClassloader(plugin);

547
        for (URL url : pluginClassloader.getURLs()) {
548 549 550 551 552 553 554 555 556 557 558 559 560 561
            File file = new File(url.getFile());

            classpath.append(file.getAbsolutePath()).append(";");
        }

        // Load all jars from lib
        File libDirectory = new File(pluginDirectory, "lib");
        File[] libs = libDirectory.listFiles();
        final int no = libs != null ? libs.length : 0;
        for (int i = 0; i < no; i++) {
            File libFile = libs[i];
            classpath.append(libFile.getAbsolutePath()).append(';');
        }

562 563
        File openfireRoot = pluginDirectory.getParentFile().getParentFile().getParentFile();
        File openfireLib = new File(openfireRoot, "target//lib");
564

565
        classpath.append(openfireLib.getAbsolutePath()).append("//servlet-api.jar;");
566 567 568
        classpath.append(openfireLib.getAbsolutePath()).append("//openfire.jar;");
        classpath.append(openfireLib.getAbsolutePath()).append("//jasper-compiler.jar;");
        classpath.append(openfireLib.getAbsolutePath()).append("//jasper-runtime.jar;");
569

570 571 572
        if (pluginEnv.getClassesDir() != null) {
            classpath.append(pluginEnv.getClassesDir().getAbsolutePath()).append(";");
        }
573 574 575
        return classpath.toString();
    }
}