IQDiscoInfoHandler.java 22.1 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile: IQDiscoInfoHandler.java,v $
 * $Revision: 2859 $
 * $Date: 2005-09-22 02:30:39 -0300 (Thu, 22 Sep 2005) $
 *
6
 * Copyright (C) 2004-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.disco;
22 23 24 25

import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;
26 27 28
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.SessionManager;
import org.jivesoftware.openfire.XMPPServer;
29 30 31
import org.jivesoftware.openfire.cluster.ClusterEventListener;
import org.jivesoftware.openfire.cluster.ClusterManager;
import org.jivesoftware.openfire.cluster.NodeID;
32 33 34
import org.jivesoftware.openfire.handler.IQHandler;
import org.jivesoftware.openfire.user.UserManager;
import org.jivesoftware.openfire.user.UserNotFoundException;
35 36 37
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.cache.Cache;
import org.jivesoftware.util.cache.CacheFactory;
38
import org.xmpp.forms.DataForm;
39 40 41
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.PacketError;
42
import org.xmpp.resultsetmanagement.ResultSet;
43 44 45

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
46
import java.util.concurrent.CopyOnWriteArraySet;
47
import java.util.concurrent.locks.Lock;
48 49 50 51 52

/**
 * IQDiscoInfoHandler is responsible for handling disco#info requests. This class holds a map with
 * the main entities and the associated DiscoInfoProvider. We are considering the host of the
 * recipient JIDs as main entities. It's the DiscoInfoProvider responsibility to provide information
53 54
 * about the JID's name together with any possible requested node.
 * <p>
55 56 57 58 59 60 61 62 63 64
 * For example, let's have in the entities map the following entries: "localhost" and
 * "conference.localhost". Associated with each entry we have different DiscoInfoProviders. Now we
 * receive a disco#info request for the following JID: "room@conference.localhost" which is a disco
 * request for a MUC room. So IQDiscoInfoHandler will look for the DiscoInfoProvider associated
 * with the JID's host which in this case is "conference.localhost". Once we have located the
 * provider we will delegate to the provider the responsibility to provide the info specific to
 * the JID's name which in this case is "room". Among the information that a room could provide we
 * could find its identity and the features it supports (e.g. 'muc_passwordprotected',
 * 'muc_unmoderated', etc.). Finally, after we have collected all the information provided by the
 * provider we will add it to the reply. On the other hand, if no provider was found or the provider
65
 * has no information for the requested name/node then a not-found error will be returned.</p>
66 67 68
 *
 * @author Gaston Dombiak
 */
69
public class IQDiscoInfoHandler extends IQHandler implements ClusterEventListener {
70

71 72
    public static final String NAMESPACE_DISCO_INFO = "http://jabber.org/protocol/disco#info";
	private Map<String, DiscoInfoProvider> entities = new HashMap<String, DiscoInfoProvider>();
73 74
    private Set<String> localServerFeatures = new CopyOnWriteArraySet<String>();
    private Cache<String, Set<NodeID>> serverFeatures;
75
    private List<Element> serverIdentities = new ArrayList<Element>();
76
    private Map<String, DiscoInfoProvider> serverNodeProviders = new ConcurrentHashMap<String, DiscoInfoProvider>();
77 78
    private IQHandlerInfo info;

79 80
    private List<Element> anonymousUserIdentities = new ArrayList<Element>();
    private List<Element> registeredUserIdentities = new ArrayList<Element>();
81 82 83 84
    private List<String> userFeatures = new ArrayList<String>();

