RemoteServerManager.java 15.8 KB
Newer Older
1 2 3 4
/**
 * $Revision: $
 * $Date: $
 *
5
 * Copyright (C) 2005-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.server;
21

22 23 24 25 26 27
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

28
import org.jivesoftware.database.DbConnectionManager;
29 30 31
import org.jivesoftware.openfire.ConnectionManager;
import org.jivesoftware.openfire.SessionManager;
import org.jivesoftware.openfire.server.RemoteServerConfiguration.Permission;
32
import org.jivesoftware.openfire.session.ConnectionSettings;
33
import org.jivesoftware.openfire.session.Session;
34
import org.jivesoftware.util.JiveGlobals;
35 36
import org.jivesoftware.util.cache.Cache;
import org.jivesoftware.util.cache.CacheFactory;
37 38
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
39 40 41 42 43 44 45 46 47 48

/**
 * Manages the connection permissions for remote servers. When a remote server is allowed to
 * connect to this server then a special configuration for the remote server will be kept.
 * The configuration holds information such as the port to use when creating an outgoing connection.
 *
 * @author Gaston Dombiak
 */
public class RemoteServerManager {

49 50
	private static final Logger Log = LoggerFactory.getLogger(RemoteServerManager.class);

51
    private static final String ADD_CONFIGURATION =
52
        "INSERT INTO ofRemoteServerConf (xmppDomain,remotePort,permission) VALUES (?,?,?)";
53
    private static final String DELETE_CONFIGURATION =
54
        "DELETE FROM ofRemoteServerConf WHERE xmppDomain=?";
55
    private static final String LOAD_CONFIGURATION =
56
        "SELECT remotePort,permission FROM ofRemoteServerConf where xmppDomain=?";
57
    private static final String LOAD_CONFIGURATIONS =
58
        "SELECT xmppDomain,remotePort FROM ofRemoteServerConf where permission=?";
59

60 61 62 63 64 65
    private static Cache configurationsCache;

    static {
        configurationsCache = CacheFactory.createCache("Remote Server Configurations");
    }

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
    /**
     * Allows a remote server to connect to the local server with the specified configuration.
     *
     * @param configuration the configuration for the remote server.
     */
    public static void allowAccess(RemoteServerConfiguration configuration) {
        // Remove any previous configuration for this remote server
        deleteConfiguration(configuration.getDomain());
        // Update the database with the new granted permission and configuration
        configuration.setPermission(Permission.allowed);
        addConfiguration(configuration);
    }

    /**
     * Blocks a remote server from connecting to the local server. If the remote server was
     * connected when the permission was revoked then the connection of the entity will be closed.
     *
     * @param domain the domain of the remote server that is not allowed to connect.
     */
    public static void blockAccess(String domain) {
        // Remove any previous configuration for this remote server
        deleteConfiguration(domain);
        // Update the database with the new revoked permission
        RemoteServerConfiguration config = new RemoteServerConfiguration(domain);
        config.setPermission(Permission.blocked);
        addConfiguration(config);
        // Check if the remote server was connected and proceed to close the connection
        for (Session session : SessionManager.getInstance().getIncomingServerSessions(domain)) {
94
            session.close();
95 96 97
        }
        Session session = SessionManager.getInstance().getOutgoingServerSession(domain);
        if (session != null) {
98
            session.close();
99 100 101 102 103 104 105 106 107 108 109 110 111 112
        }
    }

    /**
     * Returns true if the remote server with the specified domain can connect to the
     * local server.
     *
     * @param domain the domain of the remote server.
     * @return true if the remote server with the specified domain can connect to the
     *         local server.
     */
    public static boolean canAccess(String domain) {
        // If s2s is disabled then it is not possible to send packets to remote servers or
        // receive packets from remote servers
113
        if (!JiveGlobals.getBooleanProperty(ConnectionSettings.Server.SOCKET_ACTIVE, true)) {
114 115 116 117 118 119 120 121 122 123 124 125 126
            return false;
        }

        // By default there is no permission defined for the XMPP entity
        Permission permission = null;

        RemoteServerConfiguration config = getConfiguration(domain);
        if (config != null) {
            permission = config.getPermission();
        }

        if (PermissionPolicy.blacklist == getPermissionPolicy()) {
            // Anyone can access except those entities listed in the blacklist
127
            return Permission.blocked != permission;
128 129 130
        }
        else {
            // Access is limited to those present in the whitelist
131
            return Permission.allowed == permission;
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
        }
    }

