InterceptorManager.java 11.8 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: 3142 $
 * $Date: 2005-12-01 13:39:33 -0300 (Thu, 01 Dec 2005) $
 *
6
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
7
 *
8 9 10 11 12 13 14 15 16 17 18
 * 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.
19 20
 */

21
package org.jivesoftware.openfire.interceptor;
22

23 24 25 26
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
27 28 29
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

30 31 32 33 34 35
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.Packet;

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
/**
 * An InterceptorManager manages the list of global interceptors and per-user
 * interceptors that are invoked before and after packets are read and sent.
 * If an interceptor is installed for a user then it will receive all packets
 * sent or received for <b>any</b> connection of that user.<p>
 *
 * PacketInterceptors that are invoked before the packet is sent or processed
 * (when read) may change the original packet or reject the packet by throwing
 * a {@link PacketRejectedException}. If the interceptor rejects a received packet
 * then the sender of the packet receive a
 * {@link org.xmpp.packet.PacketError.Condition#not_allowed not_allowed} error.
 *
 * @see PacketInterceptor
 * @author Gaston Dombiak
 */
public class InterceptorManager {

53 54
	private static final Logger Log = LoggerFactory.getLogger(InterceptorManager.class);

55 56
    private static InterceptorManager instance = new InterceptorManager();

57
    private XMPPServer server = XMPPServer.getInstance();
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
    private List<PacketInterceptor> globalInterceptors =
            new CopyOnWriteArrayList<PacketInterceptor>();
    private Map<String, List<PacketInterceptor>> usersInterceptors =
            new ConcurrentHashMap<String, List<PacketInterceptor>>();

    /**
     * Returns a singleton instance of InterceptorManager.
     *
     * @return an instance of InterceptorManager.
     */
    public static InterceptorManager getInstance() {
        return instance;
    }

    /**
     * Returns an unmodifiable list of global packet interceptors. Global
     * interceptors are applied to all packets read and sent by the server.
     *
     * @return an unmodifiable list of the global packet interceptors.
     */
    public List<PacketInterceptor> getInterceptors() {
        return Collections.unmodifiableList(globalInterceptors);
    }

    /**
     * Inserts a new interceptor at the end of the list of currently configured
     * interceptors. This interceptor will be used for all the sent and received packets.
     *
     * @param interceptor the interceptor to add.
     */
    public void addInterceptor(PacketInterceptor interceptor) {
        if (interceptor == null) {
            throw new NullPointerException("Parameter interceptor was null.");
        }
        // Remove the interceptor from the list since the position might have changed
        if (globalInterceptors.contains(interceptor)) {
            globalInterceptors.remove(interceptor);
        }
        globalInterceptors.add(interceptor);
    }

    /**
     * Inserts a new interceptor at specified index in the list of currently configured
     * interceptors. This interceptor will be used for all the sent and received packets.
     *
     * @param index the index in the list to insert the new interceptor at.
     * @param interceptor the interceptor to add.
     */
    public void addInterceptor(int index, PacketInterceptor interceptor) {
        if (index < 0 || (index > globalInterceptors.size())) {
            throw new IndexOutOfBoundsException("Index " + index + " invalid.");
        }
        if (interceptor == null) {
            throw new NullPointerException("Parameter interceptor was null.");
        }
        // Remove the interceptor from the list since the position might have changed
        if (globalInterceptors.contains(interceptor)) {
            int oldIndex = globalInterceptors.indexOf(interceptor);
            if (oldIndex < index) {
                index -= 1;
            }
            globalInterceptors.remove(interceptor);
        }

        globalInterceptors.add(index, interceptor);
    }

    /**
     * Removes the global interceptor from the list.
     *
     * @param interceptor the interceptor to remove.
     * @return true if the item was present in the list
     */
    public boolean removeInterceptor(PacketInterceptor interceptor) {
        return globalInterceptors.remove(interceptor);
    }

    /**
     * Returns an unmodifable list of packet interceptors that are related to the
     * specified username.
     *
     * @param username the name of the user.
     * @return an unmodifiable list of packet interceptors that are related to
     *      the specified username.
     */
    public List<PacketInterceptor> getUserInterceptors(String username) {
        List<PacketInterceptor> userInterceptors = usersInterceptors.get(username);
        if (userInterceptors == null) {
            return Collections.emptyList();
        }
        else {
            return Collections.unmodifiableList(userInterceptors);
        }
    }

