WebDAVLiteServlet.java 14.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 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
/**
 * $Revision$
 * $Date$
 *
 * Copyright (C) 2008 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
 */
package org.jivesoftware.openfire.webdav;

import org.jivesoftware.util.Log;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.Base64;
import org.jivesoftware.openfire.auth.AuthFactory;
import org.jivesoftware.openfire.XMPPServer;
import org.xmpp.packet.JID;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletInputStream;
import java.io.*;

/**
 * Implements a very light WebDAV-ish servlet for specific purposes.  It does not support WebDAV extensions
 * to the HTTP protocol.  Instead, it supports the set of commands: GET, PUT, and DELETE.  This serves
 * as a WebDAV like storage interface for MUC shared files.  It handles part of XEP-0129: WebDAV File Transfers,
 * but not all of it.  We don't handle the PROPPATCH command, for example, as the user has no rights to set
 * the permissions on MUC shared files.
 *
 * TODO: How to handle a remote account?  As posed in the WebDAV XEP, we should send a message and wait for response.
 * TODO: How to handle SparkWeb?  Reasking for a username and password would suck.  Need some form of SSO.
 *    Maybe the SSO could be some special token provided during sign-on that the client could store and use
 *    for auth.
 *
 * @author Daniel Henninger
 */
public class WebDAVLiteServlet extends HttpServlet {

    // Storage directory under the Openfire install root
    private static String WEBDAV_SUBDIR = "mucFiles";

    /**
     * Retrieves a File object referring to a file in a service and room.  Leaving file as null
     * will get you the directory that would contain all of the files for a particular service and room.
     *
     * @param service Subdomain of the conference service we are forming a file path for.
     * @param room Conference room we are forming a file path for.
     * @param file Optional (can be null) filename for a path to a specific file (otherwise, directory).
     * @return The File reference constructed for the service, room, and file combination.
     */
    private File getFileReference(String service, String room, String file) {
        return new File(JiveGlobals.getHomeDirectory(), WEBDAV_SUBDIR+File.separator+service+File.separator+room+(file != null ? File.separator+file : ""));
    }
    
    /**
     * Verifies that the user is authenticated via some mechanism such as Basic Auth.  If the
     * authentication fails, this method will alter the HTTP response to include a request for
     * auth and send the unauthorized response back to the client.
     *
     * TODO: Handle some form of special token auth, perhaps provided a room connection?
     * TODO: If it's not a local account, we should try message auth access?  XEP-0070?
     * TODO: Should we support digest auth as well?
     *
     * @param request Object representing the HTTP request.
     * @param response Object representing the HTTP response.
     * @return True or false if the user is authenticated.
     * @throws ServletException If there was a servlet related exception.
     * @throws IOException If there was an IO error while setting the error.
     */
    private Boolean isAuthenticated(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String auth = request.getHeader("Authorization");
        JID jid;
        try {
            if (auth == null || !request.getAuthType().equals(HttpServletRequest.BASIC_AUTH)) {
                throw new Exception("No authorization or improper authorization provided.");
            }
            auth = auth.substring(auth.indexOf(" "));
            String decoded = new String(Base64.decode(auth));
            int i = decoded.indexOf(":");
            String username = decoded.substring(0,i);
            if (!username.contains("@")) {
                throw new Exception("Not a valid JID.");
            }
            jid = new JID(username);
            if (XMPPServer.getInstance().isLocal(jid)) {
                String password = decoded.substring(i+1, decoded.length());
                if (AuthFactory.authenticate(username, password) == null) {
                    throw new Exception("Authentication failed.");
                }
            }
            else {
                // TODO: Authenticate a remote user, probably via message auth.
                throw new Exception("Not a local account.");
            }
            return true;
        }
        catch (Exception e) {
            /**
             * This covers all possible authentication issues.  Eg:
             * - not enough of auth info passed in
             * - failed auth
             */
            response.setHeader("WWW-Authenticate", "Basic realm=\"Openfire WebDAV\"");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }

    /**
     * Verifies that the authenticated user is a member of a conference service and room, or else
     * they are not entitled to view any of the files in the room.
     *
     * @param request Object representing the HTTP request.
     * @param response Object representing the HTTP response.
     * @param service Subdomain of the conference service they are trying to access files for.
     * @param room Room in the conference service they are trying to access files for.
     * @return True or false if the user is authenticated.
     * @throws ServletException If there was a servlet related exception.
     * @throws IOException If there was an IO error while setting the error.
     */
    private Boolean isAuthorized(HttpServletRequest request, HttpServletResponse response,
                                 String service, String room) throws ServletException, IOException {
        String auth = request.getHeader("Authorization");
        JID jid;
        try {
            if (auth == null || !request.getAuthType().equals(HttpServletRequest.BASIC_AUTH)) {
                throw new Exception("No authorization or improper authorization provided.");
            }
            auth = auth.substring(auth.indexOf(" "));
            String decoded = new String(Base64.decode(auth));
            int i = decoded.indexOf(":");
            String username = decoded.substring(0,i);
            if (!username.contains("@")) {
                throw new Exception("Not a valid JID.");
            }
            jid = new JID(username);
            XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService(service).getChatRoom(room).getOccupantsByBareJID(jid.toBareJID());
            return true;
        }
        catch (Exception e) {
            /**
             * This covers all possible authorization issues.  Eg:
             * - accessing a room that doesn't exist
             * - accessing a room that user isn't a member of
             */
            response.setHeader("WWW-Authenticate", "Basic realm=\"Openfire WebDAV\"");
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
    }

    /**
     * Initialize the WebDAV servlet, auto-creating it's file root if it doesn't exist.
     *
     * @param servletConfig Configuration settings of the servlet from web.xml.
     * @throws ServletException If there was an exception setting up the servlet.
     */
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);
        File webdavDir = new File(JiveGlobals.getHomeDirectory(), WEBDAV_SUBDIR);
        if (!webdavDir.exists()) {
            webdavDir.mkdirs();
        }
    }