    public IQDiscoInfoHandler() {
        super("XMPP Disco Info Handler");
85
        info = new IQHandlerInfo("query", NAMESPACE_DISCO_INFO);
86 87 88 89
        // Initialize the user identity and features collections (optimization to avoid creating
        // the same objects for each response)
        Element userIdentity = DocumentHelper.createElement("identity");
        userIdentity.addAttribute("category", "account");
90 91 92 93
        userIdentity.addAttribute("type", "anonymous");
        anonymousUserIdentities.add(userIdentity);
        userIdentity = DocumentHelper.createElement("identity");
        userIdentity.addAttribute("category", "account");
94
        userIdentity.addAttribute("type", "registered");
95
        registeredUserIdentities.add(userIdentity);
96
        userFeatures.add(NAMESPACE_DISCO_INFO);
97 98
    }

99 100
    @Override
	public IQHandlerInfo getInfo() {
101 102 103
        return info;
    }

104 105
    @Override
	public IQ handleIQ(IQ packet) {
106 107 108 109 110 111 112 113 114 115
        // Create a copy of the sent pack that will be used as the reply
        // we only need to add the requested info to the reply if any otherwise add 
        // a not found error
        IQ reply = IQ.createResultIQ(packet);

        // Look for a DiscoInfoProvider associated with the requested entity.
        // We consider the host of the recipient JID of the packet as the entity. It's the 
        // DiscoInfoProvider responsibility to provide information about the JID's name together 
        // with any possible requested node.  
        DiscoInfoProvider infoProvider = getProvider(packet.getTo() == null ?
116
                XMPPServer.getInstance().getServerInfo().getXMPPDomain() : packet.getTo().getDomain());
117 118 119 120 121 122 123 124 125 126
        if (infoProvider != null) {
            // Get the JID's name
            String name = packet.getTo() == null ? null : packet.getTo().getNode();
            if (name == null || name.trim().length() == 0) {
                name = null;
            }
            // Get the requested node
            Element iq = packet.getChildElement();
            String node = iq.attributeValue("node");
            //String node = metaData.getProperty("query:node");
127

128 129 130 131 132 133 134
            // Check if we have information about the requested name and node
            if (infoProvider.hasInfo(name, node, packet.getFrom())) {
                reply.setChildElement(iq.createCopy());
                Element queryElement = reply.getChildElement();

                // Add to the reply all the identities provided by the DiscoInfoProvider
                Element identity;
135
                Iterator<Element> identities = infoProvider.getIdentities(name, node, packet.getFrom());
136
                while (identities.hasNext()) {
137
                    identity = identities.next();
138 139 140
                    identity.setQName(new QName(identity.getName(), queryElement.getNamespace()));
                    queryElement.add((Element)identity.clone());
                }
141

142
                // Add to the reply all the features provided by the DiscoInfoProvider
143 144 145 146 147
                Iterator<String> features = infoProvider.getFeatures(name, node, packet.getFrom());
                boolean hasDiscoInfoFeature = false;
                boolean hasDiscoItemsFeature = false;
                boolean hasResultSetManagementFeature = false;
                
148
                while (features.hasNext()) {
149 150 151 152 153 154 155 156 157
					final String feature = features.next();
					queryElement.addElement("feature").addAttribute("var", feature);
					if (feature.equals(NAMESPACE_DISCO_INFO)) {
						hasDiscoInfoFeature = true;
					} else if (feature.equals("http://jabber.org/protocol/disco#items")) {
						hasDiscoItemsFeature = true;
					} else if (feature.equals(ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT)) {
						hasResultSetManagementFeature = true;
					}
158 159
                }

160 161 162 163 164 165 166 167 168 169 170 171 172
				if (hasDiscoItemsFeature && !hasResultSetManagementFeature) {
					// IQDiscoItemsHandler provides result set management
					// support.
					queryElement.addElement("feature").addAttribute("var",
							ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT);
				}
                
                if (!hasDiscoInfoFeature) {
					// XEP-0030 requires that every entity that supports service
					// discovery broadcasts the disco#info feature.
					queryElement.addElement("feature").addAttribute("var", NAMESPACE_DISCO_INFO);
				}
                
173
                // Add to the reply the extended info (XDataForm) provided by the DiscoInfoProvider
174
                DataForm dataForm = infoProvider.getExtendedInfo(name, node, packet.getFrom());
175
                if (dataForm != null) {
176
                    queryElement.add(dataForm.getElement());
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
                }
            }
            else {
                // If the DiscoInfoProvider has no information for the requested name and node 
                // then answer a not found error
                reply.setChildElement(packet.getChildElement().createCopy());
                reply.setError(PacketError.Condition.item_not_found);
            }
        }
        else {
            // If we didn't find a DiscoInfoProvider then answer a not found error
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.item_not_found);
        }

        return reply;
    }

    /**
     * Sets the DiscoInfoProvider to use when a disco#info packet is sent to the server itself
     * and the specified node. For instance, if node matches "http://jabber.org/protocol/offline"
     * then a special DiscoInfoProvider should be use to return information about offline messages.
     *
     * @param node the node that the provider will handle.
     * @param provider the DiscoInfoProvider that will handle disco#info packets sent with the
     *        specified node.
     */
    public void setServerNodeInfoProvider(String node, DiscoInfoProvider provider) {
        serverNodeProviders.put(node, provider);
    }

    /**
     * Removes the DiscoInfoProvider to use when a disco#info packet is sent to the server itself
     * and the specified node.
     *
     * @param node the node that the provider was handling.
     */
    public void removeServerNodeInfoProvider(String node) {
        serverNodeProviders.remove(node);
    }

    /**
     * Returns the DiscoInfoProvider responsible for providing information about a given entity or
     * null if none was found.
     *
     * @param name the name of the identity.
     * @return the DiscoInfoProvider responsible for providing information about a given entity or
     *         null if none was found.
     */
    private DiscoInfoProvider getProvider(String name) {
        return entities.get(name);
    }

    /**
     * Sets that a given DiscoInfoProvider will provide information about a given entity. This
     * message must be used when new modules (e.g. MUC) are implemented and need to provide
     * information about them.
     *
     * @param name     the name of the entity.
     * @param provider the DiscoInfoProvider that will provide the entity's information.
     */
    protected void setProvider(String name, DiscoInfoProvider provider) {
        entities.put(name, provider);
    }

    /**
     * Removes the DiscoInfoProvider related to a given entity.
     *
     * @param name the name of the entity.
     */
    protected void removeProvider(String name) {
        entities.remove(name);
    }

    /**
     * Adds the features provided by the new service that implements the ServerFeaturesProvider
     * interface. This information will be used whenever a disco for information is made against
     * the server (i.e. the packet's target is the server).
     * Example of features are: jabber:iq:agents, jabber:iq:time, etc.
     *
     * @param provider the ServerFeaturesProvider that provides new server features.
     */
    private void addServerFeaturesProvider(ServerFeaturesProvider provider) {
        for (Iterator<String> it = provider.getFeatures(); it.hasNext();) {
261
            addServerFeature(it.next());
262 263 264
        }
    }