    /**
     * Inserts a new interceptor at specified index in the list of currently configured
     * interceptors for a specific username. This interceptor will be used only when a packet
     * was sent or received by the specified username.
     *
     * @param username the name of the user.
     * @param index the index in the list to insert the new interceptor at.
     * @param interceptor the interceptor to add.
     */
    public void addUserInterceptor(String username, int index, PacketInterceptor interceptor) {
        List<PacketInterceptor> userInterceptors = usersInterceptors.get(username);
        if (userInterceptors == null) {
            userInterceptors = new CopyOnWriteArrayList<PacketInterceptor>();
            usersInterceptors.put(username, userInterceptors);
        }
        else {
            if (index < 0 || (index > userInterceptors.size())) {
                throw new IndexOutOfBoundsException("Index " + index + " invalid.");
            }
            if (interceptor == null) {
                throw new NullPointerException("Parameter interceptor was null.");
            }

            // Remove the interceptor from the list since the position might have changed
            if (userInterceptors.contains(interceptor)) {
                int oldIndex = userInterceptors.indexOf(interceptor);
                if (oldIndex < index) {
                    index -= 1;
                }
                userInterceptors.remove(interceptor);
            }
        }
        userInterceptors.add(index, interceptor);
    }

    /**
     * Removes the interceptor from the list of interceptors that are related to a specific
     * username.
     *
     * @param username the name of the user.
     * @param interceptor the interceptor to remove.
     * @return true if the item was present in the list
     */
    public boolean removeUserInterceptor(String username, PacketInterceptor interceptor) {
        boolean answer = false;
        List<PacketInterceptor> userInterceptors = usersInterceptors.get(username);
        if (userInterceptors != null) {
            answer = userInterceptors.remove(interceptor);
            // Remove the entry for this username if the list is now empty
            if (userInterceptors.isEmpty()) {
                usersInterceptors.remove(username);
            }
        }
        return answer;
    }

    /**
     * Invokes all currently-installed interceptors on the specified packet.
     * All global interceptors will be invoked as well as interceptors that
     * are related to the address of the session that received or is sending
     * the packet.<p>
     *
     * Interceptors are executed before and after processing an incoming packet
     * and sending a packet to a user. This means that interceptors are able to alter or
     * reject packets before they are processed further. If possible, interceptors
     * should perform their work in a short time so that overall performance is not
     * compromised.
     *
     * @param packet the packet that has been read or is about to be sent.
     * @param session the session that received the packet or that the packet
     *      will be sent to.
     * @param read true indicates that the packet was read. When false, the packet
     *      is being sent to a user.
     * @param processed true if the packet has already processed (incoming or outgoing).
     *      If the packet hasn't already been processed, this flag will be false.
     * @throws PacketRejectedException if the packet should be prevented from being processed.
     */
    public void invokeInterceptors(Packet packet, Session session, boolean read, boolean processed)
            throws PacketRejectedException
    {
        // Invoke the global interceptors for this packet
        // Checking if collection is empty to prevent creating an iterator of
        // a CopyOnWriteArrayList that is an expensive operation
        if (!globalInterceptors.isEmpty()) {
            for (PacketInterceptor interceptor : globalInterceptors) {
                try {
                    interceptor.interceptPacket(packet, session, read, processed);
                }
                catch (PacketRejectedException e) {
                    if (processed) {
                        Log.error("Post interceptor cannot reject packet.", e);
                    }
                    else {
                        // Throw this exception since we don't really want to catch it
                        throw e;
                    }
                }
250
                catch (Throwable e) {
251
                    Log.error("Error in interceptor: " + interceptor + " while intercepting: " + packet, e);
252 253 254 255
                }
            }
        }
        // Invoke the interceptors that are related to the address of the session
256 257 258 259
        if (usersInterceptors.isEmpty()) {
            // Do nothing
            return;
        }
260
        String username = session.getAddress().getNode();
261
        if (username != null && server.isLocal(session.getAddress())) {
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
            Collection<PacketInterceptor> userInterceptors = usersInterceptors.get(username);
            if (userInterceptors != null && !userInterceptors.isEmpty()) {
                for (PacketInterceptor interceptor : userInterceptors) {
                    try {
                        interceptor.interceptPacket(packet, session, read, processed);
                    }
                    catch (PacketRejectedException e) {
                        if (processed) {
                            Log.error("Post interceptor cannot reject packet.", e);
                        }
                        else {
                            // Throw this exception since we don't really want to catch it
                            throw e;
                        }
                    }
277
                    catch (Throwable e) {
278
                        Log.error("Error in interceptor: " + interceptor + " while intercepting: " + packet, e);
279 280 281 282 283 284
                    }
                }
            }
        }
    }
}