    /**
     * Handles a GET request for files or for a file listing.
     *
     * @param request Object representing the HTTP request.
     * @param response Object representing the HTTP response.
     * @throws ServletException If there was a servlet related exception.
     * @throws IOException If there was an IO error while setting the error.
     */
    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws
                ServletException, IOException {
        // Verify authentication
        if (!isAuthenticated(request, response)) return;

        String path = request.getPathInfo();
        Log.debug("WebDAVLiteServlet: GET with path = "+path);
        if (path == null || !path.startsWith("/rooms/")) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        String[] pathPcs = path.split("/");
        if (pathPcs.length < 4 || pathPcs.length > 5) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        String service = pathPcs[2];
        String room = pathPcs[3];

        // Verify authorization
        if (!isAuthorized(request, response, service, room)) return;
        
        if (pathPcs.length == 5) {
            // File retrieval
            String filename = pathPcs[4];
            File file = getFileReference(service, room, filename);
            Log.debug("WebDAVListServlet: File path = "+file.getAbsolutePath());
            Log.debug("WebDAVListServlet: Service = "+service+", room = "+room+", file = "+filename);
            if (file.exists()) {
                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType("application/octet-stream");
                response.setContentLength((int)file.length());
                FileInputStream fileStream = new FileInputStream(file);
                byte[] byteArray = new byte[(int)file.length()];
                new DataInputStream(fileStream).readFully(byteArray);
                fileStream.close();
                response.getOutputStream().write(byteArray);
            }
            else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        }
        else {
            // File listing
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("text/plain");
            response.setCharacterEncoding("utf-8");
            String content = "Files available for "+room+"@"+service+":\n";
            File fileDir = getFileReference(service, room, null);
            Log.debug("WebDAVListServlet: File path = "+fileDir.getAbsolutePath());
            if (fileDir.exists()) {
                File[] files = fileDir.listFiles();
                for (File file : files) {
                    content += file.getName()+"\n";
                }
            }
            response.getOutputStream().write(content.getBytes());
            Log.debug("WebDAVListServlet: Service = "+service+", room = "+room);
        }
    }

    /**
     * Handles a PUT request for uploading files.
     *
     * @param request Object representing the HTTP request.
     * @param response Object representing the HTTP response.
     * @throws ServletException If there was a servlet related exception.
     * @throws IOException If there was an IO error while setting the error.
     */
    @Override
    protected void doPut(HttpServletRequest request,
                         HttpServletResponse response) throws
                ServletException, IOException {
        // Verify authentication
        if (!isAuthenticated(request, response)) return;

        String path = request.getPathInfo();
        Log.debug("WebDAVLiteServlet: PUT with path = "+path);
        if (request.getContentLength() <= 0) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        if (path == null || !path.startsWith("/rooms/")) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        String[] pathPcs = path.split("/");
        if (pathPcs.length != 5) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        String service = pathPcs[2];
        String room = pathPcs[3];
        String filename = pathPcs[4];

        // Verify authorization
        if (!isAuthorized(request, response, service, room)) return;

        Log.debug("WebDAVListServlet: Service = "+service+", room = "+room+", file = "+filename);
        File file = getFileReference(service, room, filename);
        Boolean overwriteFile = file.exists();
        FileOutputStream fileStream = new FileOutputStream(file, false);
        ServletInputStream inputStream = request.getInputStream();
        byte[] byteArray = new byte[request.getContentLength()];
        int bytesRead = 0;
        while (bytesRead != -1) {
            bytesRead = inputStream.read(byteArray, bytesRead, request.getContentLength());   
        }
        fileStream.write(byteArray);
        fileStream.close();
        inputStream.close();
        if (overwriteFile) {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            response.setHeader("Location", request.getRequestURI());
        }
        else {
            response.setStatus(HttpServletResponse.SC_CREATED);
            response.setHeader("Location", request.getRequestURI());
        }
    }

    /**
     * Handles a DELETE request for deleting files.
     *
     * @param request Object representing the HTTP request.
     * @param response Object representing the HTTP response.
     * @throws ServletException If there was a servlet related exception.
     * @throws IOException If there was an IO error while setting the error.
     */
    @Override
    protected void doDelete(HttpServletRequest request,
                         HttpServletResponse response) throws
                ServletException, IOException {
        // Verify authentication
        if (!isAuthenticated(request, response)) return;
        
        String path = request.getPathInfo();
        Log.debug("WebDAVLiteServlet: DELETE with path = "+path);
        if (path == null || !path.startsWith("/rooms/")) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        String[] pathPcs = path.split("/");
        if (pathPcs.length != 5) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        String service = pathPcs[2];
        String room = pathPcs[3];
        String filename = pathPcs[4];

        // Verify authorization
        if (!isAuthorized(request, response, service, room)) return;

        Log.debug("WebDAVListServlet: Service = "+service+", room = "+room+", file = "+filename);
        File file = getFileReference(service, room, filename);
        if (file.exists()) {
            file.delete();
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
        else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

}