265 266 267 268 269 270
    /**
     * Adds one specific feature to the information returned whenever a disco for information is
     * made against the server.
     *
     * @param namespace the namespace identifying the new server feature.
     */
271 272
    public void addServerFeature(String namespace) {
        if (localServerFeatures.add(namespace)) {
273
            Lock lock = CacheFactory.getLock(namespace, serverFeatures);
274 275 276 277 278 279 280 281 282 283 284 285 286
            try {
                lock.lock();
                Set<NodeID> nodeIDs = serverFeatures.get(namespace);
                if (nodeIDs == null) {
                    nodeIDs = new HashSet<NodeID>();
                }
                nodeIDs.add(XMPPServer.getInstance().getNodeID());
                serverFeatures.put(namespace, nodeIDs);
            }
            finally {
                lock.unlock();
            }
        }
287 288 289 290 291 292 293 294 295
    }

    /**
     * Removes a feature from the information returned whenever a disco for information is
     * made against the server.
     *
     * @param namespace the namespace of the feature to be removed.
     */
    public void removeServerFeature(String namespace) {
296
        if (localServerFeatures.remove(namespace)) {
297
            Lock lock = CacheFactory.getLock(namespace, serverFeatures);
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
            try {
                lock.lock();
                Set<NodeID> nodeIDs = serverFeatures.get(namespace);
                if (nodeIDs != null) {
                    nodeIDs.remove(XMPPServer.getInstance().getNodeID());
                    if (nodeIDs.isEmpty()) {
                        serverFeatures.remove(namespace);
                    }
                    else {
                        serverFeatures.put(namespace, nodeIDs);
                    }
                }
            }
            finally {
                lock.unlock();
            }
        }
315 316
    }