    /**
     * Returns the list of registered remote servers that are allowed to connect to/from this
     * server when using a whitelist policy. However, when using a blacklist policy (i.e. anyone
     * may connect to the server) the returned list of configurations will be used for obtaining
     * the specific connection configuration for each remote server.
     *
     * @return the configuration of the registered external components.
     */
    public static Collection<RemoteServerConfiguration> getAllowedServers() {
        return getConfigurations(Permission.allowed);
    }

    /**
     * Returns the list of remote servers that are NOT allowed to connect to/from this
     * server.
     *
     * @return the configuration of the blocked external components.
     */
    public static Collection<RemoteServerConfiguration> getBlockedServers() {
        return getConfigurations(Permission.blocked);
    }

    /**
     * Returns the number of milliseconds to wait to connect to a remote server or read
     * data from a remote server. Default timeout value is 20 seconds. Configure the
     * <tt>xmpp.server.read.timeout</tt> global property to override the default value.
     *
     * @return the number of milliseconds to wait to connect to a remote server or read
     *         data from a remote server.
     */
    public static int getSocketTimeout() {
166
        return JiveGlobals.getIntProperty(ConnectionSettings.Server.SOCKET_READ_TIMEOUT, 120000);
167 168 169 170 171 172 173 174 175
    }

    /**
     * Removes any existing defined permission and configuration for the specified
     * remote server.
     *
     * @param domain the domain of the remote server.
     */
    public static void deleteConfiguration(String domain) {
176 177
        // Remove configuration from cache
        configurationsCache.remove(domain);
178 179 180 181 182 183 184 185 186 187
        // Remove the permission for the entity from the database
        java.sql.Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(DELETE_CONFIGURATION);
            pstmt.setString(1, domain);
            pstmt.executeUpdate();
        }
        catch (SQLException sqle) {
188
            Log.error(sqle.getMessage(), sqle);
189 190
        }
        finally {
191
            DbConnectionManager.closeConnection(pstmt, con);
192 193 194 195 196
        }
    }

    /**
     * Adds a new permission for the specified remote server.
197 198
     *
     * @param configuration the new configuration for a remote server
199 200
     */
    private static void addConfiguration(RemoteServerConfiguration configuration) {
201 202
        // Remove configuration from cache
        configurationsCache.put(configuration.getDomain(), configuration);
203 204 205 206 207 208 209 210 211 212 213 214
        // Remove the permission for the entity from the database
        java.sql.Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(ADD_CONFIGURATION);
            pstmt.setString(1, configuration.getDomain());
            pstmt.setInt(2, configuration.getRemotePort());
            pstmt.setString(3, configuration.getPermission().toString());
            pstmt.executeUpdate();
        }
        catch (SQLException sqle) {
215
            Log.error(sqle.getMessage(), sqle);
216 217
        }
        finally {
218
            DbConnectionManager.closeConnection(pstmt, con);
219 220 221 222 223 224 225 226 227 228
        }
    }

    /**
     * Returns the configuration for a remote server or <tt>null</tt> if none was found.
     *
     * @param domain the domain of the remote server.
     * @return the configuration for a remote server or <tt>null</tt> if none was found.
     */
    public static RemoteServerConfiguration getConfiguration(String domain) {
229 230 231 232 233 234 235 236
        Object value = configurationsCache.get(domain);
        if ("null".equals(value)) {
            return null;
        }
        RemoteServerConfiguration configuration = (RemoteServerConfiguration) value;
        if (configuration == null) {
            java.sql.Connection con = null;
            PreparedStatement pstmt = null;
237
            ResultSet rs = null;
238 239 240 241
            try {
                con = DbConnectionManager.getConnection();
                pstmt = con.prepareStatement(LOAD_CONFIGURATION);
                pstmt.setString(1, domain);
242
                rs = pstmt.executeQuery();
243 244 245 246 247 248 249
                while (rs.next()) {
                    configuration = new RemoteServerConfiguration(domain);
                    configuration.setRemotePort(rs.getInt(1));
                    configuration.setPermission(Permission.valueOf(rs.getString(2)));
                }
            }
            catch (SQLException sqle) {
250
                Log.error(sqle.getMessage(), sqle);
251 252
            }
            finally {
253
                DbConnectionManager.closeConnection(rs, pstmt, con);
254 255 256 257 258 259
            }
            if (configuration != null) {
                configurationsCache.put(domain, configuration);
            }
            else {
                configurationsCache.put(domain, "null");
260 261 262 263 264 265 266 267 268 269 270
            }
        }
        return configuration;
    }

    private static Collection<RemoteServerConfiguration> getConfigurations(
            Permission permission) {
        Collection<RemoteServerConfiguration> answer =
                new ArrayList<RemoteServerConfiguration>();
        java.sql.Connection con = null;
        PreparedStatement pstmt = null;
271
        ResultSet rs = null;
272 273 274 275
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(LOAD_CONFIGURATIONS);
            pstmt.setString(1, permission.toString());
276
            rs = pstmt.executeQuery();
277 278 279 280 281 282 283 284 285
            RemoteServerConfiguration configuration;
            while (rs.next()) {
                configuration = new RemoteServerConfiguration(rs.getString(1));
                configuration.setRemotePort(rs.getInt(2));
                configuration.setPermission(permission);
                answer.add(configuration);
            }
        }
        catch (SQLException sqle) {
286
            Log.error(sqle.getMessage(), sqle);
287 288
        }
        finally {
289
            DbConnectionManager.closeConnection(rs, pstmt, con);
290 291 292 293 294 295 296 297 298 299 300 301
        }
        return answer;
    }

    /**
     * Returns the remote port to connect for the specified remote server. If no port was
     * defined then use the default port (e.g. 5269).
     *
     * @param domain the domain of the remote server to get the remote port to connect to.
     * @return the remote port to connect for the specified remote server.
     */
    public static int getPortForServer(String domain) {
302
        int port = JiveGlobals.getIntProperty(ConnectionSettings.Server.REMOTE_SERVER_PORT, ConnectionManager.DEFAULT_SERVER_PORT);
303 304 305 306
        RemoteServerConfiguration config = getConfiguration(domain);
        if (config != null) {
            port = config.getRemotePort();
            if (port == 0) {
307
                port = JiveGlobals
308
                        .getIntProperty(ConnectionSettings.Server.REMOTE_SERVER_PORT, ConnectionManager.DEFAULT_SERVER_PORT);
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
            }
        }
        return port;
    }

    /**
     * Returns the permission policy being used for new XMPP entities that are trying to
     * connect to the server. There are two types of policies: 1) blacklist: where any entity
     * is allowed to connect to the server except for those listed in the black list and
     * 2) whitelist: where only the entities listed in the white list are allowed to connect to
     * the server.
     *
     * @return the permission policy being used for new XMPP entities that are trying to
     *         connect to the server.
     */
    public static PermissionPolicy getPermissionPolicy() {
        try {
326
            return PermissionPolicy.valueOf(JiveGlobals.getProperty(ConnectionSettings.Server.PERMISSION_SETTINGS,
327 328 329
                    PermissionPolicy.blacklist.toString()));
        }
        catch (Exception e) {
330
            Log.error(e.getMessage(), e);
331 332 333 334 335 336 337 338 339 340 341 342 343 344
            return PermissionPolicy.blacklist;
        }
    }

    /**
     * Sets the permission policy being used for new XMPP entities that are trying to
     * connect to the server. There are two types of policies: 1) blacklist: where any entity
     * is allowed to connect to the server except for those listed in the black list and
     * 2) whitelist: where only the entities listed in the white list are allowed to connect to
     * the server.
     *
     * @param policy the new PermissionPolicy to use.
     */
    public static void setPermissionPolicy(PermissionPolicy policy) {
345
        JiveGlobals.setProperty(ConnectionSettings.Server.PERMISSION_SETTINGS, policy.toString());
346 347 348
        // Check if the connected servers can remain connected to the server
        for (String hostname : SessionManager.getInstance().getIncomingServers()) {
            if (!canAccess(hostname)) {
349 350
                for (Session session : SessionManager.getInstance().getIncomingServerSessions(hostname)) {
                    session.close();
351 352 353 354 355 356
                }
            }
        }
        for (String hostname : SessionManager.getInstance().getOutgoingServers()) {
            if (!canAccess(hostname)) {
                Session session = SessionManager.getInstance().getOutgoingServerSession(hostname);
357
                session.close();
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
            }
        }
    }

    /**
     * Sets the permission policy being used for new XMPP entities that are trying to
     * connect to the server. There are two types of policies: 1) blacklist: where any entity
     * is allowed to connect to the server except for those listed in the black list and
     * 2) whitelist: where only the entities listed in the white list are allowed to connect to
     * the server.
     *
     * @param policy the new policy to use.
     */
    public static void setPermissionPolicy(String policy) {
        setPermissionPolicy(PermissionPolicy.valueOf(policy));
    }

    public enum PermissionPolicy {
        /**
         * Any XMPP entity is allowed to connect to the server except for those listed in
         * the <b>not allowed list</b>.
         */
        blacklist,

        /**
         * Only the XMPP entities listed in the <b>allowed list</b> are able to connect to
         * the server.
         */
        whitelist;
    }
}