317 318
    @Override
	public void initialize(XMPPServer server) {
319
        super.initialize(server);
320
        serverFeatures = CacheFactory.createCache("Disco Server Features");
321
        addServerFeature(NAMESPACE_DISCO_INFO);
322 323 324 325 326
        // Track the implementors of ServerFeaturesProvider so that we can collect the features
        // provided by the server
        for (ServerFeaturesProvider provider : server.getServerFeaturesProviders()) {
            addServerFeaturesProvider(provider);
        }
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
        // Collect the implementors of ServerIdentitiesProvider so that we can collect the identities
        // for protocols supported by the server
        for (ServerIdentitiesProvider provider : server.getServerIdentitiesProviders()) {
            for (Iterator<Element> it = provider.getIdentities(); it.hasNext();) {
                serverIdentities.add(it.next());
            }
        }
        // Collect the implementors of UserIdentitiesProvider so that we can collect identities
        // for registered users.
        for (UserIdentitiesProvider provider : server.getUserIdentitiesProviders()) {
            for (Iterator<Element> it = provider.getIdentities(); it.hasNext();) {
                registeredUserIdentities.add(it.next());
            }
        }

342
        setProvider(server.getServerInfo().getXMPPDomain(), getServerInfoProvider());
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
        // Listen to cluster events
        ClusterManager.addListener(this);
    }

    public void joinedCluster() {
        restoreCacheContent();
    }

    public void joinedCluster(byte[] nodeID) {
        // Do nothing
    }

    public void leftCluster() {
        if (!XMPPServer.getInstance().isShuttingDown()) {
            restoreCacheContent();
        }
    }

    public void leftCluster(byte[] nodeID) {
        if (ClusterManager.isSeniorClusterMember()) {
363
            NodeID leftNode = NodeID.getInstance(nodeID);
364 365 366
            // Remove server features added by node that is gone
            for (Map.Entry<String, Set<NodeID>> entry : serverFeatures.entrySet()) {
                String namespace = entry.getKey();
367
                Lock lock = CacheFactory.getLock(namespace, serverFeatures);
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
                try {
                    lock.lock();
                    Set<NodeID> nodeIDs = entry.getValue();
                    if (nodeIDs.remove(leftNode)) {
                        if (nodeIDs.isEmpty()) {
                            serverFeatures.remove(namespace);
                        }
                        else {
                            serverFeatures.put(namespace, nodeIDs);
                        }
                    }
                }
                finally {
                    lock.unlock();
                }
            }
        }
    }

    public void markedAsSeniorClusterMember() {
        // Do nothing
    }

    private void restoreCacheContent() {
        for (String feature : localServerFeatures) {
393
            Lock lock = CacheFactory.getLock(feature, serverFeatures);
394 395 396 397 398 399 400 401 402 403 404 405 406
            try {
                lock.lock();
                Set<NodeID> nodeIDs = serverFeatures.get(feature);
                if (nodeIDs == null) {
                    nodeIDs = new HashSet<NodeID>();
                }
                nodeIDs.add(XMPPServer.getInstance().getNodeID());
                serverFeatures.put(feature, nodeIDs);
            }
            finally {
                lock.unlock();
            }
        }
407 408 409 410 411 412 413 414 415 416
    }

    /**
     * Returns the DiscoInfoProvider responsible for providing information at the server level. This
     * means that this DiscoInfoProvider will provide information whenever a disco request whose
     * recipient JID is the server (e.g. localhost) is made.
     *
     * @return the DiscoInfoProvider responsible for providing information at the server level.
     */
    private DiscoInfoProvider getServerInfoProvider() {
417
        return new DiscoInfoProvider() {
418
            final ArrayList<Element> identities = new ArrayList<Element>();
419 420 421 422 423 424 425 426 427 428 429 430 431

            public Iterator<Element> getIdentities(String name, String node, JID senderJID) {
                if (node != null && serverNodeProviders.get(node) != null) {
                    // Redirect the request to the disco info provider of the specified node
                    return serverNodeProviders.get(node).getIdentities(name, node, senderJID);
                }
                if (name == null) {
                    // Answer identity of the server
                    synchronized (identities) {
                        if (identities.isEmpty()) {
                            Element identity = DocumentHelper.createElement("identity");
                            identity.addAttribute("category", "server");
                            identity.addAttribute("name", JiveGlobals.getProperty(
432
                                    "xmpp.server.name", "Openfire Server"));
433 434 435
                            identity.addAttribute("type", "im");

                            identities.add(identity);
436 437 438 439 440
                            
                            // Include identities from modules that implement ServerIdentitiesProvider
                            for (Element identityElement : serverIdentities) {
                                identities.add(identityElement);
                            }
441 442 443 444 445
                        }
                    }
                    return identities.iterator();
                }
                else {
446 447 448 449 450 451 452 453 454
                    if (SessionManager.getInstance().isAnonymousRoute(name)) {
                        // Answer identity of an anonymous user.
                        return anonymousUserIdentities.iterator();
                    }
                    else {
                        // Answer identity of a registered user.
                        // Note: We know that this user exists because #hasInfo returned true
                        return registeredUserIdentities.iterator();
                    }
455 456 457 458 459 460 461 462 463 464
                }
            }

            public Iterator<String> getFeatures(String name, String node, JID senderJID) {
                if (node != null && serverNodeProviders.get(node) != null) {
                    // Redirect the request to the disco info provider of the specified node
                    return serverNodeProviders.get(node).getFeatures(name, node, senderJID);
                }
                if (name == null) {
                    // Answer features of the server
465
                    return new HashSet<String>(serverFeatures.keySet()).iterator();
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
                }
                else {
                    // Answer features of the user
                    return userFeatures.iterator();
                }
            }

            public boolean hasInfo(String name, String node, JID senderJID) {
                if (node != null) {
                    if (serverNodeProviders.get(node) != null) {
                        // Redirect the request to the disco info provider of the specified node
                        return serverNodeProviders.get(node).hasInfo(name, node, senderJID);
                    }
                    // Unknown node
                    return false;
                }
                try {
483 484 485 486
                    // True if it is an info request of the server, a registered user or an
                    // anonymous user. We now support disco of user's bare JIDs
                    return name == null || UserManager.getInstance().getUser(name) != null ||
                            SessionManager.getInstance().isAnonymousRoute(name);
487 488 489 490 491 492
                }
                catch (UserNotFoundException e) {
                    return false;
                }
            }

493
            public DataForm getExtendedInfo(String name, String node, JID senderJID) {
494 495 496 497 498 499 500 501 502
                if (node != null && serverNodeProviders.get(node) != null) {
                    // Redirect the request to the disco info provider of the specified node
                    return serverNodeProviders.get(node).getExtendedInfo(name, node, senderJID);
                }
                return null;
            }
        };
    }
}